Time limit to serve

Question: Is there a time limit within which you have to serve the ball?
I experienced a strange game where one of the players just turned his back (as he was about to serve) to his opponent and said you took too long to serve. Everyone around me said to replay the point.
Was this correct as he "wasn't ready" or is this the server's point as he composed himself before serving?
It was an odd situation and I can't find any official rules about it.
Comment: I want to add the comment that I think this situation should be addressed specifically in the rules, even if it says that it's up to the umpire to determine if the server is intentionally delaying the game by taking too long to serve, or alternatively, if the receiver is maybe over-reacting.
Answer: The ITTF handbook says the following:

3.4.4 Intervals
220.127.116.11 Play shall be continuous throughout an individual match except that any player is entitled to:
188.8.131.52.1 an interval of up to 1 minute between successive games of an individual match;
188.8.131.52.2 brief intervals for towelling after every 6 points from the start of each game and at the change of ends in the last possible game of an individual match.

(emphasis mine)
So, yes, there is a time limit, but not a specified one. This is basically decided by the umpire; if he/she thinks a player is taking too long to serve, a warning can be issued.
Comment: please correct me if i am wrong. By these rules the point should have been awarded to the server and the player can't just decide to stop the point because he feels the server is taking too long. He should express his concern to the umpire? and if the umpire agrees he can issue a warning? i should point out he had already had a 1 minute break and was ready to recieve*
Comment: I've never played a competitive table tennis match, but that's how it goes in all major sports.
Answer: As an umpire and a player, I've never encountered this scenario, but I can see where it might occur.
The play should have been called a let and replayed:
22.214.171.124 if the service is delivered when the receiving player or pair is not ready,
provided that neither the receiver nor his or her partner attempts to strike
the ball;
If you served and the player made no attempt to return the serve and claimed that you took too long, it could be argued that it should be played as a let.
The rule was actually meant more for when a player serves when the receiver is clearly not ready to receive, but if you make an attempt to return the serve, you cannot call a let.  This has happened to me personally many times because I am legally blind (no peripheral vision) and I am focused upon getting ready to get in my stance/position but the server sometimes will not look at me to confirm, with eye contact, that I'm ready and serve before I am set.
That doesn't appear to be what happened in this case, but the idea is the same.  If your opponent attempted to return your serve, but claimed you took too long, too bad on his/her part, it's your point.  If they did not attempt to return the serve, it's a let.

Time limit to serve


Como listar cada Collation name com seu charset - Firebird 2.5

Question: Quero fazer uma consulta envolvendo RDB$Character_Sets, RDB$Collations e RDB$Fields de forma a obter uma lista de "Fields" com os respectivos RDB$Character_Set_Name e RDB$Collation_Name.
Instrução SQL utilizada:
 select distinct
        Fields    .RDB$Field_Name        ,
        CharSets  .RDB$Character_Set_Name,
        Collations.RDB$Collation_Name
 from
        RDB$Character_Sets as CharSets  ,
        RDB$Collations     as Collations,
        RDB$Fields         as Fields
 where
     CharSets  .RDB$Character_Set_Id = Collations.RDB$Character_Set_Id and
     Fields    .RDB$Character_Set_Id = CharSets  .RDB$Character_Set_Id
 order by
                        Fields    .RDB$Field_Name

Resultado obtido:
 RDB$Field_Name   RDB$Character_Set_Name   RDB$Collation_Name
 --------------   ----------------------   ------------------
 RDB$10           UTF8                     UCS_BASIC
 RDB$10           UTF8                     UNICODE
 RDB$10           UTF8                     UNICODE_CI
 RDB$10           UTF8                     UNICODE_CI_AI
 ...              ...                      ...

Ou seja, tem uma linha para cada RDB$Collation_Name. Como fazer para que cada RDB$Character_Set_Name, tenha o correspondente RDB$Collation_Name e somente ele,
reduzindo para uma única linha para cada RDB$Field_Name? Grato.
Comment: Uma forma eficaz seria utilizar o group by, mas nos testes que eu fiz aqui os resultados não foram satisfatórios.
Comment: Rapha, exponha visualmente como você deseja que seus resultados apareçam. O problema é que cada charset tem vários 'collations';
Comment: Olá Fabrício. Isso foi feito no corpo da questão: tem uma representação visual de como ñ quero que apareçam em "Resultado obtido". Embaixo tem um texto esclarecendo como quero q apareçam (cada Field_Name com seu respectivo e único Char_Set_Name e Collation_Name). Veja tbm a resposta que dei à questão. No meu teste deu certo.
Answer: Após analisar melhor as tabelas RDB$Character_Sets, RDB$Collations e RDB$Fields constatei que a identificação unívoca entre o "Character Set" e o "Collation", se encontra na tabela "RDB$Collations", onde constam os campos "RDB$Character_Set_Id" e "RDB$Collation_Id". Por sua vez a tabela "RDB$Fields", tem também estas colunas, portanto, a cláusula "Where" tem que limitar por estas colunas associando "RDB$Fields" a "RDB$Collations" em RDB$Character_Set_Id e "RDB$Collation_Id". O "RDB$Collation_Name" é obtido da tabela "RDB$Collations" e o "RDB$Character_Set_Name" é obtido da tabela "RDB$Character_Sets" onde o "RDB$Fields.RDB$Character_Set_Id" = "RDB$Character_Sets.RDB$Character_Set_Id".
Assim, a cláusula "Where" fica:
CharSets.RDB$Character_Set_Id = Collations.RDB$Character_Set_Id and
Fields  .RDB$Character_Set_Id = Collations.RDB$Character_Set_Id and
Fields  .RDB$Collation_Id     = Collations.RDB$Collation_Id

Espero ter colaborado.


Form submit is not firing on large form

Question: I have an old D6 site. I created a form with hook_form with very many fields (197 rows * 6 columns = 1182 fields). It works good and form submit works properly.
But when I add a new, 7th column to the form and the fields number becomes 1379 the form submit is not firing.
I do not see any errors or warnings, php memoty limit is set to 256M and post max size too. But submit handler simple does not fire.
What can be a cause?
Comment: Can you add at least some excerpts from your hook implementation and the submit handler?
Comment: Sounds like you need to increase `max_input_vars`
Answer: Increase max_input_vars in your PHP environment as Clive suggested in the comment.
Another indication of this problem is the form validate handler won't trigger either. Unless you have E_WARNING set in the php.ini error_reporting setting the form will silently fail and run the form hook again.

Form submit is not firing on large form


Getting back into music after a long hiatus

Question: A little background:  In high school, I was first chair tenor saxophone all four years in the school's top wind symphony section, and even played in the honors district band. I did jazz band both in high school and with my buddies, transcribing Dave Brubeck and Stan Getz pieces whenever I had the time. Whatever issues I sometimes had with technicality, I made up twice as much in tone and dynamics. I cherished all the hours spent playing, and tried playing a lot outside of band practice in school.
Fast forward many years later: today, I'm wrapping up my college degree in mathematics. Due to my 2-3 hour commute each day, and the heavy workload, it was easy for me to stop playing. I haven't regularly played in years, though I still have my saxophone (and it's a very, very good one). Whenever I'm driving in my car listening to jazz music, I can't help but fall in love with the same sound that captivated my life when I was 9 years old.
I'm sort of "afraid" to pick up the horn again. I remember most fingerings, and I'm pretty sure I could still read sheet music- though my syncopation could use a lot of work.  I am determined to begin playing music again, though, and I would like to someday begin performing with a band in local jazz bars.
I am not naive- I know that this "someday" is going to be quite some time from now, which leads to my question: how should one like myself get back into playing saxophone? What exercises do you recommend I focus on? For those who have taken long hiatuses from playing music: what was the toughest aspect of getting back into playing?
This question is open to any musician, saxophonist or not. Thank you in advance!
Answer: As one gets older, time becomes an important commodity. Youngsters appear to have all the time in the world, but as we get older, that time gets filled with so many things - wife, home, kids, work, getting to work, sleeping after a hard days work, the list is as exhaustive as the life we lead !
Sounds like your time spent studying is over, so don't let anything else fill it, till the playing has taken a hold again.Yes, a job may rear its ugly head, to fill that space, but put some of that 'borrowed time' away for practising and playing.
It's like riding a bike - you never forget, but you may fall off a few times before it all comes back - and it usually does. The embouchure and fingering should be quick to return, as you seem to have been playing some challenging stuff before. The reading may take a little longer.
Revisit all the first things you did as a 9 yr old - scales, arpeggios, simple stuff. If the sax hasn't been touched in ? yrs, it won't go amiss to give it a quick overhaul. After a few weeks or months, find a jam session, or look up the guys you used to play with - some of them will be in the same position as you - finished studying, looking forward to going back to one of their first loves, music.
In the final analysis, what do you have to lose, against gain ? Go for it !!
Comment: "The embouchure ... should be quick to return": this reminds me of the time when I picked up the trumpet and French horn in my mid 20s to join a small brass band comprising mostly pre-teens and two older adults.  One of the older players couldn't understand why I was tiring so quickly: he also played trumpet only in the summertime and had no trouble with his embouchure.  I kept trying to tell him that his experience and mine were not comparable because, unlike him, I hadn't played trumpet year round for the latter half of my childhood, but to no avail.
Answer: First thing to do is fall in love with your horn again.  Take it to a shop, get it tuned up, find a reed you like.  Then go back and listen to the sax players you really love and start comping along with them.  Just long tones, roots, arpeggios, little figures.
Don't spend more than 15 minutes at a time doing this at first, do it multiple times a day if you can.  You have to build up your embouchure again and you want to look forward to your next session. Your mind will start relearning and re-remembering stuff even when you're not playing.  You'll fall in love again and will go to sleep thinking about your old lover who has returned.
Store your horn somewhere in your living space, out of the case, ready to play, with a reed in the mouthpiece.  Have it ready to play at all times.  Whenever you're bored or waiting for something or just walking by, pick up your horn and play with it a bit.
Now that you're in love again, you need to work on the relationship. As you play, you'll find the areas that you need to work on. Figure out a way to practice that's actually performance and figure out a way to play for a total of at least 30 minutes a day, every day, even if it's broken up into 5 minute chunks.
So, for example if you're studying chord inversions and substitutions, rather than drill through them all, play along with a recording of some standard with a lead sheet for that standard. Then set yourself challenges based on that music:

Comping
Chord substitutions
Tone
Circular breathing
Figures transposed into all possible ii-V7 chord changes
...

When you study lead techniques, get something like Band in a Box or some kind of Music Minus One recording and solo over it, practicing your lead techniques.  If you don't use one of these tools, then get a drum machine or software to play at your practice tempo.  Steady tempo tends to be a big challenge for lead players.
As soon as you can, start jamming with other musicians who are above your current level.  I had only been learning to play guitar for a month when I started going to a weekly living room jam with musicians who were much better than me.  They taught me a lot and I had a major motivation to practice because I wanted these folks to like what I was doing.
Life is short. Have fun.
Answer: I'm an old pro, who like most people go in and out of good practice routines. when I try to get back into it I practice at first for 30 mins per day and build to two hours. I do this:
1, 10% long tones,
2, 10 reading,
3, 10 % transposition-pick a favorite standard and learn it in all 12 keys,
4, 70% patterns in all keys.
Hope this helps.
Don't forget to listen to lots of music by your most loved players.
Good luck!
Comment: I don't understand why this was downvoted.  It's truly great advice: be disciplined about starting slowly and about having a regular routine, and cultivate your inspiration to pursue your musical goals by listening to music that moves you.  A concise and inspiring answer.  +1 from me.


Reusing a JPanel in NetBeans GUI Designer

Question: This is in NetBeans 6.5, Java 6.
I have the following hierarchy in the NetBeans GUI Designer:
<code>JFrame
  JTabbedPane
    JPanel X
      <...>
    JPanel
      JButton
      JPanel Y
        <...>
      JButton
</code>
Question:
JPanel Y is identical to JPanel X, so I'd like to simply reuse JPanel X in both places, but how do I do this inside the GUI Builder?
Attempts:
I tried copy-pasting JPanel X, but it creates a full "deep" copy (JPanel X1, etc), duplicating everything in JPanel X.
Some googling indicated it might be possible to add it to the Palette, but I haven't found a way to add a simple JPanel to the palette (as opposed to a complete JFrame).
Answer: Create a separate JPanel class. Customize JPanel as needed. You can then drag-and-drop the JPanel class onto the Form Designer. This is exactly what I do.
Alternatively, you can click on Use Bean and then type in the name of the class.
Alternatively, you can do an Add from the pallete and it will scan your JAR for any "beans". It should pick up your custom JPanel as well.


Need to Link to an Image on another Page already containing multiple images

Question: hello again...
I need to create a link on one page (my home page) that links directly to a image on another page already containing multiple images.  Thought I knew how to do it...by creating an anchor; & my code looks like this:
IMAGE SUBJECT

but it doesn't work.  Even tried the forward slash after the page id:
IMAGE SUBJECT

when the user clicks the link, I want it to go directly to a specific image on a 2nd page...here's the page:
http://www.moonjams.net/events.html
there's 2 images there now, but there will be more.  The home page links need to go directly to different images on that page you see...(which I thought was a simple anchor)...anyone have any idea what I'm doing wrong?
thanx,
dox
Answer: You need to give images in the listing file ID's, and then you can link them in your main index by doing the hyperlink as shown below.
Here's an example:
File containing images (imgfile.html):

THIS IS THE FILE WHERE THE IMAGES ARE

This is a cat

This is a dog

This is a cow

File containing links (index.html):

THIS IS THE MAIN FILE

 Cat

 Dog

 Cow

I tested this, and does exactly what you need.
You can check the live demo on my own website: https://rawstring.com/tests
After I check your website, looks easy.
Change this (line 43/44):

To this (line 43/44):

Then link them this way:

 Image 01

 Image 02

And just do it for every image you add to the page. That should do it.
Comment: @doxology in case this answer solved your problem, please accept it by clicking the "V" and the up arrow. Thanks


Comparar horário android

Question: Possuo um cadastro onde o estabelecimento coloca seu horário de funcionamento em variáveis String, Ex: horario_abertura e horario_fechamento formato: 00:00 24hrs.
Preciso que o aplicativo compare o horário atual com o de abertura e fechamento do estabelecimento, para informar se o mesmo está aberto ou fechado!
Alguém tem algum exemplo?
Answer: Pode fazer assim:
public static final String inputFormat = "HH:mm";

private Date date;
private Date dateCompareOne;
private Date dateCompareTwo;

private String horarioabertura = "8:45";
private String horariofechamento = "18:45";

SimpleDateFormat inputParser = new SimpleDateFormat(inputFormat, Locale.US);

private void compareDates(){
    Calendar now = Calendar.getInstance();

    int hour = now.get(Calendar.HOUR_OF_DAY);
    int minute = now.get(Calendar.MINUTE);

    date = parseDate(hour + ":" + minute);
    dateCompareOne = parseDate(horarioabertura);
    dateCompareTwo = parseDate(horariofechamento);

    if ( dateCompareOne.before( date ) && dateCompareTwo.after(date)) {
        //esta aberto
    } else
        //esta fechado
}

private Date parseDate(String date) {

    try {
        return inputParser.parse(date);
    } catch (java.text.ParseException e) {
        return new Date(0);
    }
}

Comment: Obrigado pela resposta, está comparando porém somente no formato 12hrs. Quando o horário ultrapassa o meio dia ele sempre está fechado.
Comment: Na verdade quando ultrapassa meio dia não entra no if
Comment: Editei a resposta.
Comment: Obrigado! Funcionou perfeitamente.

Comparar horário android


Shorewall deny all assh access except one user

Question: Hi all I have an ubuntu server with shorewall firewall.
I want to deny all ssh access exxcept my user: "alessandro".
How can I write this rule in shorewall?
Thanks
Answer: Shorewall can not do what you need.
You should put:
AllowUsers alessandro

into your /etc/ssh/sshd_config.
Comment: I don't know what you mean by "mode" but configuring user access restrictions for SSH is done exactly the way I described above. Shorewall has nothing to do with it. Of course there can be other protocols running like FTP, NFS etc. and even though you can totally deny access to them with Shorewall (actually iptables), you still can not put any user restrictions on them at this level.
Comment: I have already done this. But I don't know if someone entered into my server in some other mode..


To enable extensions, verify that they are enabled in those .ini files - Vagrant/Ubuntu/Magento 2.0.2

Question: When installing Magento 2.0.2 via composer getting this error:
Problem 1
 - Installation request for magento/product-enterprise-edition 2.0.2 -> satisfiable by magento/product-enterprise-edition[2.0.2].
 - magento/product-enterprise-edition 2.0.2 requires ext-gd * -> the requested PHP extension gd is missing from your system.

To enable extensions, verify that they are enabled in those .ini files:

- /etc/php5/cli/php.ini
- /etc/php5/cli/conf.d/05-opcache.ini
- /etc/php5/cli/conf.d/10-pdo.ini
- /etc/php5/cli/conf.d/20-curl.ini
- /etc/php5/cli/conf.d/20-imap.ini
- /etc/php5/cli/conf.d/20-json.ini
- /etc/php5/cli/conf.d/20-mcrypt.ini
- /etc/php5/cli/conf.d/20-pdo_pgsql.ini
- /etc/php5/cli/conf.d/20-pgsql.ini
- /etc/php5/cli/conf.d/20-pspell.ini
- /etc/php5/cli/conf.d/20-readline.ini

You can also run `php --ini` inside terminal to see which files are used by PHP in CLI mode.

I have installed php5-cli, php5-curl.
Comment: What have you tried to resolve the problem? Anything unclear about that output?
Answer: First installed sudo apt-get install php5-gd, then sudo apt-get install php5-intl and last one was sudo apt-get install php5-xsl.
After that, it's installing as it should.
Comment: These 2 commands worked for me: `sudo apt-get install php-zip` `sudo apt-get install php-mbstring`
Comment: If you have a newest version of php you must use `apt-cache search php7-*` to find packages and install after. In my case with php7 candidates was:
`php7.2-gd` `php7.2-intl`and `php7.2-xsl`
Comment: This helped me out                                             https://stackoverflow.com/a/46058582/8090905
Answer: This solved my issues
sudo apt-get install php7.1-xml

or newer version (* = your php version )
sudo apt-get install php7.*-xml

Comment: for me  :  sudo apt-get install php7.2-xml
Comment: How can installing an XML extension help if the GD extension is missing?
Comment: Just run this, no headaches later: `sudo apt-get install php7.*-xml`
Comment: `sudo apt-get install php7.4-xml` is what I needed to do before using composer to install phpunit9
Comment: B/c of TL;DR I jumped off to @DwayneWalsh tho it's what's written in the actual answer
Answer: ubuntu users try this
apt-get install php7.2 libapache2-mod-php7.2 php7.2-common php7.2-gd php7.2-mysql php7.2-curl php7.2-intl php7.2-xsl php7.2-mbstring php7.2-zip php7.2-bcmath php7.2-soap php-xdebug php-imagick

this is work for php 7.2 but you can change this 7.2 to 5.2 and run this command
it is work.
Comment: Thank you. It saves my day.
Answer: Have tried for many times, the above answers don't solve my quesiton, but this command helped me:
sudo apt-get install php-mbstring

Comment: sometime coming down to answer lists in stack overflow is great !
Issue fixed thanks
Answer: When I went to create a laravel project, I got this problem.
After googling, I got this solution.
I followed these steps:
Step 1: sudo apt-get install -y php7.2-gd
Step 2: sudo apt-get install php7.2-intl
Step 3: sudo apt-get install php7.2-xsl
Step 4: sudo apt-get install php7.2-mbstring
Answer: Updated....For ubuntu users
sudo apt-get install libapache2-mod-php php-common php-gd php-mysql php-curl php-intl php-xsl php-mbstring php-zip php-bcmath php-soap php-xdebug php-imagick

Answer: this command would do the trick
sudo apt-get install php5-curl

Comment: Welcome to Stack Overflow! While this code may answer the question, providing additional context regarding _how_ and/or _why_ it solves the problem would improve the answer's long-term value. It also doesn't hurt to mention why this answer is more appropriate than the previously suggested ones.
Answer: First installed
sudo apt-get install php5-gd

then
sudo apt-get install php5-intl

and last one was
sudo apt-get install php5-xsl

After that, it is installing as it should.
Comment: I did the same as above replacing php5 with php7.2 and it worked like a charm
Comment: I did the same as above replacing php5 with php7.2 and it worked like a charm
Answer: @Verse answer works fine. But there is a small thing I would like to add.
instead of installing php5-mbstring, php5-gd, php5-intl, php5-xsl. This answer  is based on @Regolith answer: Package has no installation candidate .
Install according to your php-version.
First check which php version you have by sudo php -v. I have php7 so the result is:
PHP 7.0.28-0ubuntu0.16.04.1 (cli) ( NTS )
Copyright (c) 1997-2017 The PHP Group
Zend Engine v3.0.0, Copyright (c) 1998-2017 Zend Technologies
   with Zend OPcache v7.0.28-0ubuntu0.16.04.1, Copyright (c) 1999-2017, by Zend Technologies

since i have php7, I will do the following to list the php packages:
sudo apt-cache search php7-*
this returned
libapache2-mod-php7.0 - server-side, HTML-embedded scripting language (Apache 2 module)
php-all-dev - package depending on all supported PHP development packages
php7.0 - server-side, HTML-embedded scripting language (metapackage)
php7.0-cgi - server-side, HTML-embedded scripting language (CGI binary)
php7.0-cli - command-line interpreter for the PHP scripting language
php7.0-common - documentation, examples and common module for PHP
php7.0-curl - CURL module for PHP
php7.0-dev - Files for PHP7.0 module development
php7.0-gd - GD module for PHP
php7.0-gmp - GMP module for PHP
php7.0-json - JSON module for PHP
php7.0-ldap - LDAP module for PHP
php7.0-mysql - MySQL module for PHP
php7.0-odbc - ODBC module for PHP
php7.0-opcache - Zend OpCache module for PHP
php7.0-pgsql - PostgreSQL module for PHP
php7.0-pspell - pspell module for PHP
php7.0-readline - readline module for PHP
php7.0-recode - recode module for PHP
php7.0-snmp - SNMP module for PHP
php7.0-sqlite3 - SQLite3 module for PHP
php7.0-tidy - tidy module for PHP
php7.0-xml - DOM, SimpleXML, WDDX, XML, and XSL module for PHP
php7.0-xmlrpc - XMLRPC-EPI module for PHP
libphp7.0-embed - HTML-embedded scripting language (Embedded SAPI library)
php7.0-bcmath - Bcmath module for PHP
php7.0-bz2 - bzip2 module for PHP
php7.0-enchant - Enchant module for PHP
php7.0-fpm - server-side, HTML-embedded scripting language (FPM-CGI binary)
php7.0-imap - IMAP module for PHP
php7.0-interbase - Interbase module for PHP
php7.0-intl - Internationalisation module for PHP
php7.0-mbstring - MBSTRING module for PHP
php7.0-mcrypt - libmcrypt module for PHP
php7.0-phpdbg - server-side, HTML-embedded scripting language (PHPDBG binary)
php7.0-soap - SOAP module for PHP
php7.0-sybase - Sybase module for PHP
php7.0-xsl - XSL module for PHP (dummy)
php7.0-zip - Zip module for PHP
php7.0-dba - DBA module for PHP

now to install packages run the following command with your desired package
sudo apt-get install -y php7.0-gd, php7.0-intl, php7.0-xsl, php7.0-mbstring

Note: php7.0-mbstring, php7.0-gd php7.0-intl php7.0-xsl are the package that are listed above.
UPDATE:
Don't forget to restart apache/<your_server>
sudo service apache2 reload

Answer: This was the fix for me when trying to install Laravel on a fresh WSL installation:
sudo apt-get install php7.2-gd
sudo apt-get install php7.2-intl
sudo apt-get install php7.2-xsl
sudo apt-get install php7.2-zip
Answer: On Ubuntu 16.04 php7 is now the default, so if you follow the top answers and are still having this issue, check your php version.
php --version

If your default php version is php7, but you followed an answer using php5 packages, you can use the following command to set the default version of php to php5.6:
sudo update-alternatives --set php $(which php5.6)

Answer: I used below to fix issue
yum install -y php-intl php-xsl php-opcache php-xml php-mcrypt php-gd php-devel php-mysql  php-mbstring php-bcmath
Answer: for similar case:

/etc/php/7.3/cli/php.ini
/etc/php/7.3/cli/conf.d/10-mysqlnd.ini
/etc/php/7.3/cli/conf.d/10-opcache.ini
/etc/php/7.3/cli/conf.d/10-pdo.ini
/etc/php/7.3/cli/conf.d/20-calendar.ini
/etc/php/7.3/cli/conf.d/20-ctype.ini
/etc/php/7.3/cli/conf.d/20-exif.ini
/etc/php/7.3/cli/conf.d/20-fileinfo.ini
/etc/php/7.3/cli/conf.d/20-ftp.ini
/etc/php/7.3/cli/conf.d/20-gettext.ini
/etc/php/7.3/cli/conf.d/20-iconv.ini
/etc/php/7.3/cli/conf.d/20-json.ini
/etc/php/7.3/cli/conf.d/20-mbstring.ini
/etc/php/7.3/cli/conf.d/20-mysqli.ini
/etc/php/7.3/cli/conf.d/20-pdo_mysql.ini
/etc/php/7.3/cli/conf.d/20-phar.ini
/etc/php/7.3/cli/conf.d/20-posix.ini
/etc/php/7.3/cli/conf.d/20-readline.ini
/etc/php/7.3/cli/conf.d/20-shmop.ini
/etc/php/7.3/cli/conf.d/20-sockets.ini
/etc/php/7.3/cli/conf.d/20-sysvmsg.ini
/etc/php/7.3/cli/conf.d/20-sysvsem.ini
/etc/php/7.3/cli/conf.d/20-sysvshm.ini
/etc/php/7.3/cli/conf.d/20-tokenizer.ini

solved with :
apt-get install php-dom
apt-get install php-mbstring

Answer: The exact name of the extension depends on the repository from which you got PHP but look here. For example on CentOS:
yum install -y php56w php56w-opcache php56w-xml php56w-mcrypt php56w-gd php56w-devel php56w-mysql php56w-intl php56w-mbstring php56w-bcmath
Comment: I did sudo apt-get -y install php5 php5-mhash php5-mcrypt php5-curl php5-cli php5-mysql php5-gd php5-intl php5-xsl php5-bcmath. Getting Unable to locate package php5-bcmath
Comment: `php5-bcmath` may be built-in on some systems. Try exclude that from your install command, and check to see if it's installed afterwards.
Answer: For me
sudo apt-get install php5-mcrypt

solved the issue
Answer: Gonna post this answer here after seeing some of the answers (including the accepted one) which claim to "do the trick". First, we need to identify the issue before fixing it.

the requested PHP extension gd is missing from your system.

As the above line clearly states, we need to install the extension php-gd.
So, we can go with sudo apt install php<version>-gd and it should fix this error unless the system needs more extensions which happens to be the exact case here in the system in question. It needs a couple more extensions php-intl and php-xsl.
So let it be mbstring or mcrypt, you should install whatever the extensions your system is missing. How can you find what is missing? Just read the error message, it is there.
Answer: It helped my case to install the right curl version
sudo apt-get install php5-curl

Answer:
Open the xampp/php/php.ini file in any editor
Search ";extension=php_intl.dll"
Remove the starting semicolon ( ; )

Like:
;extension=php_intl.dll to extension=php_intl.dll
This helped me.
Comment: "magento/product-enterprise-edition 2.0.2 requires ext-gd" - how does your answer resolve that problem?
Answer: Installing PHP extensions:
sudo apt-get install -y php-gd

sudo apt-get install -y php-intl

sudo apt-get install -y php-xsl

sudo apt-get install -y php-mbstring

Answer: I followed these steps:
steps1: sudo apt-get install php5-gd
steps2: sudo apt-get install php5-intl
steps3: sudo apt-get install php5-xsl
After that, it's installing as it should.
Comment: Please add some explanation to your answer such that others can learn from it. If the application needs `ext-gd`, your command might resolve problems during the installation itself, but not during the runtime of that application


What is the last non-zero digit of $((\dots(((1!)!+2!)!+3!)!+\dots)!+1992!)!$?

Question: What is the last non-zero digit of $((\dots(((1!)!+2!)!+3!)!+\dots)!+1992!)!$?

Clarification of the given expression:
Let $A_1=(1!)!$
To get $A_2$, we add $2!$ to $A_1$ then we take the factorial of that expression. So, $A_2=((1!)!+2!)!$
To get $A_3$, we add $3!$ to $A_2$ then we take the factorial of that expression. So, $A_3=(((1!)!+2!)!+3!)!$
To get $A_4$, we add $4!$ to $A_3$ then we take the factorial of that expression. So, $A_4=((((1!)!+2!)!+3!)!+4!)!$
and so on.

Now we need to find the last non-zero digit of $A_{1992}$. I am not asking for a solution, but asking for some hints how shall I begin.

Your help would be appreciated. THANKS.
Comment: Hint: what's the units digit of $5!$? of $6!$? of $7!$?
Comment: Dear??? I'd begin by computing a few examples to see whether there's a pattern. You might also look at the question listed under "Related", asking for the last non-zero digit of $50!$. There are two other Related questions asking about last nonzero digits involving factorials, they too might be helpful.
Comment: @GerryMyerson Thank you dear. But I have asked a wrong question. Could you please check my question now?
Comment: @GerryMyerson I DO know how to find the last non-zero digit of $n!$. We have just find the floor(n/5)+floor(n/5^2)+floor(n/5^3)+... to infinity. But the expression in this post is different and I could not find any related problem.
Comment: That sum of floors that you have written has the same value, $1$, for $n=5,6,7,8,9$ but the last nonzero digit of $n!$ is $2,2,4,2,8$, so I don't understand what that formula does for you.
Comment: @Hussain-Alqatari You should add info like this to the question. Also you should add the solution for the last digits of $A_k$ for small $k$ to the question.
Answer: Let $a_n$ denote the last nonzero digit of $n!$; we need only consider $n\ge5$.

Prove $a_n\in S:=\{2,\,4,\,6,\,8\}$.
Prove $a_{10k+5}=a_{10k+14}$.
Determine the order of the permutation $\sigma$ of $S$ for which $a_{10k+15}=\sigma(a_{10k+14})$.
Find a fairly small upper bound $p$ on the period of $a_n$.
Convince yourself $a_p,\,\cdots,\,a_{2p-1}$ is a period.
Explain why the original problem's answer is $a_p$, then compute it.


Alternative to $broadcast/$emit/$on in triggering events

Question: What is an alternative way in AngularJS to trigger events other than $broadcast/$emit/$on. If I will have too many event triggers between controllers and/or directives, I'm afraid this will lead to hard to trace spaghetti events. (Or could it be that too many events is a bad design after all?)
I heard using service/factory is the preferred way. Can someone give me an example how? Or are there other methods aside from service/factory?
Comment: Can you give examples of how you are using eventing? From your question it is unknown if you are overusing events.
Comment: For example, at the end of the function of controller/directive, say A, I want to invoke a function in another controller/directive, say B.
Comment: This is reasonable, directive A throws and event that directive B defines and listens to but is this really something that occurs on all of your directives?
Comment: For example if you have a Flyout directive and you want to resize it because the content inside it changes and some directive inside it throws a 'resizeFlyout' directive then that is fine.
On the other hand, if you are using eventing in every directive to state that it is done processing then you are not using events correctly.
Comment: Can you give me an example how to use service/factory to trigger events, instead of using $broadcast / $emit?
Comment: Services, factories, and providers would not handle eventing. They do not have a scope or a DOM element and thus are not the right place for that kind of thing.
Comment: Can you give any concrete example of what you are hoping to accomplish? Are you wanting to do something during initialization of the directives or during runtime when a directive detects a change? Can directive A only be used as a child or directive B, could it be used under directive C, can it be used by itself?
Answer: You could use a event queue/event bus as a solution. Check out
http://jonathancreamer.com/an-angular-event-bus-with-postal-js/
and
https://github.com/jseppi/angular-queue


Developing a heuristic for maximizing the "covering" of a distribution

Question: Context
There's a board-game called Settlers of Catan in which players compete to be the first to gain 10 victory points by trading various resources in exchange for pieces (or cards) worth victory points.  A player gains resources when the dice are rolled and they own a particular piece (a settlement) adjacent to a resource tile that corresponds to the roll.  For example, I have a settlement adjacent to an ore resource tile labeled $8$, in all cases that an $8$ is rolled, I gain one ore.
In the beginning of the game, players take turns choosing where their first two settlements will be on the map.  This can be an important part of the game, as a player's first placement will affect their starting momentum, ultimately affecting how they play in the middle- and end-games.
Here is an illustrative example of the board.  Notice, the maximum tiles one settlement can touch is three, at the vertex created by the sides of three hexagons.
Aside
In my experience of playing, I've found that by placing settlements that simply maximizes my expected return, I'm not as likely to win.  For example, if my first two settlements I've placed are on vertices $\{5,8,10\}$ and $\{5,8,11\}$, despite the fact that these rolls are likely, because I've "doubled-up" on $5$s and $8$s, the outcome of my game tends to be worse.
This is in contrast to placing settlements on say $\{5,8,10\}$ and $\{4,9,11\}$.  Although these are less likely to be rolled, by spreading my coverage of the distribution, I reduce the risk of turns where I don't gain a resource.
The Problem
We'd like to develop a heuristic to aid a player in picking the spots on which they should place their first two settlements, only taking into account the number labels of the resources (not the resources themselves, or ports, etc.).
So Far
There should likely be two functions, $f_1$ and $f_2$, that correspond to the placing of the first settlement and the second, respectively.
$f_1$ is easy to define, it takes a set of three, $x,y,z$, representing the three labels on the adjacent resource tiles (we'll assume every placement will be adjacent to three tiles despite the possibility of placing next to two or only one).  It is equal to the addition of each of the probabilities of those outcomes, except in the case of a $7$ being rolled, take it as a given that $7$s are bad.
So, we have a modified $p(x)$ that has a domain of $[2,12]\setminus\{7\}$ with the following image:

$p(2)=p(12)=\frac{1}{36}$
$p(3)=p(11)=\frac{2}{36}$
$p(4)=p(10)=\frac{3}{36}$
$p(5)=p(9)=\frac{4}{36}$
$p(6)=p(8)=\frac{5}{36}$

Note: We've removed $7$ from the domain because within the game, there are no resources labeled $7$.
Then $f_1(\{x,y,z\})=p(x)+p(y)+p(z)$
The More Interesting $f_2$
Now we get to define $f_2$ which represents the player's second settlement placement.  As I alluded to in the aside, we should take into account the player's previous placement such that $f_2$ depends on two sets each of three values, $\{x_1,y_1,z_1\}\{x_2,y_2,z_2\}$.
The Questions
My ultimate question is, how do we codify the intuition of "spreading out the values"?  I'm thinking that either there should be a penalty for "doubling up" or a bonus for "spreading out", the former at first glance seeming easier.
However, I'm not sure how to do this in a function.

How, using mathematical notation, do I say, "the length of the intersection of these sets"? (That's at least what I'm thinking, the penalty will be proportional to the number of shared elements between the two sets.)

Is this a good start? $f_2(\{x_1,y_1,z_1\},\{x_2,y_2,z_2\})=f_1(s_1)+f_1(s_2)-\alpha\left|s_1\cap s_2\right|$

One thing about this, I'm not sure that this is a good penalty since the penalty doesn't take into account the probabilities, that is, doubling-up on $9$s is not as bad as doubling-up on $12$s, but maybe this is already taken care of in the initial use of $f_1$?

Further, how do I determine a good penalty coefficient?
Or do I need to?  Does there already exist some notion within statistics or math that captures "covering a distribution", that is, ensuring that no matter what the outcome, you have a return.
Am I going about this all wrong and is there a simple, elegant way to do this?
Answer: Sure there's a measure of "covering a distribution". It's called probability!
We can see why ${5,8,10}$ and ${5,8,11}$ together aren't as likely to gain at least one resource as ${5,8,10}$ and ${4,9,11}$ by calculating the probability that we do that -- gain at least one resource.
In the first case:
P(get at least one resource) = P(5)+P(8)+P(10)+P(11) = (4+5+3+2)/36. However, the "36" is a nuisance, so drop it. So P(5)+P(8)+P(10)+P(11) $\propto$ 4+5+3+2 = 14
P(get at least one resource) = P(5)+P(8)+P(10)+P(11)$\,$ +$\,$ P(9)+P(4) $\propto$ 4+5+3+2$\,$ +$\,$ 4+3 = 21
So if we call the thing proportional to the probability "the score" (it's actually 36 times the probability), we should be able to get the "best" outcome (in terms of getting the higher probability of at least one resource).
But this needs to be fast. Can you remember how many ways out of 36 to get a 5? or a 10? Here's a way to work it out fast if you don't have them all memorized:
If the number you're looking at is less than 7, (5, say) subtract 1 (5-1=4). That's it's 'score' (36 times its probability). If the number you're looking at is more than 7 (10, say), subtract it from 13 (13-10=3) to get the score. (But only do this if the number isn't already present.)
If the roll number is <7 you add one less than the number to the total, and if it's greater than 7 you subtract the number from 13 and add it to the total, but only add a given roll in once.
So if you already placed $(5,8,10)$ and the next one is $(5,8,11)$ that can only add 13-11=2, while $(4,9,11)$ must add more (the 11 adds the 2, same as before, but it has more to add). So the second one is better.
This calculation is very fast.
(On the other hand, ${5,8,10}$ and ${5,8,11}$ may actually be a better choice if you're good at trading or can build a road to a port; getting at least one resource isn't the only important thing)

that is, doubling-up on 9s is not as bad as doubling-up on 12s,

If you're interested in something other than P(at least one resource), it might, but if that P(at least one resource) is the thing you want to maximize, then the above score-proportional-to-probability calculation will work perfectly.
Alternatively, you might like to score double-ups as something more than 0; perhaps 1/3 of the score (to represent value potentially gained in trade). So ${5,8,10}$ and ${5,8,11}$ would be worth more than 14; it would be 14 + the extra 1/3 score for the second 5 and 8 = 14 + (4+5)/3 = 17. Still not as good as the other choice, but not so bad.
Comment: I think you're right, this is the correct problem to solve (maximize probability of receiving at least one resource).  However your explanation becomes less clear at "If the roll number is <7 you add one less than the number to the total".  Could you clarify your explanation from this point on?
Comment: Okay, I edited my answer, to expand the explanation there (and added a little extra suggestion for a modified heuristic at the end)


EC2 Configuration

Question: I am trying to create a server structure for my EC2 account. The design I have chosen consists of 2 instances running in different availability zones, elastic load balancer, an auto-scaling group with cloudwatch monitoring configured and a security group defining rules for access to the instances. This setup is to support an online web application written in PHP.
I am trying to decide what is a better policy:

Store MySQL DB on a separate Instance
Store MySQL DB on an attached EBS volume (from what i know auto-scaling will not replicate the attached EBS volume but will generate new instances from a chosen AMI - is this view correct?)

Regards the AMI I plan to use a basic Amazon linux 64 bit AMI, and install bastille (maybe OSSEC) but I am looking to also use an encrypted file system.

Are there any issues using an encrypted file system and communication between the DB and webapp i neeed to be aware of?
Are there any comms issues using the encrypted filesystem on the instance housing the webapp
I was going to launch a second instance or attach a second volume in the second availability zone to act as a standby for the database - I'm just looking for some suggestions about how to get the two DB's to talk - will this be a big task
Regards updates for security is it best to create a recent snapshot and just relaunch and allow Amazon to install updates on launch or is the yum update mechanism a suitable alternative - is it better practice to relaunch instead of updates being installed which force a restart.
I plan to create two AMI snapshots one for the app server and one for the DB each with the same security measures in place - is this a reasonable - I just figure it is a better policy than having additional applications that are unnecessary included in a AMI that I intend on using.
My plan for backup is to create periodic snapshots of the webapp and DB instances (if I use an additional EBS volume instead of separate instances my understanding is that the EBS volume will persist in S3 storage in the event of an unexpected termination and I can create snapshots of the volume backup purposes).

Thanks in advance for suggestions and advice. I am new to EC2 and I may have described unnecessary overkill but I want to try implement what can be considered a best practice solution so all advice is appreciated.
Answer: The database should be on a dedicated instance, where possible. This will allow you to manage that server independent of any other servers that you may have (add disk space, replace the server, etc.).
The database should also be put on a separate EBS volume from the root volume.  This allows you to setup a new server and "move" the data to the new instance easily.
I wouldn't apply AutoScaling to your database.  AutoScaling creates new instances from AMI images, which most certainly will be out of date with regards to your data.  You can have all other instances which are launched by AutoScaling to use your single database.
You can use MySQL replication to replicate data to a slave instance in another availability zone.  See http://dev.mysql.com/doc/refman/5.0/en/replication-howto.html
The slave instances have many uses:

Keep it on standby in case the primary server goes down
Perform read-only operations on the slave to relieve the primary server's load
Backup the slave instead of the primary server to avoid table locks and/or other database accessibility problems
Comment: Hi, thanks for getting back to me, MySQL replication looks like the solution I'm after, i intend on using a separate instance for the DB.

EC2 Configuration


Neo4j Cypher Unique Constrain vs Indexing

Question: I am creating Nodes City with properties Name and ID.City node may be indexed on Id.I want unique node.
Now when populating database I want to get City node if present otherwise I want to create a City node.
What is the best way to do that?
Create a Cypher execution engine and a unique constraint. And then Use MERGE to create a unique node.
Or something like
Check if the City with that id is present **Match
START n=node:City(id = { id }) RETURN n**

if n==null Create the Node

Which is fast?What if I won't index city?
Answer: Cypher is safe as it takes the correct locks.
The Java version would probably be a tiny bit faster, but you have to create the write locks on a single root-lock-entity yourself to make sure that in no scenario more than one thread accesses that code / data.
Without an index you have to scan the whole database to check for duplicates.
Comment: Suppose I indexed the ids.Then which will be a better way?first or second?
Answer: use the info in http://docs.neo4j.org/chunked/stable/query-merge.html
MERGE (aCity:CITY {Id: '1', Name: 'aName') return aCity;

This would only create the node if it does not exist. If the node already exists it returns the existing node.
NOTE - if the name is spelled differently, a new node will be created even if the Id is the same as the existing node (a complete match of all fields is performed). If this is not the functionality you want you need to use the ON MATCH functionality described in the above link and put a unique constraint on the Id
Comment: But it looks like it will take a lot of time searching for the matched node?Is it a good way if I will be having a large database?
Comment: Normally with a label there would be auto indexing, so it would find the node immediately. If you want to be more specific you could execute 'create index on :CITY(Id)'. Which would ensure that the Id field is used to find the node.


jquery ui button padding override

Question: HTML markup is as follows:
<button id="Refresh"></button>

I am creating this button as a jquery ui button with the following code:
$("#Refresh").button();

Calling this function produces the following markup:
<button id="Refresh" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" role="button" aria-disabled="false">

</button>

This works fine. The result is a button with padding of .4em 1em; as defined in jquery's CSS. (.ui-button-text-only .ui-button-text)
I have several buttons on this page, and I like this padding for most of them. However, for this one button in particular I'd like to have no padding. I realize I could just change the CSS for .ui-button-text-only and  .ui-button-text but that would screw up the other buttons using this style, and I like them the way they are.
So I'm wondering if there's any way to override this css just for one button. I took a look at jquery's button docs but it doesn't appear to allow passing of specific CSS in with the button options.
Thanks in advance for the help!
Comment: Have you tried adding a class after the button is created?
Comment: @JoshMein do you mean trying to override jquery's css class? If so, wouldn't that just override the css for the other buttons as well?
Comment: I meant to add a class to that specific button. Check out my answer below.
Answer: You can simply style it using CSS. To make sure it's not overridden add '!important'
Add the span tag
#Refresh span {
    padding:0 !important;
}

Comment: Unfortunately this doesn't seem to work. My guess is because it's not actually #Refresh being styled, but the span jquery creates.
Comment: use a selector like `button#Refresh span.ui-button-text` and it will work as intended.
Comment: to access the jquery button, don't forget the prefix "ui-", .ui-button.clearButton span.ui-button-text{padding:0;} // here I also created a class clearButton as per accepted answer
Answer: You can just add a new class to the span within the button after it is created.
$("#Refresh").button();
$("#Refresh").find('span.ui-button-text').addClass('yourClass');

jquery ui button padding override


Preciso pegar a ultima string mas ele consta espaço como remover o espaço final?

Question: select
    top 1 SUBSTRING(
       [nome funcionario],
       CHARINDEX(' ',[nome funcionario]),
       LEN([nome funcionario])
    )
as Sobrenome
from Tabela_nome

Resultados
" DE FREITAS  "
O problema é que ele consta espaço no inicio do sobrenome e no final do sobrenome, como remover espaço e trazer apenas "DE FREITAS"
Comment: Benvindo ao StackOverflow em Português! Tentou a função `TRIM`?
Comment: Trim e caso como "de freitas" precisariam ser tratados. Regornaria "freitas".
Comment: https://pt.stackoverflow.com/questions/131877/extrair-nome-e-ultimo-sobrenome-mysql
Answer: Apenas use TRIM(string) na sua query, igual o Daniel Ikenaga falou.
Deixarei alguns exemplos que encontrei:
SELECT TRIM(leading ' ' from ' Google.com ');

--Result: 'Google.com '

SELECT TRIM(trailing ' ' from ' Google.com ');

--Result: '' Google.com'

SELECT TRIM(both ' ' from ' Google.com ');

--Result: 'Google.com'

SELECT TRIM(' ' from ' Google.com ');

--Result: 'Google.com'

SELECT trim(' Google.com ');

--Result: 'Google.com'

SELECT trim(leading '0' from '000123');

--Result: '123'

SELECT TRIM(trailing '1' from 'Number1');

--Result: 'Number'

SELECT TRIM(both '123' from '123PostgreSQL123');

--Result: 'PostgreSQL'

Caso queria saber mais, clique aqui (inglês, mas com certeza tem em pt-br) para ver o site que peguei de referência.
Mas claro, mesmo existindo essa função no sql, você pode fazer essa alteração no próprio código, vamos a um exemplo em python:
s1 = '  abc  '

print(f'String =\'{s1}\'')

print(f'Depois de remover espaços em branco da ESQUERDA da string =\'{s1.lstrip()}\'')

print(f'Depois de remover espaços em branco da DIREITA da string =\'{s1.rstrip()}\'')

print(f'Depois de remover espaços em branco da ESQUERDA E DIREITA da string =\'{s1.strip()}\'')

resultado:
String ='  abc  '
Depois de remover espaços em branco da ESQUERDA da string ='abc  '
Depois de remover espaços em branco da DIREITA da string  ='  abc'
Depois de remover espaços em branco da ESQUERDA E DIREITA da string ='abc'

Para saber mais aprofundadamente, leia aqui (inglês, mas com certeza tem em pt-br)


Randomize search result in sphinx

Question: Hi im using sphinx 201 beta (r2792)
i have rt index with rt_attr_uint = rake my goal is to sort results by this attribute
whitch work as expected using
$this->sphinx->SetSortMode(SPH_SORT_EXTENDED, 'rake DESC')

but i want to also randomize this result ... lets say i have this data
(id,  title,  rake)
  1, 'test',  3
  2, 'test2', 3
  3, 'ásdf',  1
  4, 'rreer', 0

so after i append random
$this->sphinx->SetSortMode(SPH_SORT_EXTENDED, 'rake DESC, @random')

i would expect randomize result sorted by attribute rake descending
but im getting error:
sort-by attribute '@random' not found

whitch i dont understand because this random attribute is internal attribute
am i doing something wrong? where could be a problem? thanks
Answer: From my quick tests, it looks like Sphinx only supports @random if it is the only attribute in the sort clause. So I'm afraid you're out of luck - either you just sort randomly, or you just sort by rake.
Comment: @rogerkk  unfortunately I'm not aware of any other way around this, especially if you've found it's still happening in recent Sphinx/Manticore releases.
Comment: Hey Pat! I'm wanting to achieve the same with our `thinking_sphinx`/`flying_sphinx` setup 13 years later. Happen to know if there's a solution for this today that doesn't involve a random value in the index itself? :)  Seems to me that @random is on it's way out and that RAND() has the same limitation you mention above.
Answer: What I did is create the random number on the SQL query
SELECT ...  RAND() as random_sort, ...

Added it as an attribute
sql_attr_float = random_sort

And then use it in the extended sort query
$this->sphinx->SetSortMode(SPH_SORT_EXTENDED, 'rake DESC, random_sort DESC');

Answer: For real time randomness, index the ids and sort using expr mode with an expression like this (not sure this one is 100% random):
( ( ( id % #{pagesize} + #{rand(pagesize * 2)} ) % #{pagesize} ) / #{pagesize} )

Add an If statement to the expression above to use your rake attribute.
[http://sphinxsearch.com/docs/1.10/sorting-modes.html][1]

Randomize search result in sphinx


When a link is clicked, a value is retrieved from the table and displayed on a Webform field

Question: I have created a basic page with two buttons, "Yes" and "No". When the "Yes" button is clicked, it is directed to the webform.
Aim: When the webform appears, it displays a value from the table into a field.
Database

Table name: Room
Field: Room
Data: Training Room

The Basic Page

The Webform

I created a module for this functionality:
test_presave.info
name = "Test presave"

description = "Retrieving data from table"

core = 7.x

package = Test

test_presave.module
/*

*Implements hook_node_presave()

*/

function test_presave_node_presave($node)

{

    $accessnode=$node->nid;

    if($accessnode==20)//Lettable Room Booking webform

    {

        $result=$db_query("SELECT Room FROM {Room} WHERE Room =:ln",array(':ln'=>'Training Room'))->fetchCol();

        $node->webform['components'][1]['value']=$result;

    }

}

Am I using the correct hook?
Do I have to use the node api or the webform api?
Can you help me with this?
Answer: Rather do this:
Alter the button link to include a parameter:
Yes

In hook_form_alter, check for the parameter and set the default value(s):
function test_presave_form_alter(&$form, &$form_state, $form_id) {
    // dpm($form_id); // uncomment to get $form_id
    // dpm($form); // uncomment to get $form
    if ($form_id == 'webform_client_form_2') { // use dpm($form_id) to get your form id
        $param = drupal_get_query_parameters();
        if (isset($param['captured']) && $param['captured'] == "true")
        {
            $result = ...
            if ($result) {
                $form['submitted']['room']['#default_value'] = $result; // use dpm($form) to get your room field
            }
        }
    }
}

Comment: Thanks for your answer. What is 'room'? Is it the name or the form_key?
Comment: It is the form field name that webform gave my room field. Yours might be different. Use dpm($form['submitted']) to inspect
Comment: PS. to get dmp() you need [Devel](https://www.drupal.org/project/devel) installed


Is there a square-filling curve?

Question: How can an image of [0,1] fill a square? It seems to me that it would have to be DISCONTINUOUS, so it wouldn't satisfy the definition of a curve.
Comment: It may seem that it would have to be discontinuous, but in fact it doesn't.  There are continuous functions $f : [0,1] \to [0,1]^2$ which are surjective.  See http://en.wikipedia.org/wiki/Space_filling_curve for an introduction, and feel free to ask back with questions about what you read.
Answer: The space filling curve is in itselft the limit of a process,iteraded infinitely many times. They key here is that the function built are surjective functions to the limit, which mean they fill the space.You can check out for example This article which gives an introduction to Peano's curve.

Is there a square-filling curve?


Mercurial set per user rights

Question: I would like to set better user access to my mercurial repos trough the cgi web interface. This is my current hgweb.config :
[web]
contact = first.lastname
description = HG Repos
allow_push=user1,user2,user3
allow_read=user1,user2,user3
[paths]
repo01 = /home/mercurial/repo01
repo02 = /home/mercurial/repo02
repo03 = /home/mercurial/repo03
repo04 = /home/mercurial/repo04

How to setup the following ? :

user1 has only access (push/read) to repo01 and repo02
user2 has only access (read only) to repo01 and repo02
user3 has only access (read) to repo01 and repo02, (push/read) repo03

I've checked multiple mercurial config tutorials but nothing helped me so far.
Answer: You don't want to have the [web] section in the hgweb.config file. Instead you want to an individual [web] config in each repository, using the files
/home/mercurial/repo01/.hg/hgrc
/home/mercurial/repo02/.hg/hgrc
etc...

Myself I've found the publishing repositories wiki page to be a good tutorial.

Mercurial set per user rights


Send single stream to multiple users

Question: I intend to send a live video stream to multiple users. Currently, I'm using a webrtc gateway(server-side) to relay an incoming stream to multiple recipients, which incurs one stream per recipient, leading to high outgoing bandwidth.
Is there a method by which the relaying can be done by the network to take the burden off the server?
(My setup is something like this: https://stackoverflow.com/a/28645913/1100528. Webrtc isn't a necessity but I wanted to avoid Flash.)
Comment: Multicasting video is the keyword, although it never gained enough momentum to get adopted by regular ISPs. I'll leave this as a comment because the last time I saw a multicasting video stream was in the late 90ies in the German research network DFN.
Comment: From all the skeptical answers on the internet, I understand there's no feasible multicasting option at the moment. Just to confirm I'm getting this right - multicasting consumes constant bandwidth on the server regardless of the number of requests, right?
Comment: Yes, a client subscribes to a multicasting group via a protocol, IGMP or PIM. Your local switch forwards this to your next multicasting outer, which will ask his connected routers if they know the route to the service, simply speaking. It works like a routing protocol. The server will only send one copy of each packet to the router, and the router knows on which paths subscribers are listening. Ideally a tree will converge so that only routers on the paths to the clients will get the packets and only forward it on the paths leading to clients. The switches will care for final distribution.
Answer: You would probably be best looking into a third party library, something like OpenTok or Peer5.
They provide the ability to manage large multicast streams using a hybrid (p2p/server) network solution, that spreads the workload between peers, minimizing the reliance on a single server.
Comment: You simply cannot multicast across the Internet unless it is through a tunnel. The Internet would collapse under the weight of DM multicast, and SM multicast requires RPs, but would bear the expense of purchasing, and maintaining them.

Send single stream to multiple users


How the session work in asp.net?

Question: Please any one suggest me how the session is actually work in asp.net?
I am confuse in part of session and want to briefly knowledge of it so please guide me
Comment: Try to read this CodeProject article
http://www.codeproject.com/Articles/32545/Exploring-Session-in-ASP-Net
Answer: ASP.NET uses a cookie to track users. When you try to write something to the session for the first time a cookie is sent to the client, something like ASP.NET_SessionId. This cookie is sent by the client on subsequent requests. Thanks to this cookie the server is able to identify the client and write/read the associated session data. It is important to note that this cookie is not persistent (wouldn't survive browser restarts) and is emitted with the HttpOnly flag meaning that client scripts cannot access it.
In addition to cookies you could also configure ASP.NET to use hidden fields or append the session id to the query string on each request.
So the base idea behind session is that the actual data is stored somewhere on the server and the client sends some ID on each request so that the server can know where to find its data.
By default there are 3 places where the actual session data can be stored:

In-Proc: the session is stored into the memory of the application (fastest but if you have multiple servers in a server farm this won't work)
Out-of-Proc: the data is stored into a separate server which has the State service installed (the data is stored in the memory of a separate machine meaning that multiple web servers can work in a web farm)
SqlServer: the data is stored in SQL Server (it's the slowest but most reliable as the session data is stored in a SQL Server database and could servive if the Session server crashes which is not the case with Out-Of-Proc)
Custom implementation: thanks to the extensibility of ASP.NET you could write your own session provider and store the data wherever you like.

Here's a good article on MSDN which explores the ASP.NET Session State.
Comment: I have a doubt , Lets say, I just created a  `AboutUs` page in asp.net Mvc application which just returns a `View` , Will this create a new session for the request for the user or does Session is created using the code in our application like form authentication ?
Answer: Session: [Stored on Server side]
1.If you create the session means,the server stores your session data and creates one SessionID . [Session Data with SessionID stored in State Provider in Server]
2.Then the server Returns the SessionID to the client's browser.
3.Then you can store the returned SessionID in Cookie.
4.Upcoming Subsequent request attached with SessionID can access the Server Data.
Note: Session only for current browser Session and user specific.

How the session work in asp.net?


Python - Retrieving data and labels from a pickle file

Question: I have a pickle file that looks as follows:
[array([[[148, 124, 115],
        [150, 127, 116],
        [154, 129, 121],
        ...,
        [159, 142, 133],
        [159, 142, 133],
        [161, 145, 142]],

       [[165, 136, 145],
        [176, 137, 141],
        [178, 138, 144],
        ...,
        [199, 163, 171],
        [202, 163, 167],
        [200, 158, 163]]]), array([1, 1])]

In a previous question, we were able to retrieve the data and label by doing that separately. But, when I have many images that approach would not be suitable.
My script now looks as follows:
data, labels = [], []
    for i in range(0, 1):

        filename = 'data.pickle'
        batch_data = unpickle(filename)
        if len(data) > 0:
            data = np.vstack((data, batch_data[0][i]))
            labels = np.hstack((labels, batch_data[1][i]))
        else:
            data = batch_data[0][0]
            labels = batch_data[1][0]

        data = data.astype(np.float32)
        return data, labels

When I run the code and print the labels for instance, I always get 1, while I was expecting to get two labels, [1 1] (I'm not sure if they should be displayed as an array?)
What am I doing wrong here?
Thanks.
Answer: I was able to get labels the way you expect it to be. I used
# Create batch data that represents what you are asking, I created three labels and data
batch_data = np.array([[np.random.random((5,5)), np.random.random((5,5)), np.random.random((5,5))], np.array([1,1,1])])

#pickle the data
import pickle
pickle.dump( batch_data, open( "test.pickle", "wb" ) )

# create data and labels seperately

def test_func(batch_data):
    data, labels = [], []
    for i in range(0, batch_data.shape[1]):
        if len(data) > 0:
            data = np.vstack((data, batch_data[0][i]))
            labels = np.hstack((labels, batch_data[1][i]))
        else:
            data = batch_data[0][0]
            labels = batch_data[1][0]
        data = data.astype(np.float32)
    return data, labels

# unpickle
unpickled_batch_data = pickle.load(open( "test.pickle", "rb" ))

# get stacked data and labels
data, labels =  test_func(unpickled_batch_data)
print labels

returns
[1 1 1]

Answer: You may be able to get away with just using zip twice:
In [24]: pickle_data = [array([[[148, 124, 115],
    ...:         [150, 127, 116],
    ...:         [154, 129, 121],
    ...:         [159, 142, 133],
    ...:         [159, 142, 133],
    ...:         [161, 145, 142]],
    ...:
    ...:        [[165, 136, 145],
    ...:         [176, 137, 141],
    ...:         [178, 138, 144],
    ...:         [199, 163, 171],
    ...:         [202, 163, 167],
    ...:         [200, 158, 163]]]), array([1, 1])]

You also need argument unpacking with the * operator:
In [25]: data, labels = zip(*zip(*pickle_data))

In [26]: data
Out[26]:
(array([[148, 124, 115],
        [150, 127, 116],
        [154, 129, 121],
        [159, 142, 133],
        [159, 142, 133],
        [161, 145, 142]]), array([[165, 136, 145],
        [176, 137, 141],
        [178, 138, 144],
        [199, 163, 171],
        [202, 163, 167],
        [200, 158, 163]]))

In [27]: labels
Out[27]: (1, 1)

Now the labels and data correspond by index:
In [28]: data[0]
Out[28]:
array([[148, 124, 115],
       [150, 127, 116],
       [154, 129, 121],
       [159, 142, 133],
       [159, 142, 133],
       [161, 145, 142]])

In [29]: data[1]
Out[29]:
array([[165, 136, 145],
       [176, 137, 141],
       [178, 138, 144],
       [199, 163, 171],
       [202, 163, 167],
       [200, 158, 163]])

In [30]: labels[0]
Out[30]: 1

In [31]: labels[1]
Out[31]: 1

Or better yet, I think, since your images are being stored along the first axis, you can just decompose the array into a list of arrays using a list comprehension:
In [37]: images = pickle_data[0]

In [38]: labels = pickle_data[1]

Decompose the array:
In [39]: images = [x for x in images]

In [40]: images[0]
Out[40]:
array([[148, 124, 115],
       [150, 127, 116],
       [154, 129, 121],
       [159, 142, 133],
       [159, 142, 133],
       [161, 145, 142]])

In [41]: images[1]
Out[41]:
array([[165, 136, 145],
       [176, 137, 141],
       [178, 138, 144],
       [199, 163, 171],
       [202, 163, 167],
       [200, 158, 163]])

In [42]: labels[0]
Out[42]: 1

In [43]: labels[1]
Out[43]: 1

In [44]: labels
Out[44]: array([1, 1])

In [45]: images
Out[45]:
[array([[148, 124, 115],
        [150, 127, 116],
        [154, 129, 121],
        [159, 142, 133],
        [159, 142, 133],
        [161, 145, 142]]), array([[165, 136, 145],
        [176, 137, 141],
        [178, 138, 144],
        [199, 163, 171],
        [202, 163, 167],
        [200, 158, 163]])]

In [46]:


relative link in vue returns with nothing

Question: I have got two components in vue, one with lightbox for images and one for playing audio. I got relative links to the assets but either the images or the audio is being displayed and played. First I thought it was an issue with the component itself but since it doesnt work on either of these it might be something else.
If I provide an absolut url it works however fine for some reason
This doesnt work either when I build the application or locally:
export default {
      components: {
        VueLitebox,
        "vue-audio": VueAudio
      },
      data() {
        return {
          // AUDIO
          file1: "../assets/music/myfile.mp3",

          // LITEBOX
          images: [
            ".../assets/img/myimage.jpg",

This works fine:
export default {
  components: {
    VueLitebox,
    "vue-audio": VueAudio
  },
  data() {
    return {
      // AUDIO
      file1: "http://mypage.com/music/myfile.mp3",

      // LITEBOX
      images: [
        "http://mypage.com/img/myimage.jpg",

I can of course upload the images and music separate and make it work but it feels a bit inconvenient.
What can be wrong?
UPDATE:
Thanks for the answers. Now I got two methods. And both actually works.
One is to put all my assets in the public folder. That solved it with a link like:
"/assets/img/myimage.jpg",

The other way is to using require.
require("../assets/img/myimage.jpg"),

Both works but is there a prefered way?
Comment: Check [this answer](https://stackoverflow.com/a/52083358/3226121)
Answer: You should use require when using assets
file1: require("../assets/music/myfile.mp3")

Without require webpack won't know that you want to bundle that asset and your path will remain unchanged. Actually webpack knows how to handle this kind of files thru the use of plugins and not out of the box.
Regarding the fact that it works with absolute path and not relative ones.
Your relative path is valid in the local file system on your dev server. When deploying the app you are not running in the local file system, but on the web. Even though relative paths are resolved using a similar algorithm, your results will depend on the URL where the component is used and not on the path of the vue file.
For example if the component is rendered on a URL of the form
https://example.com/list/

The relative path would resolve to https://example.com/assets which is probably what you want. But on the following URL
 https://example.com/list/1/

Will resolve to https://example.com/list/assest which isn't what you'd expect.
Webpack takes care of this problems (to some degree, you need to be sure that you don't mess up the base tag).
Comment: Thanks! Now I got two methods. And both actually works. One is to put all my assets in the public folder. That solved it with a link like: ´"/assets/img/myimage.jpg", ´ The other way is to using require.  require("../assets/img/myimage.jpg"),  Is there a prefered way?
Comment: I don't think so. Keep in mind that the absolute path solution will only work for the assets folder. The default vuejs template also has a assets golder under src and for that you must ise require


Autenticação sites externos

Question: Estou utilizando JWT para fazer a autenticação de acesso. Quando tento uma requisição GET de fora do meu sistema, ele exibe essa mensagem:

trecho do código onde faço a requisição (js):
[...]
var cep = this.soNumero(this.state.cep);
var cepUrl = 'https://viacep.com.br/ws/' + cep + '/json/';
axios.get(cepUrl).then(res => {
[...]

Utilizo React e PHP com o Slim Framework
OBS: Se quiserem testar o link, é só colocar qualquer CEP no lugar da variável no código (Ex.:https://viacep.com.br/ws/37701140/json/)
Answer: Você está passando por default um header que o server-side (ViaCEP) não aceita, que é o X-Access. Limpe o seu header default antes da requisição:

axios.defaults.headers.common = {}
axios.get('https://viacep.com.br/ws/01311200/json/')
      .then(res => console.log(res.data))

Autenticação sites externos


Show that $S_n = X_1+ \cdots X_n $ the probability density function $f_{s{_n}}$

Question: We consider $(\Omega, \mathcal{F}, \mathcal{P})$ a probability space and $(X_{n})_{n \in \mathbb{N}}$ a sequence of independent and identically distributed random variables such that $X_1 \sim \operatorname{Unif}(-1,1)$. Show that $S_n = X_1+ \cdots X_n $ for $n \ge 2$ has  the probability density function $$f_{s{_n}} = \frac{1}{n} \int_{0}^{\infty} \Bigg(\frac{\sin(t)}{t} \bigg)^n \cos(xt)dt $$
I have found out that I could use that $|\frac{\sin(t)}{t}|\le1$ for $\forall t \in \mathbb{R}$ and I have also calculated that $$\int_{0}^{\infty} \Bigg(\frac{\sin(t)}{t} \bigg)^2 dt = \frac{\pi}{2}$$ At this point I have no clue how should I continue it I would really appreciate any kind of help since I'm learning the topics on my own.
Comment: If $X_1,\dots,X_n$ are any independent r.v.s with probability distributions $\mu_1,\dots,\mu_n$, then the probability distribution of their sum is the convolution $\mu_1*\dots*\mu_n$. For the rest, just use the Fourier transform.
Comment: https://math.stackexchange.com/q/3615897/321264
Answer: The characteristic function of $S_n$ is
$$\phi_{S_n}(t) = E[e^{itS_n}] = \prod_{k=1}^n E[e^{itX_k}] = \left(\frac{e^{it} - e^{-it}}{2it}\right)^n = \left(\frac{\sin t}{t}\right)^n.$$
The inversion theorem shows how you can compute the density $f_{S_n}$ if you know the characteristic function $\phi_{S_n}$.
\begin{align}
f_{S_n}(x)
&= \frac{1}{2\pi} \int_{-\infty}^\infty e^{-itx} \phi_{S_n}(t) \, dt
\\
&= \frac{1}{2\pi} \int_0^\infty e^{-itx} \phi_{S_n}(t) \, dt + \frac{1}{2\pi} \int_0^\infty e^{iux} \phi_{S_n}(-u) \, du
& u = -t
\\
&= \frac{1}{2\pi} \int_0^\infty (e^{itx} + e^{-itx}) \phi_{S_n}(t) \, dt
& \phi_{S_n}(-t) = \phi_{S_n}(t)
\\
&= \frac{1}{\pi} \int_0^\infty \cos(tx) \phi_{S_n}(t) \, dt.
\end{align}
Comment: $\frac{1}{\pi}$ makes more sense than $\frac{1}{n}$
Answer: Characteristic function will work.  Ley $f(x)$ be density function for $X_k$.  $\phi(t)=\int_R e^{itx}f(x)dx$.  Then density function for $S$ is given by $f_S(x)=\frac{1}{2\pi}\int_R e^{-itx}\phi^n(t)dt$.
Comment: I'm very sorry but I really don't know how can I get the density function could maybe someone help me a bit in this part? May a little bit more detailed way could make me clear how does it work exactly. Thank you very much in advance
Comment: Wikipedia has a detailed discussion of characteristic function.


Non-Linear Techniques

Question: This Question is a practice exercise assigned to us. I have the answer but I don't find it very intuitive. The answer I have is on this pdf : http://math.stanford.edu/~ralph/math53h/solution5.pdf
Find a global change of coordinates that linearizes the system
$x' = x + y^2$
$y' = −y$
$z' = −z + y^2$
Please do not give negative rating before giving me a chance to make corrections if any errors are found in the question.
Comment: "Please do not give negative rating before giving me a chance to make corrections if any errors are found in the question." +1
Answer: We are asked to find a global change of coordinates that linearizes the nonlinear system:
$\tag 1 x' = x + y^2$
$\tag 2 y' = −y$
$z\tag 3' = −z + y^2$
From $(2)$, we get:
$\tag 4 y = y_0 e^{-t}$ (You know how to solve this, correct?)
Lets now substitute this into $(1)$ and solve that DEQ:
We have $x' - x = y^2 = (y_0 e^{-t})^2 = y_0^2 e^{-2t}$. Lets work the details of this one as a sample manually.
Homogeneous: $m - 1 = 0 \rightarrow m = 1 \rightarrow x_h = x_0e^t$
Particular: Assume $x_p = Ae^{-2t}$, so $x' - x = -2Ae^{-2t} - A e^{-2t} = y_0^2 e^{-2t}$, so $-3A = y_0^2 \rightarrow A = -\frac{1}{3} y_0^2$.
Thus, we get $x = x_h+x_p, so$:
$\tag 5 \displaystyle x(t) =  x_0 e^t - \frac{1}{3} y_0^2e^{-2t}.$
Lets now repeat this process for $(3)$ and solve that DEQ:
We have $z' + z = y^2 = (y_0 e^{-t})^2 = y_0^2 e^{-2t}$, and solving for $z$ yields:
$\tag 6 z(t) =  z_0 e^{-t} - y_0^2e^{-2t}.$
Next, our goal is to get rid of the nonlinear terms in $x, y$ and $z$ by finding a 'global change of coordinates'.
What if we choose a change a variables that guarantees those nonlinear terms disappear? How can we do that?
Let: $\displaystyle u = x + \frac{y^2}{3} = x_0 e^t - \frac{1}{3} y_0^2e^{-2t} + \frac{1}{3} y_0^2e^{-2t} = x_0e^t.$
So, we have: $u = x_0e^t$.
If you take the derivative of $u$, what do you get?
$u' = x_0e^t$. In other words $u' = u.$ (That nicely linearized.)
Next, if we let: $v = y = y_0e^{-t}$, what is $v'$? Well, $v' = -y_0e^{-t} = -v$. (That nicely linearized.)
If we let (note - there is a slight typo in the solution key here, they meant $y^2$):
$w = z + y^2 = z_0e^{-t} -y_0^2e^{-2t} + y_0^2e^{-2t} = z_0e^{-t}.$
If we take the derivative of this, we get $w' = -z_0e^{-t} = -w$. (That nicely linearized.)
We are now left with a linearized system:
$\tag 7 u' = u$
$\tag 8 v' = -v$
$\tag 9 w' = -w$
They wrote the solution in a very compact/condensed form and maybe that was throwing you off. I would recommend comparing the above with what they wrote and make sure it is clear!
Hope that makes sense!
Comment: Thank @Amzoti. I am still reviewing the answer.
Comment: Take your time and go through each step - rewrite it and ask if any step is confusing! Regards
Comment: So very thorough $+1^{\infty}$ for all that work!
Comment: @amWhy: thank you. I can see how the solution could be confusing the way it was written, maybe that was intentional to let them work through the details, but interesting problems nonetheless! Regards
Comment: It's nice when we can combine being helpful and finding the question interesting, at the same time ;-)
Comment: @Amzoti why do you have 1/3 in step (5). This may be something obvious but I cant grasp it.
Comment: @KjTada: see my update to the answer. Just assume a particular soultion, take $x' - x = x_p$ and solve for constant (see answer above). Regards
Comment: Seems slow tonight (for me anyway). Will need to head to bed soon, but I was hoping Babak would "appear" before that!
Comment: @amWhy: Agreed - I have been editing, doing reviews and listening to good music! Slow night, and I have not seen Babak ina couple of days. Have a great night - getting close to bedtime for me too!

Non-Linear Techniques


In how many ways can we choose 5 balls from the box so that we have at least one blue ball?

Question: A box has ten blue balls numbered from 1 to 10 and ten green balls numbered from 1 to 10.
In how many ways can we choose 5 balls from the box so that we have at least one blue ball?
I'm trying to do it by subtracting total by no blue balls but I don't think I'm getting the right answer
Has exactly one blue ball--$5*10*10*9*8*7$ (5 because the first step is to chose where the blue ball goes)
is that how you're suppose to do it then do 2 blue balls etc?
Comment: Do you distinguish between different balls of the same color?
Comment: @M.B. Given that they are numbered, looks like it.
Comment: Oops, sorry. :)
Answer: The order in which the balls are drawn is irrelevant. Let the green balls have numbers from $1$ to $10$ and the blue balls have numbers from $11$ to $20$.
There are ${20\choose 5}=15\,504$ subsets of five balls from all twenty balls.
There are  are ${10\choose 5}=252$ subsets of five balls from these twenty balls, when only the numbers from $1$ to $10$ may occur.
It follows that $15\,504-252={\bf 15\,252}$ subsets of five contain at least one ball with number $>10$.
Answer: Hint:
If you want to subtract the total by no blue balls, that's a good way to do it.
The total is ${n}\choose{k}$. Now let's think about how many ways we can choose $10$ green balls. Well, on the first pick there are $10$ ways to pick a green ball, since there are $10$ green balls. After that there are $9$ ways to pick the next green ball. Hence we have $10*9*...$
Can you solve it from here?
Comment: Lets say there are 3 green balls numbered 1,2,3. Is it 6 ways of drawing 3 balls from this collection?
Comment: 123, 132, 213, 231, 312, 321. 6 ways. In other words, 3*2*1
Comment: Yeah, but I would assume those are counted as equal.
Comment: I see. Well, I guess I'm making a different assumption. I mean, suppose you have 9 red balls and 1 black ball. You have one pick. I would say you have 9 ways of choosing a red ball and only 1 way to pick a black one
Comment: Sure, and I would agree! But that is not what we are disagreeing on.
Comment: In that case, I guess I'm not following you. Did I do something wrong?
Comment: I would agree that picking ball 1 is different from picking ball 9. I would however not agree that if we were to draw two balls then 1,2 and 2,1 are to be viewed as different.
Comment: let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/11408/discussion-between-kbball-and-m-b)
Answer: The key instrument you have to use here is the binomial coefficient $\binom{n}{k} = \frac{n!}{k!(n-k)!}$, which indicates the number of possible ways to choose $k$ elements from a set of $n$ objects.
The number of ways to draw exactly $1$ blue ball is found as follows: You choose $1$ blue ball among $10$, and then $4$ green balls among $10$, so you get
$$\binom{10}{1}\binom{10}{4} = \frac{(10!)^2}{9!4!5!} = 12600$$
possible ways. Obviously if you want also to take into account the order of drawing, you have to multiply by $5! = 120$.
Now you can use this method to find the number of ways you can draw at least one blue ball.
Comment: That's the answer for *exactly* one blue ball.  The OP asked for *at least one*.
Comment: @BarryCipra Sure, but I wanted to leave to the OP the computation for $2$, $3$ etc. blue balls as an exercise, in order to undertand how it works.
Answer: I think your method is best, regardless of whether you think your answer is right.
There are $\binom{20}{5} = \frac{20!}{5!15!} = \frac{20*19*18*17*16}{5!}=19*3*17*16$ total ways to choose 5 balls.
To choose only green balls, there are $\binom{10}{5} = \frac{10!}{5!5!}=\frac{10*9*8*7*6}{5!}=9*8*7$ total ways. Hence there must be $19*3*17*16 - 9*8*7 = 15000$ ways to choose at least one blue ball.


Alimentar variável dentro de variável

Question: Em JS tenho a seguinte linha:
var recebeMensagem = '';
var mensagemBot = '
'+recebeMensagem+'
';
// 1ª mensagem
recebeMensagem = 'Olá';
$('.recebe_as_mensagens').append(mensagemBot);

Mas quando rodo esse trecho do código, não aparece a mensagem Olá dentro da DIV, ela vem vazia. Mas se no começo do código var recebeMensagem = ''; eu já alimentar ela com Olá, aparece, como fazer da forma que estou tentando?
Pois o projeto é mais complexo, precisaria ser +- como mostrei....
Comment: Você recebe essas mensagens como?
Answer: Vou arriscar uma adaptação do código que pode ser o que você deseja. Seguindo a linha da resposta do Netinho, acredito que possa resolver. Se for isto, os créditos são do Netinho, pois apenas adaptei seu código.
var recebeMensagem = []

var mensagemBot = '
' + recebeMensagem + '
';
var conteudoHtml = '';
conteudoHtml = $('.recebe_as_mensagens').html();

recebeMensagem += 'Olá';
recebeMensagem += 'Tudo bem?';
recebeMensagem += 'Tchau';

conteudoHtml += mensagemBot;
$('.recebe_as_mensagens').html(conteudoHtml);
$(".bot_mensagens").text(recebeMensagem)

Aqui você tem um vetor em Javascript recebeMensagem = [], agora basta ir jogando os itens para dentro do vetor e as mensagens serão armazenadas em posições diferentes.
Seguindo a mesma lógica, é possível varrer seu array e mostrar os resultados da seguinte forma:
for(var i = 0; i < recebeMensagem.length; i++){
  conteudoHtml = mensagemBot;
  $('.recebe_as_mensagens').html(conteudoHtml);
  $(".bot_mensagens").text(recebeMensagem)
}

Veja no JsFiddle

Espero que ajude, apenas tentei adequar a lógica, não tenho muita experiência com Javascript. Abraços!
Answer: O que você quer não corresponde ao conceito de "variável".
Variável é um espaço de memória que será reservado para guardar valores pelo seu programa/aplicação. O que você quer talvez possa ser atingido por uma propriedade (ai estamos entrando no conceito de orientação à objeto) ou uma função.
A linguagem do javascript permite que sejam criadas funções "inline" e para o seu propósito podemos usar uma aproximação do seu código como exibido abaixo:

var recebeMensagem = '';
var mensagemBot = function() {
    return '
' + recebeMensagem + '
';
};
var conteudoHtml = '';
conteudoHtml = $('.recebe_as_mensagens').html();
recebeMensagem = 'Olá';
conteudoHtml += mensagemBot();
$('.recebe_as_mensagens').html(conteudoHtml);

Só ratificando, no exemplo acima, cada vez que a função mensagemBot() for utilizada, ela vai trazer o elemento div com o conteúdo igual a ao da variavel recebeMensagem no seu retorno. (Se o conteúdo da variável for alterado, o retorno da função também o será).
Answer: Você pode usar um pouco mais do ES6 se quiser deixar seu código mais fancy.
const outputMessage = message => `<div class="bot_mensagens">${message || 'Olá'}</div>`;
$('.recebe_as_mensagens').append(outputMessage());
$('.recebe_as_mensagens').append(outputMessage('Tc de onde?'));

Answer: Você está recebendo o valor na variável recebeMensagem e não está a usando em nenhum lugar. Para setar o valor da variável na div use a função text()

var recebeMensagem = '';
var mensagemBot = '
' + recebeMensagem + '
';
var conteudoHtml = '';
conteudoHtml = $('.recebe_as_mensagens').html();
recebeMensagem = 'Olá';
conteudoHtml += mensagemBot;
$('.recebe_as_mensagens').html(conteudoHtml);
$(".bot_mensagens").text(recebeMensagem)

Comment: Obrigado, mas desse jeito eu sei que é possível, o problema é que não posso fazer assim. A variável recebeMensagem ta lá, dentro da mensagemBot, eu teria que atualizar a mensagemBot, sem precisar reescrver ela
Comment: Pelo que entendi a solução proposta pelo Netinho não ajuda pois você está falando que ao alterar o valor de `recebeMensagem` todas as mensagens já enviadas seriam reescritas para o último valor enviado, certo? Uma dúvida, você já pensou em utilizar um vetor (array)? Pode resolver seu problema.

Alimentar variável dentro de variável


How to upload a CSV file to a new tab(sheet) in the google spreadsheet

Question: I want to write a script that can automatically upload the CSV file to a google spreadsheet.
And following is my code to realize it:
import csv

import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ["https://spreadsheets.google.com/feeds", 'https://www.googleapis.com/auth/spreadsheets',
         "https://www.googleapis.com/auth/drive.file", "https://www.googleapis.com/auth/drive"]

credentials = ServiceAccountCredentials.from_json_keyfile_name('client_secret.json', scope)

client = gspread.authorize(credentials)

sheetName = "abc"
spreadsheet = client.open("abc")
worksheet = spreadsheet.worksheet(sheetName)
content = list(csv.reader(open('123.csv')))
worksheet.append_rows(content, value_input_option="USER_ENTERED")

However, this script can only append the values under the same sheet, and my boss asked me to upload CSV to a new tab under the same spreadsheet every day. For example, today I am going to upload CSV data to CSV-to-Google-Sheet, tomorrow I am going to upload it to sheet1. Please check the screenshot I attached.
I googled the related information for hours but find nothing useful. What should I do?
As you can see there are two tabs at the bottom of the sheet, one is called CSV-to-Google-Sheet, the other is called sheet1:
Answer: As you need to put the data each day on a new page, my suggestion would be for you to create a new page with the name of today's date and then add the values:
import gspread
from oauth2client.service_account import ServiceAccountCredentials
import datetime

scope = ['https://spreadsheets.google.com/feeds']
dicter = 'client_secret.json'
creds = ServiceAccountCredentials.from_json_keyfile_name(dicter, scope)
client = gspread.authorize(creds)

id_file = 'xxxxxxxxxxxxxxxxxxxxxxx'
spreadsheet = client.open_by_key(id_file)

today = datetime.date.today()
worksheet = spreadsheet.add_worksheet(title=str(today), rows=1000, cols=26)
worksheet.update('A1',[['test','test_2']])

Additional note:
Always try to use the file ID to open instead of using the name, it's a bit risky if you or someone else edits the name (it's easier for someone to edit the file name than you delete the file and create another one).
The ID → xxxxxxxxxxxxxxxxxxxxxxx I used can be found at:
https://docs.google.com/spreadsheets/d/xxxxxxxxxxxxxxxxxxxxxxx/

Comment: Sorry, what is the 'sh' on line 5?
Comment: It works! Thank you! I don't have a 15 reputations now XD so I cannot give you a upvote, but I will do so immediately after I got the 15 reputations!
Comment: Hi @TryingToLearnSomething ```sh.``` has been edited to ```spreadsheet.``` for better viewing, it is the specification of the file opened by you.
If it solves your problem, please mark the answer as a solution and if you liked the approach, give an additional upvote.
Comment: Ummm, it shows me an error "Object of type date is not JSON serializable" for worksheet = spreadsheet.add_worksheet(title=today, rows=1000, cols=26), I guess it's date package problem?
Comment: @TryingToLearnSomething could you please test with ```title=str(today)```?
Comment: @TryingToLearnSomething test using ```spreadsheet.add_worksheet(title=str(today), rows=1000, cols=26)```
Comment: @TryingToLearnSomething I made some edits and additions to the answer.


How to validate nested fieldsets in Zend Framework 2 without using factory

Question: I've got a form class that dynamically creates fieldsets with elements/fieldsets recursively. I do this to get settings[general][rpp][value] as an input name (for example). The fields get generated because the settings are user defined in an XML file.
Fieldsets are getting created like this:
$fieldset = new Fieldset(...);
$fieldset->add(...);
$form->add($fieldset);

The form is being output correctly; everything works. Except i need validation.
My goal is to define validators and filters for these nested elements. I'm really confused at how it works - but it looks like just the form itself defines an input_filter setInputFilter(...) and i don't know how to get it to recognize the recursion without a factory and proprietary classes for the fieldsets instead of being dynamic.
Am i clear?
Thanks.
Comment: In short, the Fieldsets have to provide their own validation Rules using the `InputFilterProviderInterface`.
Answer: I've figured out how to do this highly dynamic type of form with validation and filters. I will explain here with this hypothetical script:
// create a form instance and a filter instance
$form = new Form();
$filter = new InputFilter();

// create a fieldset instance and another filter instance
$fieldset_a = new Fieldset('general');
$fieldset_a_filter = new InputFilter();

// create element(s) to assign to fieldset
$setting_1 = new Element('setting_1');

// create another input filter for element defining filters and validators
$setting_1_filter = new InputFilter(array(
    'name' => 'setting_1',
    'required' => true,
    'validators' => array(), // ...
));

// add element to fieldset
$fieldset_a->add($setting_1);
// add fieldset to form
$form->add($fieldset_a);

// add element filter to fieldset filter
$fieldset_a_filter->add($setting_1_filter,'setting_1');
// add fieldset A filter to main input filter
$filter->add($fieldset_a_filter,'general');

$form->setInputFilter($filter);

So you can see you have to create input filters for each set of elements and each fieldset and then work backwards through them adding them to each other until the main input filter is built and you can assign it to the form instance.
This then would use the supplied validators with input names such as general[setting_1] after running $form->setData($this->request->getPost()) - $form->isValid()
This response could be 100 times more detailed, but it's better than what is available on the subject of dynamic fieldset validation.
Answer: here, in the ZF2 docs is explained as well http://framework.zend.com/manual/2.3/en/modules/zend.form.collections.html
Comment: No sure why you were given a down vote for this. The link you have referred to explains the solution (if you have created your forms correctly).
Comment: Answers that only contain links are generally frowned upon. The answer itself should provide an explanation.


VS2015/vb Not Picking Up Reference

Question: I'm working on a Visual Basic project using Visual Studio Community 2015. I need to convert an Excel spreadsheet to a PDF document. I have added the Microsoft.Office.Interop.Excel dll as a reference and it is showing up in my Reference list from Solution Explorer. When I look at that dll, it contains a class called Workbook. However, when I try to use this class, I'm getting a compile time error saying that this type does not exist. I'm very new to this environment and don't understand what I've forgotten to do. Here is the line of code where I'm getting the compile time error, and I will try to attach a screen print showing that I do have the dll in my references.
<code>Dim myworkbook As New Workbook()[![reference list and class list within it][1]][1]
</code>
Answer: Before you can use the name "Workbook" unqualified, you will need to import the namespace which contains the class:
<code>    Imports Microsoft.Office.Interop.Excel

    Dim myworkbook As New Workbook()
</code>
Or you could use the full name:
<code>    Dim myworkbook As New Microsoft.Office.Interop.Excel.Workbook()
</code>

VS2015/vb Not Picking Up Reference


How to send an email notification when a page is visited?

Question: Is there a way to send an email notification if a certain page is visited?
(Triggers an email saying the page was viewed)
Ie. User comes to this page: thank-you.php
And email is automatically sent to the admin of the website upon page load.  Then the user gets redirected to another page right after this email trigger as been sent.
EDIT ---
I would need to check if a user came from a specific domain name or URL. This is to avoid exploits or other misc. submission hacks.
Any suggestions?
Comment: Does the code need to be able to tell the difference between a human and a bot?  Are you only interested in unique visitors, or do you want an email every time the page gets hit?  Do you need to implement some kind of threshold so that you don't get flooded with emails if somebody refreshes the page a bunch of times?
Comment: Yes Pheonix, it should check for something. It needs to check if it comes from a specific domain. Will add this to the question.
Answer: Try:
<code><?php
// The message
$message = "Line 1\nLine 2\nLine 3";

// In case any of our lines are larger than 70 characters, we should use wordwrap()
$message = wordwrap($message, 70);

// Send
mail('email@example.com', 'My Subject', $message);

// Redirect
header('Location: anotherpage.php');
?>
</code>
Comment: Richard, is there a way to add this in a condition that checks if the URL referrer meets a certain domain name?
Comment: @detonate Yes, this is possible. You could use: `if (isset($_SERVER['HTTP_REFERER']) && preg_match('/^http:\\/\\/www\\.yourdomain.com\\//',$_SERVER['HTTP_REFERER']))`. Remember that this is set by the user agent. Not all user agents will set this, and some provide the ability to modify HTTP_REFERER as a feature. Some antivirus software will delete the HTTP_REFERER. In short, it cannot really be trusted.
Comment: ok thanks for the tip Richard. Would you have another alternative suggestion?
Comment: Depending on the purpose, I would recommend mailing on a weekly basis. If `cron` isn't an alternative, you could use a script to append the visit to a text file and then send and delete the text file on the first visit the next week. Simply load the `$message` from the text file with `file_get_contents()`.
Comment: Interesting, I've never worked with cron... this might take me too long to implement and deploy. I wish we could send something that would alert via an email notification without writing up to a text file etc. Never thought this would've become such a task!
Comment: This is a good start, I'll have to look into stopping floods or other  crawlers... any other suggestions would be nice!
Comment: @detonate You could also use HTTP_USER_AGENT to distinguish between crawlers and users. To improve my answer, I need some more information. If we suppose that there are 20 visitors every day, how many e-mails would you like during a week?
Answer: Yes, the mail function.
But I think you should reconsider this design - imagine what will happen if the page suddently gets hit by thousands upon thousands of users - or a buggy web crawler. A log file or database update is alot easier to handle.
Comment: This is one of the things Anders. I would need to check if a user came from a specific domain name. Would this be secure enough?
Comment: Ask the person who will have to handle the mails, and ask yourself _what_ the person will do with the mail. Is it a trigger to a manual routine that should be automated aswell?
Comment: No, just to notify that someone visited this page via email.
Comment: You should plan for mail flooding at the design phase, and try to group the messages in a way that satisfies both the admins request for feedback with the potential millions-of-mails scenario. How about a combined report every (week|day|businessday|hour|15 minutes)?
Comment: A daily report seems like a good idea. The email flood is definitely something to consider here. How would you put all of this together Anders? (Check for domain name referrer and send a notification once a day).
Comment: Depends on how much information is needed - a simple cron job `grep`ing in the web server log might be enough, but you could also go for one of the many web log analyzers: http://en.wikipedia.org/wiki/List_of_web_analytics_software
Comment: Anders, is there a way to simplify this. Avoiding cron jobs and log analyzers. I really want to keep this simple but functional.
Answer: Yes. Just use this at any place in your page: PHP Mail
Comment: Jed, Made and edit to my question. Is there a way to add this in a condition that checks if the URL referrer meets a certain domain name?


Is it a foul in football if the pursuer unintentionally clips the runner from behind?

Question: When I play recreational football, I pursue my man or a player a lot.  Sometimes, out of nowhere, their back foot clip my thigh while running and they trip.  It looks bad from far away and a foul is taken. I haven't done much besides running behind them or a bit on the side.
In another case, I was standing still and when the player twist and run, the same thing happen.
Is an unintentional clipping from behind considered as a foul in football?
Comment: wth? you're asking 2 questions here, one about football, and one about ultimate. The rules are going to be completely different for the two sports. Please split this question.
Comment: @waxeagle - I agree.  I've edited the question to remove the ultimate aspects.  The OP can ask a new question if he wants an answer regarding ultimate.
Answer: It's a short answer, but "Yes".
If you impede a player unfairly then your team will be penalised with the appropriate free-kick/penalty and possible card.
It doesn't matter if it's accidental or not, you have still impeded the player.
Law 12 (Misconduct) of the Laws of the Game state:

A direct free kick is awarded to the opposing team if a player commits any
  of the following seven offences in a manner considered by the referee to be
  careless, reckless or using excessive force:
[..]

trips or attempts to trip an opponent

The key word here is "careless".  When running behind a player you need to take care that you don't trip him.  If you do, you will be penalised with a direct free-kick against your team.
Comment: Plus it's often a cynical way of stopping a player who's got past a defender.