Angle in a triangle within a circle.

Question: A and B are two points on the circumference of a circle with centre O. C is a point on OB such that AC $\perp OB$. AC = 12 cm. BC = 5 cm. Calculate the size of $\angle AOB$, marked $\theta$ on the diagram.

The answer given in the textbook is $45.2 ^\circ$ (1dp)
Note: This is not a homework question. I'm just doing maths for my own interest.
Answer: let radius = $r$, then in triangle ACO, using Pythagoras:
$$\begin{align}
AO^2 &= AC^2+CO^2\\
\\
r^2 &= 12^2+(r-5)^2\\
\\
144+25-10r &= 0\\
\\
r &= 16.9\\
\end{align}$$
In triangle ACO,
$$\begin{align}
\sin\theta &= \dfrac{12}{r}\\
\\
\sin\theta &= \dfrac{12}{16.9}\\
\\
\theta &= 45.2^{\circ} (1dp)\\
\end{align}$$
Answer: Radius $AO=BO=x$ CM(say)
So, $OC=OB-BC=x-5$ i.e., $x\ge5$  and $AC=12$
We have $AO^2=OC^2+AC^2$
$\angle AOB=\arctan\dfrac{12}{x-5}$
Comment: You didn't calculate $x$.
Comment: @ZubinMukerjee, I left it for Blakes7
Answer: Draw line AB, and observe that ABC is a (5,12,13) right-angled triangle. Since AB is a chord, the bisector of angle AOB also bisects AB, call this point T. Now triangle OTB is similar to triangle ACB. Therefore angle AOB is:
2 * arctan(5/12)
Which a handy calculator says is 45.2 degrees.
(I'm surprised someone marked this down: I did get the answer, which one other answer didn't, and I think it's neater than the other answer, since you need almost no calculation.)
Comment: I didn't down vote but I am having trouble intuitively seeing why OTB is similar to ACB...
Comment: The line AB and its midpoint T aren't in the diagram, and I don't have the means to draw them, but then: angles TBO and ABC are coincident, and angles OTB and BCA are right angles. So angles are all the same.
Comment: I think this user down votes answers that don't meet his exact criteria or expected format.

Angle in a triangle within a circle.


A first differenced time series

Question: I have differenced my time series because is not stationary.Now in my model I will use this time series, but I have a value less.Is this correct?Thank You.
Answer: Yes, that is correct.

If your original series has one data point, you can't difference it.
If your original series has two data points $y_1, y_2$, your differenced series has one: $y_2-y_1$.
If your original series has three data points $y_1, y_2, y_3$, your differenced series has two: $y_2-y_1, y_3-y_2$.

And so forth. Each time you take differences, you lose one data point. (If you difference twice, you lose two points.)
Comment: Thank you very much.My original data has 24 observation (from the year 1994-2017) and after differencing I obtain 23.But can I insert this data in my model, if the other time series have 24 observations?
Comment: It depends on the relationship between the other data and the series you are differencing. If you believe that a predictor's value in 1994 has an impact on the increment of the focal series (the one you are differencing) between 1994 and 1995, then include the values of the predictor for 1994-2016 to model the differences in your focal series.
Comment: Dear Stephan,thank you for helping me and sorry for my english(is not very good). I should insert the differencing time series in the model, but my question is: is correct having 23 observations, when other time series have 24?For example, in "r" when I use to find the lag order, using VAR select function, and I insert my data, for the time series that I am differencing "r" shows the message:missing data (for example: Error in VARselect(variablat4, lag.max = 10, type = c("none")) : NAs in y.)
Comment: Maybe I have to use the function na.omit for non having missing data?

A first differenced time series


In flex container, position child 1 on top, and stack 2 and 3 at bottom

Question: I am using flexbox to get the height of the parents to be the same (need them to match) and flex-wrap to wrap every 3.
I then have a button that is always going to be at the bottom.
The first child will always have different sized heights, but always the same width.
Now the trick is, I want child 2 to be at the bottom on top of the button and have both clear the content of child 1.
Absolute positioning will not clear the text of child 1.
I tried flex-grow, but it didn't work for me, maybe because I am new to flexbox.
Please look at the fiddle: https://jsfiddle.net/mm783qc6/4/

.contain {
  display: flex;
  border: 1px solid #000;
  width: 100%;
  flex-wrap: wrap;
}
.p {
  width: 29.5%;
  float: left;
  position: relative;
  margin: 0 10px 30px;
  border: 1px solid red;
}
.bb {
  position: absolute;
  bottom: 0;
  border: 1px solid green;
}
.c1 {
  border: 1px solid blue;
}
.c2 {
  border: 1px solid orange;
}

Random Height and text Random Height and text Random Height and text Random Height and text Random Height and text Random Height and text Random Height and text Random Height and text Random Height and text

Go to bottom, but on top of bottom bumper - text can grow sdfkjlkfdj;lksjdf;

---------------Button--------------

Random Height and text Random Height and text Random Height and text Random Height and text Random Height and text Random Height and text Random Height and text Random Height and text Random Height and textRandom Height and text Random Height and
        text Random Height and text Random Height and text Random Height and text Random Height and text Random Height and text Random Height and text Random Height and text

Go to bottom, but on top of bottom bumper - text can grow sdfkjlkfdj;lksjdf;

-------Button-------

Random Height and text Random Height and text Random Height and text Random Height and text Random Height and text Random Height and text Random Height and text Random Height and text Random Height and textRandom Height and text Random Height and
        text Random Height and text Random Height and text Random Height and text Random Height and

Go to bottom, but on top of bottom bumper - text can grow sdfkjlkfdj;lksjdf;

-------Button-------

Random Height and text Random Height

Go to bottom, but on top of bottom bumper - text can grow sdfkjlkfdj;lksjdf;

---------------Button--------------

Random Height and text Random Height

Go to bottom, but on top of bottom bumper - text can grow sdfkjlkfdj;lksjdf;

-------Button-------

Random Height and text Random Height

Go to bottom, but on top of bottom bumper - text can grow sdfkjlkfdj;lksjdf;

-------Button-------

Answer: Try making your class p elements into flex containers with column-direction. Then using auto margins to push children 2 and 3 down to the bottom. This method aligns the items as you want, and prevents overlapping.
Revised CSS
.contain {
    display: flex;
    border: 1px solid #000;
    width: 100%;
    flex-wrap: wrap;
}

.p {
    width: 29.5%;
    /* float: left;              <-- remove; not necessary */
    /* position: relative;       <-- remove; not necessary */
    margin: 0 10px 30px;
    border: 1px solid red;

    display: flex;               /* new */
    flex-direction: column;      /* new */
}

.bb {
    /* position: absolute;       <-- remove; not necessary */
    /* bottom: 0;                <-- remove; not necessary */
    border: 1px solid green;
}

.c1 {
    border: 1px solid blue;
    margin-bottom: auto;         /* new; push self to top, everything else to bottom */
    flex: 1;                     /* new; consume all available free space */
}

.c2 {
    border: 1px solid orange;
}

Revised Fiddle
Learn more about flex auto margins here: Methods for Aligning Flex Items along the Main Axis
Also, if you are wanting equal height columns to extend beyond the first row – i.e., you want the items on the second row to match the height of items on the first row – this is not possible with flexbox. I explain the reason here: Equal height rows in a flex container
Comment: Drat, oh well.  Thanks again.
Comment: Got it to work with some crazy useage of padding-bottom.  http://jsfiddle.net/kJL3u/394/  I took off the flex-child and added a couple divs.  To note the c1's  are really images for me - they will always be square.  The width of the square-box containers are driven by bootstrap - .square-box{
    width: 100%;
    text-align: center;
    padding-bottom: 100%;
    position:relative;
}
.box-item {
    position:absolute;
}
Comment: Works like a charm.  Thank you for your answer and the time it took.  It was really helpful.
Comment: Second question - https://jsfiddle.net/mm783qc6/8/

How would you get c1's height to be equal - then have c2 snap to the bottom of c1 and c3 on bottom of the parent.  See fiddle for example.  As you see in the first column "Go to" is not aligned with the others.  Didn't think of that.  I can add another question to stack if need be.
Comment: I want all c1 to be equal height and all c2 to snap to the bottom of c1.  Then c3 to be at the bottom of the parent. All clearing each other of course.  I started typing the second question, let me know.  Also, each row can have a different c1 height - as in row one all three 100px, row 2 all 146px, etc.
Comment: Can't do that with flexbox. Equal height columns exist among *siblings* in a flex container. So your class `p` elements share equal height. Your `c1` elements are not siblings. They are cousins. As such, there is no flex equal height feature. You could hard-code an equal height for the `c1` class, or find a way to re-structure your HTML making `c1` siblings in the same container.


How to prevent dynamic library definition from being cached?

Question: I have a use case where i want to dynamic add library  , Attributes of library will vary with page. In my case the $callback will be different depending on the page.

$libraries['sample.my-lib'] = [
    'js' => [
      '//maps.googleapis.com/maps/api/js?'.$key.'&callback='.$callback
       => [
        'type' => 'external',
        'attributes' => [
          'async' => "true",
          'defer'=> 'true'
        ],
       ],
    ],
    'weight' => '2200',
  ];

The above code works but when i navigate to different page i have to clear the cache to get updated value of $callback.
I have tried hook_library_info_alter but library definition is still cached.
How can i work around it to make my use case work.
Comment: This depends on how dynamic this should be, see the official Drupal documentation [Dynamically generated CSS and JS](https://www.drupal.org/node/2274843#dynamic-css-js)
Answer: You could trigger Drupal::service('library.discovery')->clearCachedDefinitions() every time, but that seems like a painful workaround performance-wise. All library definitions for a particular theme seem to be stored in a single cache entry library_info:$activeTheme, which doesn't allow any more finely grained invalidation.
Would the range of values of "callback" allow you to loop through them and define a separate library for each one you use, and then attach the specific one you need? The JS gets loaded on demand, so only the attached library would appear on each page.
foreach (static::CALLBACKS as $name) {
  $libraries['sample.my-lib.' . $name] = [
    //...
  ];
}

Or maybe it would be possible to call the appropriate callback from a single main function (possibly setting the callback via a drupalSettings attachment), allowing you to put a fixed value in the Google Maps API URL?
Answer: Don't make the library dynamic, instead provide dynamic drupalSettings.


Como mandar de volta a resposta do meu array para views?e aparecer dentro das td

Question: //PASTA VIEWS
<?php
$botao="Sorteio";
$action="sorteio1";
?>
<!doctype - html5>

    <title>Array</title>
        <link rel="stylesheet" type="text/css" href="css/style_home.css">
        <meta charset="utf-8">

        <form name="frmsorteio" method="post" action="router.php?controller=sorteio&modo=<?php echo($action)?>">
            <input class="botao1" type="submit" name="btn_prymari" value="<?php echo($botao)?>">

//ROUTER.PHP
<?php

    $controller=$_GET['controller'];
    $modo=$_GET['modo'];

    switch($controller)
    {
        case 'sorteio':

            require_once('controllers/sorteio_controller.php');
            require_once('models/sorteio_class.php');

            switch($modo)
            {
                case 'sorteio1':
                    $controller_sorteio = new ControllerSorteio();
                    $controller_sorteio->Sorteio1();
                    break;
            }
    }

?>

//PASTA CONTROLLERS
<?php
 class ControllerSorteio{

        public function Sorteio1(){

            if($_SERVER['REQUEST_METHOD']=='POST'){
              require_once('models/sorteio_class.php');
            }
        }
    }
?>

//PASTA MODEL
<?php
class CodeGen{
    private $codes = array();
    public function __construct($codes) {
        $this->codes = $codes;
}
    public function getRandomCode($min, $max){
       $next = 60;
            while (count($this->codes) < $next) {
                $code = mt_rand($min, $max);
                if (!in_array($code, $this->codes)) {
                    $this->codes[] = $code;
         }
    }
}
    public function getLastCode(){
        return ($this->codes);
    }
}
    $codes = array();
    $CodeGen = new CodeGen($codes);
    $CodeGen->getRandomCode(0, 60);
    print_r $CodeGen->getLastCode();
?>

Answer: Acredito, pelo menos por enquanto, que seu código não precisa de um model, apenas uma view e um controller, mas deixando no mesmo padrão que esta fazendo:
View:
<?php
    session_start(); //função necessária para usar a variável global $_SESSION, deve ser chamada antes de qualquer outro código php

    $botao="Sorteio";
    $action="sorteio1";
?>
<!doctype - html5>

    <title>Array</title>
        <link rel="stylesheet" type="text/css" href="css/style_home.css">
        <meta charset="utf-8">

        <form name="frmsorteio" method="post" action="router.php?controller=sorteio&modo=<?php echo($action)?>">
            <input class="botao1" type="submit" name="btn_prymari" value="<?php echo($botao)?>">
            <?php
                //Verifica se existe o array_sorteio e se ele não está vazio para criar a tabela
                if(isset($_SESSION["array_sorteio"]) && $_SESSION["array_sorteio"] != "") {
            ?>

                        <?php
                            $array = $_SESSION["array_sorteio"]; //Atribui a variável array o valor que está na sessão "array_sorteio"
                            unset($_SESSION["array_sorteio"]); //Destroi a posição "array_sorteio" da variável $_SESSION

                            for($i = 0; i < count($array); $i++) {
                                echo "".$array[i]."	";
                            }
                        ?>

            <?php
                }
            ?>

Router.php:
<?php
    session_start(); //função necessária para usar a variável global $_SESSION, deve ser chamada antes de qualquer outro código php

    $controller=$_GET['controller'];
    $modo=$_GET['modo'];

    switch($controller) {
        case 'sorteio':

            require_once('controllers/sorteio_controller.php');
            //require_once('models/sorteio_class.php'); - Retirar essa linha, o model vai ser inserido abaixo

            switch($modo) {
                case 'sorteio1':
                    $controller_sorteio = new ControllerSorteio();
                    //Aqui é inserido o model
                    if($controller_sorteio->Sorteio1()) {
                        //Se o model foi inserido..
                        $codes = array();
                        $CodeGen = new CodeGen($codes);
                        $CodeGen->getRandomCode(0, 60);
                        $array_sorteio = $CodeGen->getLastCode(); //Pega o array gerado no model e atribui a variável $array_sorteio

                        $_SESSION["array_sorteio"] = $array_sorteio; //Cria uma posição "array_sorteio" no array $_SESSION e atribui a ele o array gerado anteriormente
                        header("location: ./camiho/view.php"); //Envia o usuário para á pagina selecionada
                    }
                    break;
            }
    }

?>

Controller:
<?php
    class ControllerSorteio {
        public function Sorteio1() {
            if($_SERVER['REQUEST_METHOD']=='POST') {
                require_once('models/sorteio_class.php');

                //Cria um retorno para saber se o model foi (true) ou não (false) inserido
                return true;
            } else {
                return false;
            }
        }
    }
?>

Model:
<?php
    class CodeGen {
        private $codes = array();

        public function __construct($codes) {
            $this->codes = $codes;
        }

        public function getRandomCode($min, $max){
            $next = 60;
            while (count($this->codes) < $next) {
                $code = mt_rand($min, $max);
                if (!in_array($code, $this->codes)) {
                    $this->codes[] = $code;
                }
            }
        }

        public function getLastCode(){
            return ($this->codes);
        }
    }

    /* Esse bloco de código deve ser chamado dentro do router.php e não abaixo da classe do model
    $codes = array();
    $CodeGen = new CodeGen($codes);
    $CodeGen->getRandomCode(0, 60);
    print_r $CodeGen->getLastCode();
    */
?>

Não vou poder testar o código mas é mais ou menos isso (que eu faria) boa sorte, qualquer coisa é só perguntar
Comment: ok, já coloquei o codigo inteiro da models, só não entendi onde criarei a $_SESSION, na controllers?
Comment: ok, seu código está meio confuso e eu não vou poder montar uma resposta agora tenho que sair mas amanhã eu edito minha resposta e aviso. Quando fizer uma pergunta ou editar deixe seu código identado corretamente e com 4 espaços a mais no início de cada linha (para deixar no formato de bloco de código)
Comment: @Bruna editei a resposta com o modo que eu faria
Comment: Guilherme muito obrigada, o código ficou perfeito só precisei fazer alguma incrementações mas deu tudo certo, muito obrigada.
Comment: Se você sanou suas duvidas dessa pergunta, finalize com aceitando uma resposta
Answer: Poderia fazer da seguinte maneira
Antes da tag Html, dentro da php:
try{
    require('conexao.php'); // Chama seu arquivo de conexão
    $sql = "Sua SCRIPT"; // Cria Script
    $stmt = $conexao->prepare($sql); //Prepara sua script com sua conexão
    $stmt->execute(); //Executa
}
catch(PDOExeption $e){
    echo " ".$e;
}

Depois da tag html:

<title>Array</title>
    <link rel="stylesheet" type="text/css" href="css/style_home.css">
    <meta charset="utf-8">

<?php
  while($consulta = $stmt->fetch()){
?>
    <form name="frmsorteio" method="post" action="router.php?
 controller=sorteio&modo=<?php echo($action)?>">
        <input class="botao1" type="submit" name="btn_prymari" value="<?php
 echo($botao)?>">

            <?php echo $consulta["nomecoluna"];?>
            <?php echo $consulta["nomecoluna2"];?>
            <?php echo $consulta["nomecoluna3"];?>

Não esqueça de fechar no depois da tag tr
<?php
   }
?>

Comment: Do modo como está, se a cunsulta retornar mais de uma linha, vai criar varioa formularios e tabelas em vez de só adicionar a linha, além disso a idéia  (pelo que posso ver do código) é manter as partes do mesmo separadas (arquivos com model, outros com o controller e outros com as view)
Comment: esta dando erro somente na variavel  #sql, não sei o que colocar no script
Comment: muito obrigada Gabriel


Confusion in Base, Scales and Sargam

Question: I am learning and playing flute from Youtube on my own for over 10 months now but there are some questions and doubts that still confuse me. Now according to me no matter what the bass of flute is the Indian Sargam remains same on it. I mean SRGmPDNS' remains same whether it be A or Bb bass flute. According to me the bass of the flute gives us the base note of Sa. For example if I am playing on C scale Sa will sound C, Re will sound D and so on.
Now secondly I was learning a song on E bass flute on Youtube. Now the instructor said he had kept the scale of the song composition to A# on the same E scale flute and this is where I got confused.
Question 1: Have I got the first concept right? And if not what is the difference between different bass flutes in terms of Sargam? For instance what is the difference between C and D bass flute in terms of Indian Sargam?
Question 2: What does the instructor mean by that? I mean I know any instrument can be tuned to any scale keeping a base note but my doubt is are the sargam notes that he gave keeping A# scale on E bass flute universal and can be played on any bass flute? Or do they account for only A# scale and I will have to change them according to A# scale while playing on any other bass flute?
Comment: Ans 1: Yes the concept is right. Basically when you have a 'x' bass flute then according to Indian notation your 'Sa' (three holes covered on flute) or according to Western notation your 'Do' will sound exactly the equivalent of that 'x' western note.
For example if you are playing on C bass flute your Sa/Do will sound C, Re/Re will sound D and so on.
References:
http://www.notesandsargam.com/indian-sargam-vs-western-notes/
http://www.bansuriflute.co.uk/p/beginners-how-to-play-bansuri.html
Answer:
As stated in the comment, the first concept is absolutely correct that basically when you have a 'x' bass flute then according to Indian notation your 'Sa' (three holes covered on flute) or according to Western notation your 'Do' will sound exactly the equivalent of that 'x' western note. For example if you are playing on C bass flute your Sa/Do will sound C, Re/Re will sound D and so on.

Now coming to second answer we can play notes with reference to any scale on any bass scale flute. If you have a 'x' scale flute then your normal SRGmPDNS' (western equivalent - Do Re Mi Fa So La Ti Do') on flute will be played in natural scale of your flute i.e. in C scale. But if you want to play a song, in 'y' scale then your SRGmPDNS' (western equivalent - Do Re Mi Fa So La Ti Do') will shift on your flute according to the scale difference between natural scale ('x') and your desired scale ('y'). For an example let us say that you have a D scale flute then your normal SRGmPDNS' (western equivalent - Do Re Mi Fa So La Ti Do') will be played in D scale but if you want to play in C scale then you will have to shift your every note 2 scales higher as there is a difference of two scales between C and D (C, C#, D) i.e. your Sa (Do) will become Re (Re) and Re (Re) will become Ga (Mi) and so on.

References:

notesandsargam.com/indian-sargam-vs-western-notes

bansuriflute.co.uk/p/beginners-how-to-play-bansuri.html

Confusion in Base, Scales and Sargam


help to optimize container

Question: I have an openvz node with only one container (Cpanel server).  Yesterday I had many memories issues:

Unable to fork: Cannot allocate memory

Can someone help me to optimize my node setting ? I have a 4Gb node and I can use all node resources for the container.
This is my resources output:
cat /proc/user_beancounters
Version: 2.5
       uid  resource                     held              maxheld              barrier                limit              failcnt
      100:  kmemsize                 20674962             43480374            419090432            460999475                    0
            lockedpages                     0                    7                20463                20463                    0
            privvmpages                230416              1045032               900000              1000000               363565
            shmpages                    11328                17450                30695                30695                    0
            dummy                           0                    0                    0                    0                    0
            numproc                       106                  161                10230                10230                    0
            physpages                  129958               885303                    0  9223372036854775807                    0
            vmguarpages                     0                    0               491520  9223372036854775807                    0
            oomguarpages               153680               906996               917504  9223372036854775807                    0
            numtcpsock                     56                  191                10230                10230                    0
            numflock                        7                   21                 1000                 1100                    0
            numpty                          1                    1                  512                  512                    0
            numsiginfo                      0                   31                 1024                 1024                    0
            tcpsndbuf                 1171104              4738832             97794730            139696810                    0
            tcprcvbuf                  917504              4212568             97794730            139696810                    0
            othersockbuf               139120              1841832             48897365             90799445                    0
            dgramrcvbuf                     0               147352             48897365             48897365                    0
            numothersock                   72                  110                10230                10230                    0
            dcachesize                      0                    0             91533669             94279680                    0
            numfile                      7101                 7630               163680               163680                    0
            dummy                           0                    0                    0                    0                    0
            dummy                           0                    0                    0                    0                    0
            dummy                           0                    0                    0                    0                    0
            numiptent                     421                  421                  400                  500                    0

It appears "privvmpages" parameter failed:
This is my node settting:
VERSION="2"

ONBOOT="yes"

NUMPROC="10230:10230"
AVNUMPROC="5115:5115"
NUMTCPSOCK="10230:10230"
NUMOTHERSOCK="10230:10230"
VMGUARPAGES="491520:9223372036854775807"

# Secondary parameters
KMEMSIZE="419090432:460999475"
TCPSNDBUF="97794730:139696810"
TCPRCVBUF="97794730:139696810"
OTHERSOCKBUF="48897365:90799445"
DGRAMRCVBUF="48897365:48897365"
OOMGUARPAGES="917504:9223372036854775807"
PRIVVMPAGES="900000:1000000"

# Auxiliary parameters
LOCKEDPAGES="20463:20463"
SHMPAGES="30695:30695"
PHYSPAGES="0:9223372036854775807"
NUMFILE="163680:163680"
NUMFLOCK="1000:1100"
NUMPTY="512:512"
NUMSIGINFO="1024:1024"
DCACHESIZE="91533669:94279680"
NUMIPTENT="400:500"
DISKSPACE="203811210:224192332"
DISKINODES="5000000:6000000"
CPUUNITS="139987"
VE_ROOT="/vz/root/$VEID"
VE_PRIVATE="/vz/private/$VEID"
ORIGIN_SAMPLE="1vs"

DISK_QUOTA="yes"
OSTEMPLATE="centos-5-x86_64"
IP_ADDRESS="xxx.xxx.xxx.xxx"
NAMESERVER="22.214.171.124 22.214.171.124"
HOSTNAME="xxx.xxxxxx.xxx"
QUOTAUGIDLIMIT="800"
DISKSPACE="204857600:215302400"
QUOTATIME="1200"

Comment: What kernel version do you have? You may be able to run the new vswap style config - currenly only available on RHEL kernels. I haven't got a chance to try it out but it looks like it makes things way simpler.
Answer: Multiply by 2 both fields in PRIVVMPAGES.
That is, replace
PRIVVMPAGES="900000:1000000"

with
PRIVVMPAGES="1800000:2000000"

or (no tested, but should work) with:
PRIVVMPAGES="6.8G:7.6G"

and restart the container.

help to optimize container


How to control image size in menu?

Question: I have menu with images. I have big images 72x72.
In activity layout I'm using:
android:layout_height="55dip"
android:layout_width="55dip"
android:scaleType="fitCenter" - this works fine.

But in menu items I don't know how to do the same.
Answer: @Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu,menu);
 menu.findItem(R.id.menu_Help).setIcon(resizeImage(R.drawable.ic_noaction_help,108,108));
    return true;
}

private Drawable resizeImage(int resId, int w, int h)
{
      // load the origial Bitmap
      Bitmap BitmapOrg = BitmapFactory.decodeResource(getResources(), resId);
      int width = BitmapOrg.getWidth();
      int height = BitmapOrg.getHeight();
      int newWidth = w;
      int newHeight = h;
      // calculate the scale
      float scaleWidth = ((float) newWidth) / width;
      float scaleHeight = ((float) newHeight) / height;
      // create a matrix for the manipulation
      Matrix matrix = new Matrix();
      matrix.postScale(scaleWidth, scaleHeight);
      Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0,width, height, matrix, true);
      return new BitmapDrawable(resizedBitmap);
}

Answer: An improvement to Kostadin's answer above is to save memory by avoiding the creation of the first bitmap he calls BitmapOrg, by using the approach described http://developer.android.com/training/displaying-bitmaps/load-bitmap.html.
Answer: Inside onCreateOptionsMenu:
getMenuInflater().inflate(R.menu.my_menu, menu);
menu.findItem(R.id.action_overflow).setIcon(resizeImage(R.mipmap.more,72,72));

How to control image size in menu?


How do I get an item in a list that matches a certain condition?

Question: I have the following sample code :
package models

import java.util.concurrent.atomic.AtomicInteger
import scala.collection.mutable.ArrayBuffer

case class Task(id: Int, label: String)

object Task {

  private val buffer = new ArrayBuffer[Task]
  private val incrementer = new AtomicInteger()

  def all(): List[Task] = buffer.toList

  def create(label: String): Int = {
    val newId = incrementer.incrementAndGet()
    buffer += new Task(newId, label)
    newId
  }

  def delete(id: Int): Boolean = {

    // TODO : add code

  }
}

In method delete I need to find a Task that has id equal to the parameter id and if one is found I need to remove it from the collection and return true from the method. Otherwise (if none is found) I should just return false.
I know how to do this in an imperative language such as C# or Java but Scala stumps me..
PS : The code is strictly used to understand the language and the platform, it sucks too much to be pushed in production. Don't worry.
Answer: This is one possible solution, however in this case I think it's also possible to switch to var + immutable ArrayBuffer and use filter. Also note that this code is not thread safe
  import java.util.concurrent.atomic.AtomicInteger
  import scala.collection.mutable.ArrayBuffer

  case class Task(id: Int, label: String)

  object Task {

    private val buffer = new ArrayBuffer[Task]
    private val incrementer = new AtomicInteger()

    def all(): List[Task] = buffer.toList

    def create(label: String): Int = {
      val newId = incrementer.incrementAndGet()
      buffer.append(Task(newId, label))
      newId
    }

    def delete(id: Int): Boolean = {
      buffer.
        find(_.id == id). // find task by id
        map(buffer -= _). // remove it from buffer
        exists(_ => true) // the same as: map(_ => true).getOrElse(false)
    }
  }

  val id1 = Task.create("aaa")
  val id2 = Task.create("bbb")

  println(s"Id1 = $id1 Id2 = $id2")
  println(s"All = ${Task.all()}")

  val deleted = Task.delete(id1)
  println(s"Deleted = $deleted")
  println(s"All = ${Task.all()}")

  println(s"Not Deleted = ${Task.delete(123)}")

Comment: looks really good! (as in functional-oriented if I can say so)
Comment: I eventually found out `find` but I didn't know about `map` and that it can be used like so :)
Comment: One question if I may : does the expression `buffer -= _`, which is the argument of `map`, return the removed item?
Comment: No, it returns buffer itself. But you can update this expression to return removed item: map(found => {buffer -= found; found}).


Approximating SVM using Perceptron

Question: Suppose that we have a set of linearly separable data and this pseudocode of Perceptron:
Input: (xi, yi), i=1,...,n, w = 0, k = 0
Repeat:
  k = (k + 1) mod n
  if(sign(yi) != sign(traspose(w)*xi) then
      w = w + yi*xi
  end if
until(every point is not misclasified)

Is there a way to modify this code to get a separator hyperplane as optimal as possible? In other words, is there a way to modify this code to obtain a new algorithm that learns an hyperplane as similar as possible to the hyperplane that SVM algorithm obtains? Maybe iterating first on the most misclassified data, or changing the if condition to be more restrictive?
Comment: (Although this question asks about modifying code, it is about *pseudocode*, i.e., an algorithm. This is software-neutral, & should be considered on topic here. I'm voting to leave open.)
Answer: If you want to get a similar solution to SVM (max margin) then you will similarly need some sort of regularizer term for what you're solving - e.g. $\frac{\lambda}{2}||w||^2_2$. If you wish to consider $\lambda = 0$ you could do that as well, although convergence would be smaller, and I'm less sure about whether it will indeed be max margin.
In any case, to keep your format similar to what you have, you could solve using various stochastic schemes (e.g. SGD would apply for $\lambda = 0$ or not, and if you do have $\lambda > 0$, you could also consider Pegasos). Those aren't the latest results, but their algorithms are simple; in both cases, you'd only update $w$ when you encounter loss (not misclassification but loss according to e.g. the hinge loss), and the step-sizes are not constant. If you want constant step sizes, consider  SAGA, although I do believe that requires your loss function to be Lipschitz smooth with constant $L$ which it isn't for the hinge loss (but you could use the Huber loss as a good substitute)

Approximating SVM using Perceptron


what is meant by stochastic drift?

Question: could anybody define what is meant by stochastic drift?
I think I have a rough idea, say on a random walk X(n)= a + X(n-1) + Z(n) where Z(n) are iid zero mean and constant variance, then E[X(n)] = na. Is this stochastic drift?
Many thanks
Comment: The term $Z(n)$ is your stochastic drift term. As it is stated, you have a deterministic drift term also $a$.
Answer: Wikipedia gives a definition:

stochastic drift is the change of the average value of a stochastic (random) process.

If you look further down that page, it's clear that the final term in your model is the source of stochastic drift.

what is meant by stochastic drift?


Given $f(x,y) = 8xy$, for $0 1)$

Question: Could anyone help me with this probability question?
Question Picture
Its not homework, its more of a question from a past year paper that I'm doing for self revision.
What I did was:
$P(X+Y > 1) = P(Y > 1 - X)$
1) Draw the graph for $y$ and $x$.
Graph
So have to evaluate the area in the graph,
$$
\int_{0}^{1}\int_{1-x}^{1} 8xy\,dydx
$$
Integrating this. i... dont know how to integrate this. However, the answer is 5/6...
I think it has to do with the range, but im not sure how to proceed. Can anyone assist? :D
Thanks guys!
EDIT: Realized i shaded wrongly, new uploaded.
Comment: Realized I shaded it wrongly, Thank you! :)
Answer: First, observe that the problem provides the condition $y>x$.  More precisely, if you ignore this condition and and just think of the domain as the unit square, you get that the probability is
$$
\int_0^1\int_0^18xydydx=2,
$$
which should be $1$.
On the other hand, if you use the condition that $y>x$, you have the integral over the region is
$$
\int_0^1\int_x^18xydydx=1,
$$
as desired.
Therefore, for your problem, you need the probability that $X+Y>1$, but recall the condition that $Y>X$.  Therefore, we need both $Y>X$ and $Y>1-X$.  When $X<\frac{1}{2}$, the second condition is more restrictive and when $X>\frac{1}{2}$, the first condition is the restrictive one.  Therefore your probability should be divided at $x=\frac{1}{2}$:
$$
\int_0^{\frac{1}{2}}\int_{1-x}^18xydydx+\int_{\frac{1}{2}}^1\int_x^18xydydx=\frac{13}{48}+\frac{9}{16}=\frac{5}{6}.
$$
Comment: I see now! Thank you so much for your help! :) I find it difficult to see the ranges i should integrate given the restrictions of the conditions, is there any way I can more easily see it? I normally look at the graph and try to discern the ranges.
Comment: Not really, graphing is a good way to figure out what's going on.  One algebraic way to figure this out is to write all the inequalities that pertain, in this case $Y>X$ and $Y>1-X$ and solve $X=1-X$ to find the intersection points to determine which inequality is more restrictive at each case.

Given $f(x,y) = 8xy$, for $0 1)$


Adding vector tiles to mapbox.js

Question: Mapbox JS has an extensive library of examples here, but what is missing is documentation on how to load vector tiles from Mapbox Studio.
In the upgraded Mapbox GL JS, this is clearly explained in the documentation.
map.addLayer({
    "id": "terrain-data",
    "type": "line",
    "source": {
        type: 'vector',
        url: 'mapbox://mapbox.mapbox-terrain-v2'
    },
    "source-layer": "contour",
    "layout": {
        "line-join": "round",
        "line-cap": "round"
    },
    "paint": {
        "line-color": "#ff69b4",
        "line-width": 1
    }
});

Where the url contains the mapid and the source-layer is the name of the layer.  So if mapid = abcd1234, my username is testUser, and my vector layer name is testLayer I would write:
"source": {
    type: 'vector',
    url: 'mapbox://testUser.abcd1234'
},
"source-layer": "testLayer",

This works perfectly in Mapbox GL JS, but what would the equivalent example be for loading mapbox vector tiles from Mapbox Studio in Mapbox JS?
Answer: Assuming Mapbox JS is based on Leaflet 1+, then you can use http://leaflet.github.io/Leaflet.VectorGrid/vectorgrid-api-docs.html. Actually I find this plugin + Leaflet/Mapbox JS has certain advantages over gl js.

Adding vector tiles to mapbox.js


Downloading from server doesn't work

Question: I am trying to make a website in Java and trying to add upload system.
I am using the following tag:
 Download It

but the thing is, if the file is text file it doesn't start downloading. Instead it just opens the text. Also when I start the server on eclipse it works fine but when I type the same link in chrome, It says: Failed - Network error.
Any suggestions?
Comment: You should read that page, it could be a lead [Chrome Download Attribute not working](https://stackoverflow.com/questions/23872902/chrome-download-attribute-not-working)
Answer: It seems the best way to do that (if the download attribute does not work), is to properly set the header Content-type to application/octet-stream on your resource URI, but this needs a server-side change of course.
Potentially, you also have to set Content-Length and Content-Disposition.
That's weird that download does not work in Chrome though: did you try to capture the HTTP exchange?
Comment: A question in an answer usually means it is not an answer but a comment ;)
Comment: The very strange thing is that when I generate the source of page and put the whole text in html, it work just fine even on chrome. But when I do exact same thing from  server it gives network error.
Comment: @GeorgeDopeG have you checked that the link is correct in the generated page (on the client side) that it is not using a cached version or something else
Comment: @AxelH I would be glad to comment but my account does not let me do that :(
Comment: @AxelH yes. Also it work fine in eclipse browser. And it also works fine when I put the generated html source in just html file. It only give error when I try running it from server on chrome.
Comment: @sjahan just saying, but using an answer for the wrong reason could lead to downvotes, then it would take you even longer to get the reputation to be able to comment. Just be patient instead of using the wrong tool.
Comment: @GeorgeDopeG you means by copying the source from the JSP page received on the client side (so generated by the server), into an HTML page, it works ? Since the browser don't really see a the difference there, maybe in headers, I don't see how it could be possible.
Comment: Anyway, I don't know on which technology is based the Eclipse server, but you should try something more production ready. If Chrome tells you there is a network error, it is certainly that the HTTP protocol is not respected! That's why sniffing the HTTP request/response should be interesting.

Downloading from server doesn't work


Generalization of the sum of angles formula for any number of angles

Question: In another question one user helped me prove that the sum of three angles was a multiple of 360 degrees with formulas for sine and cosine sums of three angles. The sine formula was:
$\sin(α+β+γ)=\sin α\cos\beta\cos γ+\cos α\sin β\cos γ+\cos α\cos β\sin γ-\sin α\sin β\sin γ$
I infer that the pattern for five angles is as shown below? For brevity, I'm using a shorthand, e.g. $\sin(α+β+γ):s(a_1+a_2+a_3 )$ and $\sin α\cos \beta\cos γ∶s_1 c_2 c_3$. So, is the following the proper pattern for summing five angles?
$$s(a_1+a_2+a_3+a_4+a_5)=s_1 c_2 c_3 c_4 c_5+c_1 s_2 c_3 c_4 c_5+c_1 c_2 s_3 c_4 c_5+c_1 c_2 c_3 s_4 c_5+c_1 c_2 c_3 c_4 s_5-s_1 s_2 s_3 s_4 s_5$$
If so, I can also infer the pattern for cosine and use the patterns for any number of angles.
Comment: I am looking for the correct form of a 5-angle sum using the format in my attempt above. I hope to use it to find certain combinations among thousands or millions of sets of angles generated programmatically.
Answer: In my opinion this formula is the best one:
\begin{equation}
\sin\left[\sum_{j=1}^N a_j\right] = \sum_{\sigma_{1,\dots,N-1}=\pm} \left[\prod_{j=1}^{N} \sin\left[a_j + \left(2 + \sigma_j-\sigma_{j-1} -\delta_{j1}(1-\sigma_{j-1}) - \delta_{jN}(1+\sigma_{j})\right)\frac{\pi}4\right]\right]
\end{equation}
The $\delta$'s are Kronecker deltas.
I hope it will be of use to someone; I used it to write the sine as a product of eigenvalues = a matrix. (This last fact is not relevant to the question, but a useful consequence of the above decomposition, i.e. any symbolic product can be written as a matrix with the individual factors of the product along the diagonal. The above produces a signed sum of these matrices, which gave the decomposition as given above some other application.)
EDIT:
Applied to the case N=5, the formula predicts
\begin{align}
\sin\left[\sum_1^5 a_j\right] = \sum_{\sigma_1,\sigma_2,\sigma_3,\sigma_4=\pm} \sin\left[a_1+(1+\sigma_1)\frac\pi4\right]\sin\left[a_2+(2+\sigma_2-\sigma_1)\frac\pi4\right]\sin\left[a_3+(2+\sigma_3-\sigma_2)\frac\pi4\right]\sin\left[a_4+(2+\sigma_4-\sigma_3)\frac\pi4\right]\sin\left[a_5+(1-\sigma_4)\frac\pi4\right]
\end{align}
which can be verified by using the Mathematica code
<code>pmlist = {-1, 1};
n = 5;
sigma\[LetterSpace]list\[LetterSpace]symb =
  Reap[Do[Sow[
       ToExpression["\[Sigma]\[LetterSpace]" <> ToString[l]]], {l,
       Range[n]}]][[2]][[1]];
sigma\[LetterSpace]list\[LetterSpace]symb\[LetterSpace]appended = \
{sigma\[LetterSpace]list\[LetterSpace]symb[[#]], pmlist} & /@
  Range[n - 1]
Sin[Sum[Subscript[a, i], {i, 1, n}]] -
  Fold[Sum[#1, #2] &,
   Product[Sin[
     Subscript[a,
       j] + (\[Pi]/4)*(2 +
         ToExpression["\[Sigma]\[LetterSpace]" <> ToString[j]] -
         ToExpression["\[Sigma]\[LetterSpace]" <> ToString[j - 1]] -
         KroneckerDelta[j,
           1]*(1 -
            ToExpression[
             "\[Sigma]\[LetterSpace]" <> ToString[j - 1]]) -
         KroneckerDelta[j,
           n] (1 +
            ToExpression[
             "\[Sigma]\[LetterSpace]" <> ToString[j]]))], {j, 1, n}],
   sigma\[LetterSpace]list\[LetterSpace]symb\[LetterSpace]appended] // \
TrigExpand
</code>
Comment: I have no idea what you are talking about, especially after looking up Kronecker deltas and  Eigenvalues. What I asked for is a formula for the sum of $5$ dissimilar acute angles.
Comment: @poetasis I have added your application to the answer plus some code for symbolic verification. Best wishes
Comment: Hello,
are the sigmas +-1 or how does this work? :)
Comment: Hi @easymathematics, yes sigma is basically just a sign. The summation over sigmas then implies that you have two terms, one in which the sigma is + and the other in with it is -. The single summation sign over multiple sigma_1 sigma_2 etc. is actually an abuse of notation. Read the above example for $n=5$ as four separate summations.
Answer: The correct formulas can be derived from the following knowledge.
$$e^{i\alpha}=\cos\alpha + i\sin\alpha.$$
Hence
$$\sin(a_1+a_2+a_3+a_4+a_5)=\renewcommand{\Im}{\operatorname{Im}}\Im e^{i(a_1+a_2+a_3+a_4+a_5)} = \Im e^{ia_1}e^{ia_2}e^{ia_3}e^{ia_4}e^{ia_5}$$
$$=\Im (c_1+is_1)(c_2+is_2)(c_3+is_3)(c_4+is_4)(c_5+is_5)$$
$$= \sum_{j=1}^5s_j\prod_{k\ne j} c_k
- \sum_{\substack{\{j_1,j_2,j_3\}\subseteq[5]\\\{j_4,j_5\}=\{j_1,j_2,j_3\}^C}} s_{j_1}s_{j_2}s_{j_3} c_{j_4}c_{j_5} + s_1s_2s_3s_4s_5.$$
Note that the middle summation is the only piece missing from your formula above, and that the product of all sins has opposite sign from your formula. The reason we get this formula is that the only pieces of the product that contribute to the imaginary part are the pieces which have an odd number of sins in them. Thus we have three parts in our formula, since we can take 1 sin, 3 sins or 5 sins to get an imaginary piece.
In general, this leads one to derive the formula (correct me if my indices are messed up)
$$\sin\left(\sum_{i=1}^n a_i\right)
=\sum_{k=0}^{\lfloor(n-1)/2\rfloor}\sum_{\substack{A\subseteq [n]\\|A|=2k+1}}(-1)^k\prod_{i\in A} s_i\prod_{j\in A^C}c_j.$$
Comment: I'm guessing your answer is probably correct but it is in terms that I don't remember how to use – it's been 4 decades since I got my degree and I've been out of academics since then. I'm more interested a simple yes or no about the pattern I inferred for the sum of 5 angles. Thanks.
Comment: @poetasis Briefly, no. If I try to express the correct pattern in words it is: First take all possible products with one sine and the rest cosine, subtract all possible products with three sines and the rest cosines, add all possible products with 5 sines and the rest cosines, subtract again for 7 sines, add again for 9 sines, and so on until you run out of angles. (As in for 5 angles, you naturally can't take 7 sines.)
Comment: @poetasis if you could explain what dissatisfied you about my comment, I might be able to help you. My comment made no mention of e or imaginary parts, and I've never mentioned limits in my answer or comments. Moreover I answered your question both in my answer and the comments telling you that your formula was incorrect. What's more I have described the correct formula in both words and symbols, but I don't have the time to spend typing out all the pieces of the sum explicitly.
Comment: @poetasis ... Though I see you're responding to someone else whose comment is no longer present. That being said, I'd hoped my comment would be helpful.
Comment: I misread the 'Im' in your answer to be 'lim' but your answer did speak of 'e' and imaginary parts. Further, your attempt to explain in words left me skeptical because you indicated a need for 7 and 9 sines. I don't want to take up any more of your time and MSE discourages extended discussions so let us end this now, accepting that some communications are just not effective.
Comment: @poetasis That's reasonable, I'll just try to clarify my comment slightly. There is no need for 7 or 9 sines in the case of 5 angles, since there are none. Rather you stop at 5. I was giving the general pattern that generalizes to any number of angles.
Comment: In case everyone else is wondering what those funny symbols mean: $\{j_1,j_2,j_3\}\subseteq[5]$  means a subset of three variables from a set of 5 integers (1 to 5). $\{j_4,j_5\}=\{j_1,j_2,j_3\}^C$  means two variable subset complementary to the three chosen before. $\lfloor(n-1)/2\rfloor$  means round down the value of $(n-1)/2$, $|A|=2k+1$ is the number of elements inside $A$ chosen from $[n]$. For cosine formula, just swap $s_i$ with $c_i$ and $c_j$ with $s_j$ (maybe, I think).
Answer: $s(a_1+a_2+a_3) = s_1c_2c_3+c_1s_2c_3+c_1c_2s_3-s_1s_2s_3 $
$c(a_1+a_2+a_3) =$  $$s(\frac \pi 2 -(a_1+a_2+a_3))
\\ =s((\frac \pi 2 -a_1)+(-a_2)+(-a_3))
\\= c_1c_2c_3 -s_1s_2c_3- s_1c_2s_3-c_1s_2s_3$$
And we also know ...
$s(a_4+a_5) = s_4c_5+ c_4s_5$
$c(a_4+a_5) = c_4c_5- s_4s_5$
So
$$s(a_1+a_2+a_3+a_4+a_5) \\
=( s_1c_2c_3+c_1s_2c_3+c_1c_2s_3-s_1s_2s_3) ( c_4c_5- s_4s_5)
\\+ (  c_1c_2c_3 -s_1s_2c_3- s_1c_2s_3-c_1s_2s_3)(s_4c_5+ c_4s_5 )
$$
There will be no cancellations so you will get 16 terms ( they will be the half of the $2^5=32$  possible arrangements of sines and cosines having an odd number of sines )
The coefficient in front of each term having $(2k+1)$ sines will be $(-1)^k$
So for 5 angles you would expect...
$\binom 51=5$ terms  having 1 sine , coefficient = +1
$\binom 53=10$ terms  having 3 sines  , coefficient = -1
$\binom 55=1$ term  having 5 sines , coefficient = +1
Answer: Alternatively, assuming that all angles $\,\alpha_j \in \left(0, 180^\circ\right)\,$ and none of them is a right angle, one can use that $\,\sum \alpha_j = k \cdot 360^\circ$ $\iff \sum \dfrac{\alpha_j}{2} = k \cdot 180^\circ$ $\iff \tan\left(\sum \dfrac{\alpha_j}{2}\right) = 0\,$.
For five angles $\,\alpha_j \mid j=1,2,3,4,5\,$, let $\,t_1 = \tan \dfrac{\alpha_1}{2}, t_2 = \tan \dfrac{\alpha_2}{2},\; \ldots \,, t_5 = \tan \dfrac{\alpha_1}{2}\,$, then using the $\tan$ of sum of angles formula:
$$
\tan\left(\frac{\alpha_1}{2}+\frac{\alpha_2}{2}+\ldots+\frac{\alpha_5}{2}\right)
 = \frac{e_1-e_3+e_5}{e_o-e_2+e_4} \quad\quad \style{font-family:inherit}{\text{where:}} \\[20px]
\begin{align}
\begin{cases}
e_0 &= 1 \\
e_1 = \sum_{1 \le i \le 5} t_i &= t_1+t_2+t_3+t_4+t_5 \\
e_2 = \sum_{1 \le i \lt j \le 5} t_i &= t_1t_2+t_1t_3+t_1t_4+t_1t_5 \\ &\quad+t_2t_3+t_2t_4+t_2t_5 \\
&\quad+t_3t_4+t_3t_4 + \\
&\quad +t_4t_5 \\
e_3 = \sum_{1 \le i \lt j \lt k \le 5} t_it_jt_k &= t_1t_2t_3+t_1t_2t_4+t_1t_2t_5+t_1t_3t_4+t_1t_3t_5+t_1t_4t_5 \\
&\quad + t_2t_3t_4 + t_2t_3t_5+t_2t_4t_5 \\
&\quad + t_3t_4t_5 \\
e_4 = \sum_{1 \le i \lt j \lt k \lt l \le 5} t_it_jt_kt_l&= t_1t_2t_3t_4+t_1t_2t_3t_5+t_1t_2t_4t_5+t_1t_3t_4t_5+t_2t_3t_4t_5 \\
e_5 = \prod_{1 \le i \le 5} t_i &= t_1t_2t_3t_4t_5 \\
\end{cases}
\end{align}
$$
Comment: I appreciate your efforts here and in my prior question about proving that perimeter angle add up to $\pi$ but what I am looking for is a solution like 'Blue' provided in answer to 'that' question. I have extrapolated from his equation and, regrettably, used a shorthand that apparently doesn't make it clear what I want. I do want a solution in terms of sines and cosines that I can implement in Excel or programmatically. Can you offer a critique of my 'shorthand' extrapolation of Blue's solution? https://math.stackexchange.com/questions/2812907/how-to-prove-the-sum-of-angles-is-pi-radians
Comment: @poetasis There was an answer posted already in terms of $\,\sin\,$ and $\,\cos\,$, so the above proposed an alternative in terms of $\,\tan\,$. As far as computations go, $\,\tan \frac{A}{2} = \sqrt{\frac{(s-b)(s-c)}{s(s-a)}}\,$ in a triangle, which is as easy to calculate as $\,\sin\,$ and $\,\cos\,$. `Can you offer a critique of my 'shorthand' extrapolation of Blue's solution?` The correct formula is the one posted in jgon's answer, or [here](https://en.wikipedia.org/wiki/List_of_trigonometric_identities#Sines_and_cosines_of_sums_of_infinitely_many_angles).


Proving that the sum $\sum_{x \in \mathbb{F}_2^n} (-1)^{w^Tx}$ is either $2^n$ or zero

Question: Please help me prove that $$\sum_{x \in \mathbb{F}_2^n} (-1)^{w^T \cdot x} = 2^n \delta(w)$$ for any vector $w \in \mathbb{F}_{2}^n$ where $\delta(w) = 1$ for $w = 0$ and $\delta(w) = 0$ otherwise.
Comment: There is no $w$ on the LHS.  Is this the name of something standard?
Comment: I cannot transform all the formula correctly; so you see what is W from the link in the post. Thanks
Comment: W means weight..
Comment: muzzlator, thanks for the edit..
Comment: No problems.  Welcome to Math.SE, hope you see how to apply my solution.  If not, consider it an exercise to show that for any set of size $n$, there is a bijection between the subsets of odd size and the subsets of even size.
Comment: Thanks. Can you please give more details. I mean, can you show using the notation?
Answer: For $w = 0$, it's clear that the sum just counts elements of the vector space and so you have $2^n$
If $w \neq 0$, take the support of $w$ and show that there are exactly the same number of subsets with odd size and with even size.  Use these to cancel everything else out.
Comment: +1 A standard alternative argument with this type of sums is the following. If $\neq0$ there exists a $y\in V$ such that $y$ and $w$ have a single common one, i.e. $(-1)^{w^T\cdot y}=-1.$ Fix such a $y$. Then $x$ ranges over the vector space as $x+y$ so ranges, so the asked sum $S$ satisfies
$$S=\sum_{x\in V}(-1)^{w\cdot x}=\sum_{x+y\in V}(-1)^{w\cdot(x+y)}=\sum_{x\in V}(-1)^{w\cdot(x+y)}=(-1)^{w\cdot y}S=-S,$$ hence $S=0$.
Comment: Wow, that's nice.  Thanks @JyrkiLahtonen
Answer: Imagine how
$$\begin{align*}\sum_{x\in\Bbb F_2^n} (-1)^{w^T \cdot x}
&=\sum_{x_1\in\Bbb F_2}\sum_{x_1\in\Bbb F_2}\cdots\sum_{x_n\in\Bbb F_2}(-1)^{w_1x_1+\cdots+w_nx_n}\\
&=\left(\sum_{x_1\in\Bbb F_2}(-1)^{w_1x_1}\right)\cdots\left(\sum_{x_n\in\Bbb F_2}(-1)^{w_nx_n}\right)
\end{align*}$$
which is $2^n$ if all $w_k=0$ and $0$ if at least one $w_k\neq0$.


RecyclerView only show the first array index

Question: I want to display all contact that i get from api and show it using recyclerview. But when i want to run the code it show only one contact, actually it has 2 contacts on array.
Recyclerview adapter
    package com.example.ilham.dompettebal;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import java.util.List;

public class contactRecyclerAdapter extends RecyclerView.Adapter<contactRecyclerAdapter.ViewHolder> {

    private List<String> mData;
    private LayoutInflater mInflater;
    private ItemClickListener mClickListener;

    contactRecyclerAdapter(Context context,List<String> data)
    {
        this.mInflater = LayoutInflater.from(context);
        this.mData = data;
    }
    @Override
    public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = mInflater.inflate(R.layout.contact_recyclerview, parent, false);
        return new ViewHolder(view);
    }
    @Override
    public void onBindViewHolder(ViewHolder holder, int position) {
        String teman = mData.get(position);
        holder.myTextView.setText(teman);
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        TextView myTextView;

        ViewHolder(View itemView) {
            super(itemView);
            myTextView = itemView.findViewById(R.id.usernameTeman);
            itemView.setOnClickListener(this);
        }

        @Override
        public void onClick(View view) {
            if (mClickListener != null) mClickListener.onItemClick(view, getAdapterPosition());
        }
    }

    String getItem(int id) {
        return mData.get(id);
    }

    // allows clicks events to be caught
    void setClickListener(ItemClickListener itemClickListener) {
        this.mClickListener = itemClickListener;
    }

    // parent activity will implement this method to respond to click events
    public interface ItemClickListener {
        void onItemClick(View view, int position);
    }

}

mainactivity that include get data from server and recyclerview
package com.example.ilham.dompettebal;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.androidnetworking.AndroidNetworking;
import com.androidnetworking.common.Priority;
import com.androidnetworking.error.ANError;
import com.androidnetworking.interfaces.JSONObjectRequestListener;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity implements contactRecyclerAdapter.ItemClickListener {
    contactRecyclerAdapter adapter;
    private static final String TAG = "MainActivity";
    private TextView username;
    public String tokenUser;
    public JSONObject namaTeman;
    public JSONArray friends;
    private TextView usernameFriends;
    ArrayList<String> usernameFriendsProfile = new ArrayList<String>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tokenUser= getIntent().getStringExtra("token");
        Log.d(TAG, "tokenmainactivity" + tokenUser); //untuk log pada onerror
        Log.d(TAG, "tokenhalamanselanjutnya " + tokenUser);
        username = (TextView) findViewById (R.id.user);
        usernameFriends = (TextView)findViewById(R.id.usernameTeman);
    initData();

    }

    @Override
    public void onItemClick(View view, int position) {
        Toast.makeText(this, "You clicked " + adapter.getItem(position) + " on row number " + position, Toast.LENGTH_SHORT).show();
    }

    public void initData() {
        //get user
        AndroidNetworking.get("http://10.0.2.2:3000/users")
                .addHeaders("Authorization","Bearer "+tokenUser)
                .setPriority(Priority.MEDIUM)
                .build()
                .getAsJSONObject(new JSONObjectRequestListener() {
                    @Override
                    public void onResponse(JSONObject response) {
                        Log.d(TAG, "onResponse: " + response); //untuk log pada onresponse
                        try {

                            JSONObject obj = new JSONObject(String.valueOf(response));
                            String usernameAkun = obj.getString("username");
                            username.setText(usernameAkun);
                            Log.d(TAG, "namaprofil : " + username);
                            JSONArray friends = obj.getJSONArray("friends");

                            for (int i=0;i<friends.length();i++)
                            {
                                JSONObject objek = friends.getJSONObject(i);
                                usernameFriendsProfile.add(objek.getString("username"));
                            }
                            Log.d(TAG, "usernametemendidalem : " + usernameFriendsProfile);
//                            ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(MainActivity.this,R.layout.contact_recyclerview,R.id.usernameTeman,usernameFriendsProfile);
//                            teman.setAdapter(arrayAdapter);
                            RecyclerView recyclerView = findViewById(R.id.teman);
                            recyclerView.setLayoutManager(new LinearLayoutManager(MainActivity.this));
                            adapter = new contactRecyclerAdapter(MainActivity.this, usernameFriendsProfile);
                            adapter.setClickListener(MainActivity.this);
                            recyclerView.setAdapter(adapter);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }

                    }

                    @Override
                    public void onError(ANError error) {
                        Log.d(TAG, "onError: Failed" + error); //untuk log pada onerror
                    }
                });
    }

}

The values of usernameFriendsProfile is [falah, ilham] but on the display it only shows the first index like this
The contact interface -

this is the active_main.xml
    <?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">
<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/addFriendButton"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_toLeftOf="@+id/searchButton"
        android:src="@drawable/add_friend"/>

    <ImageView
        android:id="@+id/searchButton"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="20dp"
        android:layout_toLeftOf="@+id/settingButton"
        android:src="@drawable/search"
        />

    <ImageView
        android:id="@+id/settingButton"
        android:layout_width="25dp"
        android:layout_height="25dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="5dp"
        android:src="@drawable/setting"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="50dp"
        android:id="@+id/myprofile"
        >

        <ImageView
            android:id="@+id/avatar"
            android:layout_width="50dp"
            android:layout_height="50dp"
            android:src="@drawable/avatar" />

        <TextView
            android:id="@+id/user"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:layout_marginLeft="10dp"
            android:text="Username" />
    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Teman"
        android:layout_below="@id/myprofile"
        android:layout_marginTop="20dp"
        android:paddingLeft="10dp"
        android:id="@+id/contact"
        />
   <android.support.v7.widget.RecyclerView
       android:layout_width="wrap_content"
       android:layout_height="wrap_content"
       android:layout_below="@+id/contact"
       android:id="@+id/teman"
       />

</RelativeLayout>

this is on contact recycleview xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal"
    android:paddingLeft="20dp"
    >

    <ImageView
        android:id="@+id/avatar"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:src="@drawable/avatar" />

    <TextView
        android:id="@+id/usernameTeman"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:layout_marginLeft="10dp"
        android:text="Username" />
</LinearLayout>

</android.support.constraint.ConstraintLayout>

Comment: What exactly is your problem?
Comment: the recyclerview only show  one contact but actually there are two contacts on array
Comment: Can you please attach your layout codes - for activity_main.xml, and contact_recyclerview
Comment: yes i already add it
Answer: RecyclerView
Definition:

If your app needs to display a scrolling list of elements based on
  large data sets (or data that frequently changes), you should use
  RecyclerView as described on this page.

The most common issue with the UI not showing all the elements could be:
The item layout for each row that you are using here, in this case, is
R.layout.contact_recyclerview I suggest you make the     android:layout_height="wrap_content" in the XML file.


select where year less than 2014

Question: I want to select all posts from 2014 or less. How can I do this?
SELECT id, fotos, cover, titulo, descricao, data, link_key FROM posts where `date` < '2014'

data is datetime.
Comment: Possible duplicate of [sql take year and month from date](http://stackoverflow.com/questions/34229581/sql-take-year-and-month-from-date)
Answer: I would suggestion:
where date < '2014-01-01'

Keeping the comparison simple ensures that indexes and partitions can be used for the query.
Answer: You can use extract function.
SELECT id,
       fotos,
       cover,
       titulo,
       descricao,
       data,
       link_key
FROM posts
WHERE EXTRACT(YEAR FROM date) < 2014

Answer: You could also use the YEAR function:
SELECT id,
       fotos,
       cover,
       titulo,
       descricao,
       data,
       link_key
FROM posts
WHERE YEAR(date) < 2014

select where year less than 2014


force download script downloads 0kb file

Question: I use this script to download a file but what i get is a 0kb file
How can i solve this? The video files have a size of 100MB. Do i need to do any changes in php.ini?
<code>//$myfile = "http://localhost/project/".$_POST['file'];
$myfile='http://localhost/project/upload/WP_20130425_002.mp4';

$temp = explode(".",$myfile);
$ext = strtolower(end($temp));
$mime_types = array(

        // video
        '3gp' => 'video/3gpp',
        '3g2' => 'video/3g2',
        'avi' => 'video/avi',
        'mp4' => 'video/mp4',
        'asf' => 'video/asf',
        'mov' => 'video/quicktime',
    );
if (array_key_exists($ext, $mime_types)){
$mm_type=$mime_types[$ext];
}
else{
$mm_type="application/octet-stream";
}

//header("Cache-Control: public, must-revalidate");
header("Pragma: public");

header("Content-Type: ".$mm_type);

header('Content-Disposition: attachment; filename='.basename($myfile));
header('Content-Length: '.filesize($myfile));
header("Content-Transfer-Encoding: binary");
ob_clean();
flush();
readfile($myfile);
</code>
UPDATE: Problem resolved. I removed the full pathname to relative path name and things worked. :)
Comment: If you solved your problem, either post the answer and accept it, or delete the question.
Answer: UPDATE: Problem resolved. I removed the full pathname to relative path name and things worked. :)
So instead of :
<code>$myfile='http://localhost/project/upload/WP_20130425_002.mp4';
</code>
I used this:
<code>$myfile='upload/WP_20130425_002.mp4';
</code>


Alinhar botão JPanel

Question: Quero alinhar um único botão ao JPanel, mas não estou conseguindo, esta usando o layout padrão.
public class Test extends JFrame {

    private JButton btn;
    private JPanel painel;
    private JScrollPane scroll;
    private JTextArea tArea;

    public Test() {

        btn = new JButton("Sair");
        btn.setPreferredSize(new Dimension(72, 35));
        btn.addActionListener(e -> System.exit(0));

        painel = new JPanel();
        painel.add(btn, FlowLayout.LEFT); //nao funciona

        JScrollPane scroll = new JScrollPane(tArea = new JTextArea());
        scroll.setPreferredSize(new Dimension(400, 300));
        scroll.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);

        Container cp = getContentPane();
        cp.add(painel, "North");
        cp.add(scroll, "Center");

        getRootPane().setDefaultButton(btn);

        setSize(400, 280);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(EXIT_ON_CLOSE);
    }

    public static void main(String[] args) {
        new Test().setVisible(true);
    }

}

Comment: Alinhar como, a esquerda?
Comment: Isso mesmo, esqueci de dizer.
Comment: A resposta lhe ajudou? Se sim, você pode marcá-la como aceita, clicando no `v` a esquerda da resposta :)
Answer: Não funciona porque no caso do FlowLayout, não é bem desta forma que você configura o modo de alinhamento dele, não é como se faz com o BorderLayout.
Você deve recuperar o layout do JPanel e chamar o método setAlignment(), passando um dos cinco modos suportados por esse gerenciador de layout, no seu caso, o modo FlowLayout.LEFT:
painel = new JPanel();
FlowLayout layout = (FlowLayout) painel.getLayout();
layout.setAlignment(FlowLayout.LEFT);
painel.add(btn);

Ou simplificando:
((FlowLayout)painel.getLayout()).setAlignment(FlowLayout.LEFT);

Há outro jeito também, que é instanciando este layout na inicialização do painel, já passando o alinhamento, apesar de achar um desperdicio, pois este layout já é criado pelo java, mas pode ser uma opção:
painel = new JPanel(new FlowLayout(FlowLayout.LEFT));

Deixo aqui alguns links bastante úteis a respeito:

A Visual Guide to Layout Managers
Using Layout Managers
How to Use Various Layout Managers

Alinhar botão JPanel


How to add web folder to chef's private nginx?

Question: In my Chef recipes I use remote_file to access files at http server. I would like to use Chef server's ngnix to serve those files.
How to configure Chef's nginx to serve files in specific folder using http?
Comment: That's a very bad idea. 1) This is not a supported feature. 2) It will break at any update if you persist and tweak it. 3) Use a real artifact manager like nexus or artifactory OR use a standalone nginx/apache to provide those packages, you'll thank yourself later.
Answer: This is not a feature of Chef. You can use the files/ folder in a cookbook and the cookbook_file resource to serve files directly from the Chef Server but it is very limited and you should really use your own server to manage large files or complex downloads.
Answer: We have many machines in LAN to be configured with Chef. There are also many remote_file resources in our recipes. The problem was: downloading from internet takes a lot of time, but at the same time the file was available on another machine in LAN.
What I did is:

Installed Nexus for binary file storage.
Monkeypatched remote_file resource using a library in a cookbook, so that it gets loaded every time a cookbook is loaded overwriting original resource behaviour.

Now every time remote_file resource has to download some file, it will first ask Nexus. If that file is available in Nexus, it downloads from there.
If there is no such file there, Chef downloads the file from original source and then uploads it to Nexus too for other nodes.
Comment: I did not want to install one more software. Maintenance, documentation,... I was hopping to get single entry in existing/new config file.
Comment: Sounds somewhat complex to me. Setting up just an nginx instance shouldn't be that much hassle, right? If VMs are expensive to you, let it run on the same node as the Chef Server, but a second nginx instance on another port. Don't fiddle with Chef Server setup itself.


Como pegar dados do Lado Cliente para o Servidor

Question: Olá.
Desenvolvi uma aplicação em .NET CORE e na pagina de acesso vai pegar a geolocalização do cliente com as coordenadas de Longitude e Latitude. Porém, fiz este código usando javascript, e o mesmo ira rodar no lado do cliente, fiz um implemento para preencher 2 Label com as informações, mas não estou conseguindo enviar estas para o meu servidor, minha ideia e armazenar a localização (Com o conhecimento do cliente), porém não esta funcionado, não estou conseguindo fazer isso.
Abaixo o javascript que estou pegando a localização, e na sequencia como estao as label dentro do meu html, nao coloquei ele todo mas esta dentro de uma form, estou.
Javascript

HTML

            <asp:Label ID="Label1" runat="server" Text="Controle de Acesso "></asp:Label>

            <asp:Label ID="lblat" runat="server" > </asp:Label>

            <asp:Label ID="lblog" runat="server" Text=""> </asp:Label>

            <asp:Label ID="lbIp" runat="server" Text=""></asp:Label>

            <asp:Label ID="lbHost" runat="server" Text=""></asp:Label>

             <asp:Label ID="Label3" runat="server" Text=""></asp:Label>

             <asp:Label ID="lboutro" runat="server" Text=""></asp:Label>

             <asp:Label ID="lat" runat="server" Text=""></asp:Label>

             <asp:Label ID="lot" runat="server" Text=""></asp:Label>

abaixo um print da minha aplicação pegando as informações, quero pegar elas para armazenar em um banco de dados e usar isso para comparar os locais de acesso do cliente, e caso tenha algum acesso em um local diferente executara alguma ação.
Comment: Se você deseja enviar dados do client para o servidor você precisa fazer uma requisição GET ou POST para assim. Assim como implementar a recepção desse request no servidor para o tratamento necessário.
Comment: O que não faz muito sentido é você estar utilizando componentes do ASP.NET que com a declaração `Runat="Server"`, sendo que eles não têm nenhum interação com o servidor e sua manipulação está sendo realizada apenas no lado do cliente, via javascript. Isso está servindo apenas para deixar a renderização de sua página um pouco mais lenta e adicionando uma carga desnecessária no lado do servidor.
Answer: Para enviar as informações do cliente ao servidor, aconselho utilizar ajax, já que está trabalhando com o javascript e também não precisa da interação do cliente. O .Net Core não trabalha com a sintaxe de "Runat=Server".
Essa documentação deixa bem claro como efetuar o procedimento:

https://api.jquery.com/jquery.post/


How to configure bind to not to do internal recursion?

Question: While quering my authoritative-name-server (implemented with bind locally in VM) for "A" record of "host1.cool.com", it internally resolves the query using recursion (maybe) and returns with the actual "A" record. I need the nameserver to reply with one CNAME record each query, the recursive resolver can issue multiple dns query to resolve the name. But, I have not been able to do that with setting "recursion no;" to "named.conf.options".
My query (from another machine):
dig A @192.168.0.115 host1.cool.com

Response is the whole CNAME chain, and the final answer:
;; ANSWER SECTION:
host1.cool.com.     5   IN  CNAME   host2.cool.com.
host2.cool.com.     5   IN  CNAME   host3.cool.com.
host3.cool.com.     5   IN  CNAME   host4.cool.com.
host4.cool.com.     5   IN  CNAME   host5.cool.com.
host5.cool.com.     5   IN  CNAME   host6.cool.com.
host6.cool.com.     5   IN  CNAME   host7.cool.com.
host7.cool.com.     5   IN  A   22.214.171.124

I want the nameserver to respond with just one CNAME record even for the "A" query. Maybe something like this:
host1.cool.com CNAME host2.cool.com

My named.conf.local file
zone "cool.com" IN {
  type master;
  file "/etc/bind/db.cool.com";
  allow-transfer { none; };
};

And named.conf.options file
options {
  directory "/var/cache/bind";
  auth-nxdomain no;
  allow-query { any; };
  allow-transfer { none; };
  recursion no;
};

db.cool.com file
@TTL 5S

@  IN  SOA  @ hostmaster.cool.com. (
  0, 3H, 1H, 1W, 3H )

@  IN  NS  ns1.cool.com.
@  IN  NS  ns2.cool.com.
@  IN  A   18.104.22.168

ns1  IN  A  10.20.30.40
ns2  IN  A  10.20.30.41

host1.cool.com.  IN  CNAME  host2.cool.com.
host2.cool.com.  IN  CNAME  host3.cool.com.
host3.cool.com.  IN  CNAME  host4.cool.com.
host4.cool.com.  IN  A      188.8.131.52

How to configure bind not to internally use recursion to resolve the query?
Answer: This type of behaviour would break CNAMEs. If you don't want to get the IP-Address, you shouldn't query A/AAAA resource records (RRs), but ask the server explicitly for CNAME.
Quoting RFC 1034:

CNAME RRs cause special action in DNS software.  When a name server
fails to find a desired RR in the resource set associated with the
domain name, it checks to see if the resource set consists of a CNAME
record with a matching class.  If so, the name server includes the
CNAME record in the response and restarts the query at the domain name
specified in the data field of the CNAME record.  The one exception to
this rule is that queries which match the CNAME type are not
restarted.
For example, suppose a name server was processing a query with for
USC- ISIC.ARPA, asking for type A information, and had the following
resource records:
USC-ISIC.ARPA   IN      CNAME   C.ISI.EDU

C.ISI.EDU       IN      A       10.0.0.52

Both of these RRs would be returned in the response to the type A
query, while a type CNAME or * query should return just the CNAME.

Recursion, in DNS-speak, is when your DNS server resolves names starting from the root zone, recursively descending zones until reaching the terminal label an querying the desired RR.


What happened to IIS lockdown?

Question: A long time ago before I left the Windows environment, there was such a thing as "IIS lockdown tool" - something that Microsoft provided for free. It was meant to well lock down your IIS instance and do some common security tests and tell you about what potential security weaknesses of your IIS/MS SQL are, what happened to that?
Here is my situation right now,
I have access to a Windows 2003 SP2 server (MS SQL Server Web Edition 10.0), that has been hacked once. It hosts an asp website, and we think it's been compromised via an SQL injection. The developers who wrote this a decade ago say there were different users there for read and write, and that it was not configured properly hence it got hacked.
Fixing the code is nearly impossible, so right now I'm looking for something that would make IIS and SQL as secure as possible.
Is there some kind of tool/module I could install on IIS to scan for SQL injection?
Anything like IIS lockdown?
Answer: If the site was attacked via SQL Injection, the only thing that can fix it is fixing the code.
Comment: Again, the ONLY way to fix SQL Injection is to fix the code.  Nothing else will fix it.  The only other option would be to down the site until dev resources can be found to fix it. If the app is that important to the business surely they can find some budget to fix it.  I suppose that you could buy a SQL Firewall to inspect all the sql commands being executed and block the ones that are a problem but this will probably be more expensive than just fixing the site.
Comment: You mean shut down the site? Only alternative. 10 years without maintenancy - sure. Have fun.
Comment: Seriously: FIX. THE. CODE. OR. SCRAP. THE. CODE. I appreciate you don't want to hear that but it doesn't make it any less of the correct answer. Anything else isn't "making IIS and SQL as secure as possible", its fiddling while Rome burns.
Comment: Well yes, but as I mentioned in the question that is not an option at this point. So I'm trying to do whatever "else" I can.
Answer: According to Microsoft, IIS Lockdown is still available:

http://www.microsoft.com/download/en/details.aspx?id=25064 (oldest)
http://support.microsoft.com/kb/325864 (IIS 6)
http://technet.microsoft.com/en-us/library/dd450372(WS.10).aspx (for Vista, Windows 7, Windows 2008)
Answer: Here is my little friend, UrlScan, what exactly I was looking for
http://technet.microsoft.com/en-us/security/cc242650
Answer: There are tools claiming to be "application layer firewalls" or something like that which will scan for SQL injection but I am not familiar with any one product to say "go buy this". If you are using a hosting provider they may have something like this available.
IIS lockdown will reduce your attack surface but it will not mitigate the existing problems you have.

What happened to IIS lockdown?


Related nodes by taxonomy term in a view block

Question: In Drupal 7, I've got a content type called "Asset" with a taxonomy field called "Category". All I need is a Block on the Asset pages that looks at the current node's Category term(s), finds all other Asset nodes tagged similarly, and spits out a list of their titles, links to them, and a few other bits of info from their node.
A Views Block was my first thought... but I'm having a heck of a time making this happen in Drupal 7. Maybe it's problematic because my URL doesn't include the Term ID? Anyway, I've searched and followed a bunch of tutorials (like this one and this one), but to no avail. So, here are my questions:

If Views is the answer, what am I doing wrong?
Is there a Drupal 7 module that can do this for me?
Comment: The first tutorial you listed should do exactly what you wish. (Forget the second one!) If you are not able to get it to work, it just means you are not understanding. Have another go, and see where you can take it.
Comment: @Triskelion, I'll surely give it another go... but I followed it precisely!
Comment: Once you have the view, let me know what problems you are having.
Comment: With a little tweaking... IT WORKED! I'm at the refining stage of the Views build process, so it's not perfect, but it's getting there. I'll be honest, I don't really understand the Aggregation part.
Comment: This answer on StackOverflow did the trick... with a little tweaking: [Creating list of similar nodes in Drupal 7/Views 3](http://stackoverflow.com/questions/10454507/creating-list-of-similar-nodes-in-drupal-7-views-3)
Answer: I've done a little tweaking myself, and I seem to have gotten a working solution here.

Create a new block for the nodes you'd like to display
Add a new Contextual Filter: Content: Has Taxonomyterm-ID
Select: "when the filter is not available, provide a default value: Taxonomyterm-ID from URL."
Put a check next to "Load Standard Filter from node-page, useful for related taxonomyblocks"
And you will probably want to limit the vocabulary as well

In order to exclude the current Node you have to add a second Contextual Filter for Node-ID, provide default value as the content ID from URL and at the bottom of the modal pop open 'More' and check 'Exclude'
Comment: Brilliant answer. Just what I was looking for!
Comment: But it matches only with first term available in that node, how to match with all?
Comment: 5 years later, this answer is still relevant, concise and most importantly flawless. Thank you!
Comment: 7 years later, +1


Create a Background Service (Android, WP8) using Visual Studio - Cordova

Question: I have created a Multi Device Hybrid App, it's working amazing.
I want to create a background service for the app, which runs even if the app is closed. After reading some posts, I found out Cordova doesn't support this natively.
Only addin I found was this one: https://github.com/katzer/cordova-plugin-background-mode
It does the trick 50%, it works, as long as the app isn't force closed. That's not suitable.
Other posts I found was that I have to write a native service. But all posts are focusing on Phonegap / using Eclipse for the Android part. How do I write Java in the Visual Studio solution?
Comment: Anyone?? This must not be so hard, right?
Comment: Thanks for revealing that cordova-plugin-background-mode only works until the app is killed.
Answer: There is no way to create a plugin in Visual Studio today.
That being said, the cordova library to create WP8 plugins can be found here. This library can then be used to create a WP8 plugin as documented here
Answer: Alright, it is easier than I thought. I just have to write a plugin to call the native code. This is a create starting point: https://github.com/Red-Folder/bgs-core
I now can of course add a WP8 folder, add the required .cs files and it should work. However, how do I debug the plugin? I cannot find any information regarding developing/debugging plugins with Visual Studio. Also the documentation re debugging plugins for Cordova is not enough: http://cordova.apache.org/docs/en/2.5.0/guide_plugin-development_windows-phone_index.md.html
It starts with "Add a file to the project", but what type of project? I cannot add a class file to a Cordova project.
Help is appreciated.


Babel not working as expected, Error : Uncaught ReferenceError: require is not defined

Question: I am trying to transpile this simple code so as to use in browser, but its not working and getting Uncaught ReferenceError: require is not defined at line require('uniq')(array);
I know browser ( chrome in my case ) doesn't support require, but I thought that's what babel supposed to do.
I can use webpack or browserify, but this time I am trying my hands on Babel and come across this issue.
package.json
"devDependencies": {
    "@babel/cli": "^7.11.5",
    "@babel/core": "^7.11.5",
    "@babel/preset-env": "^7.11.5"
  },
  "dependencies": {
    "@babel/polyfill": "^7.11.5",
    "uniq": "^1.0.1"
  }

index.js
const array = [1,1,2,2,3,5]
require('uniq')(array)
document.querySelector('p').innerText = array

using babel to transpile
npx babel index.js --out-file index2.js
index2.js ( generated by babel )
"use strict";
const array = [1, 1, 2, 2, 3, 5];
require('uniq')(array);
document.querySelector('p').innerText = array;

babel.config.json
{
  "presets": [
    [
      "@babel/env",
      {
        "targets": {
          "edge": "17",
          "firefox": "60",
          "chrome": "67",
          "safari": "11.1",
        },
        "useBuiltIns": "usage",
        "corejs": "3.6.4",
      }
    ]
  ]
}

index.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Babel Example</title>

Babel Example

Comment: You need to use a bundler like webpack for this. Babel does not provide this functionality, it is a language transpiler.
Comment: *"but I thought thats what babel supposed to do"* No. Babel just transforms from one JavaScript version to another. It does not concerned with module loading/processing.
Comment: Babel just transforms your code to `commonjs` which is not runnable on browser. Consider to write as esmodule which can run on browser by specify module attribute on script tag.
Answer: looks like the same issue was discussed here
https://github.com/babel/gulp-babel/issues/117
You just need to add the env preset
--presets=@babel/preset-env
https://babeljs.io/docs/en/babel-cli#using-presets
Your transpile command should become
npx babel index.js --out-file index2.js --presets=@babel/preset-env
Comment: I tried as per your suggestion, no change in output, and the presets parameter you suggested, is already there in babel.config.json I posted above.
Comment: hmm yeah actually, might be more complicated, this is a similar question: https://stackoverflow.com/questions/31593694/do-i-need-require-js-when-i-use-babel


Convergence/ divergence of $\sum_{k\geqslant 1}\frac{1}{k+1}\frac{1}{\sqrt{\pi k}}(4(1-r)r)^k$

Question: Consider the series
$$
\sum_{k\geqslant 1}\frac{1}{k+1}\frac{1}{\sqrt{\pi k}}(4(1-r)r)^k.
$$
Why does it converge if $r\neq \frac{1}{2}$, why diverge if not?

If $r\neq\frac{1}{2}$, then $4(1-r)r<1$, but why does it converge then and why not converge if $4(1-r)r\geqslant 1$?
Answer: Hint
We have

if $|a|<1$ then
$$k^2\frac{1}{k+1}\frac{1}{\sqrt{\pi k}} a^k\xrightarrow{k\to\infty}0\implies \frac{1}{k+1}\frac{1}{\sqrt{\pi k}} a^k=\left(\frac1{k^2}\right) $$
so the series
$$\sum \frac{1}{k+1}\frac{1}{\sqrt{\pi k}} a^k$$
is convergent by comparison with $\sum\frac1{k^2}$.
if $ |a|>1$  then
$$\frac{1}{k+1}\frac{1}{\sqrt{\pi k}} a^k \xrightarrow{k\to\infty}\infty$$
so the series is clearly divergent.
if $|a|=1$ and since
$$ \frac{1}{k+1}\frac{1}{\sqrt{\pi k}}\sim_\infty \pi^{-1/2}\frac1{k^{3/2}}$$
then the series is absolutely convergent by comparison with $\sum\frac1{k^{3/2}}$

Now for what values of $r$ we have
$$4|r(1-r)|\le 1$$
Answer: If  $|4(1-r)r|<1$, then  series converges by ratio test.:
$$\lim_{k \to \infty}\frac{|a_{k+1}|}{|a_{k}|}=\lim_{k \to \infty}|4(1-r)r|\frac{(k+1)\sqrt{\pi k}}{(k+2)\sqrt{\pi (k+1)}}=|4(1-r)r|<1$$
If $|4(1-r)r|>1$ then series doesn't converges also by ratio test.
If $|4(1-r)r|=1$, then you have two cases:
First: $4(1-r)r=-1$, then series converges by alternating series test.
Second: $4(1-r)r=1$ (it's only when $r=\frac{1}{2}$), then series converges by integral test:
$$\sum_{k=1}^{\infty}\frac{1}{(k+1)\sqrt{\pi k}} \leq \pi^{-1}\sum_{k=1}^{\infty}\frac{1}{k\sqrt{ k}} < \infty$$
Because:
$$\int_{1}^{\infty}\frac{1}{x\sqrt{x}} dx < \infty$$


May I ask how to repaint() repeatedly?

Question: Excuse me,May I ask java repaint repeatlyed questions,
I meet a trouble that I use drafting repeatedly  to express Pacman Open&Close mouth motion.
But this program Only once will not move...
Somebody can help me to solve this problem...
Very thanks so much!:D
My code as below:
package Strive;
import java.awt.*;
import java.awt.geom.*;
import javax.swing.*;

class CDrawF extends JFrame {
    CDrawF (){
        setTitle("繪製各式圖形");                       //JFrame interface
        setBounds(50, 50, 490, 260);        setVisible(true);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    public void paint(Graphics g) {
        Graphics2D g2 = (Graphics2D) g;
        for(int i = 0; i<= 360; i++){              //repeatly 360 times
        repaint();
        g2.setColor(new Color(1.0f, 0.0f, 1.0f));
        g2.fill(new Arc2D.Double(100, 100, 80, 80, 30, 300, Arc2D.PIE));
        //PacMan close mouth
        repaint();
        try{            //Delay setions
                Thread.sleep(1000);
             }catch(InterruptedException ex){}
        g2.fill(new Arc2D.Double(100, 100, 80, 80, 10, 340, Arc2D.PIE));
        //PacMan open mouth
        repaint();
        }
    }
}

public class NewClass {          //Main
    public static void main(String[] args){
        new CDrawF ();
    }
}

Comment: possible duplicate of [Pacman open/close mouth animation](http://stackoverflow.com/questions/14426693/pacman-open-close-mouth-animation)
Answer: Suggestions:

Don't draw directly in the JFrame
Don't draw in the paint(...) method.
Never call Thread.sleep(...) on the Swing event thread
And especially don't call it in a paint(...) or paintComponent(...) method.
Instead draw in a JPanel or JComponent's paintComponent(...) method
Read the Java graphics tutorials as they will explain all of this.
Don't call repaint() inside of paint(...) or paintComponent(...)
Use a Swing Timer for your animation loop. Again the tutorials will help you do this.
Comment: And for example please check out [this link](http://stackoverflow.com/a/9986368/522444), and [this](http://stackoverflow.com/a/4702819/522444), and [this](http://stackoverflow.com/a/12545773/522444).
Comment: +1 ... Lol I am fighting myself to not add more exmaples of my own :P
Comment: @DavidKroukamp: ah go ahead, why not?

May I ask how to repaint() repeatedly?


angular history route and fragment

Question: my angular app use the history route path
localhost/blog/article/:id
when this route on open localhost/blog/article/123456, httpclient get some markdown content data and render
the markdown content
- [one](#one)
- [two](#two)

# one
some thing

# two
some thing

render html
one
two

one

some thing

one

some thing

but click the a tag redirect to root path
how to scroll to the fragment when clicking on a tag
---------UPDATE---------
The problem has been solved
refer to here
Answer: You need to enable anchorScrolling in RouterModule.forRoot() like below :-
RouterModule.forRoot({anchorScrolling: true})

And use fragment attribute to assign the fragment like above instead of href.
Dashboard

You can read about it here :-
https://medium.com/dev-genius/advanced-router-configuration-in-angular-d22c6dc420be
Or :-
https://angular.io/api/router/ExtraOptions
Comment: can't use fragment attribute,because makerdown component according to standard render `[one](#one)` html content is `one`,so i don't know what to do

angular history route and fragment


Not sure why inner promise is not firing

Question: I'm new to Promises with Parse Cloud Code and I'm having some difficulty figuring out why my inner promise is not correctly firing. I get all the way through majority of my promises, but it's not getting to the comment. Is there something I'm missing, or did I not structure this correctly?
You'll see where it breaks down in the comment, but it should get a user for each of the IDs in the array and then send the SMS message.
I based my code on the following topic:
https://www.parse.com/questions/executing-query-within-promisethen-block
app.post('/send_sms_group', function(req, res) {

    var to_group = req.body.to;
    var from = req.body.from;
    var message = req.body.message;

    var Groups = Parse.Object.extend("Groups");
    var query = new Parse.Query(Groups);
    query.get(to_group).then(function(group){
        return group;
    }).then(function(group){
        var groupOwner = group.get("groupOwner");
        var members = group.get("members");
        var promise = Parse.Promise.as();
        for (i=0; i<members.length; i++)
        {
            var memberId = members[i];
            if(memberId != groupOwner.id){
                promise = promise.then(function(){
                    var findUser = new Parse.Query(Parse.User);
                    findUser.get(memberId).then(function(participant){
                        // Not getting here
                        console.log(participant);
                        if(participant.get('phone')){
                            console.log(participant.get('phone'));
                            if(!participant.get('isClaimed')){
                                console.log(participant.get('isClaimed'));
                                twilio_client.sendSms({
                                    to:participant.get('phone'),
                                    from:from,
                                    body:message
                                  }, function(err, responseData) {
                                    console.log(responseData);
                                    return responseData;
                                  }
                                );
                            }
                        }
                    });
                });
            }
        }
        return promise;
    }).then(function(){
        res.json(200, {"status":"success"});
    }, function(error) {
        console.log(error);
        res.json(400,error);
    });
});

Comment: Add a catch listener to see if you have any errors in your code.
Comment: I'm still trying to help, but the first `.then(function(group){return group;})` is unecessary
Comment: You should return the result of findUser.get(memberId), which is a promise itself. That is `return findUser.get(memberId).then(function(participant){`
Comment: Holy smokes that was it! Thanks xissburg! Also, thanks for the help gfpacheco and Benjamin, I modified with both of your answers as well to clean up my code.
Comment: a) you are missing a few `return` statements in those callbacks - you always will need to return promises from asynchronous function b) you've fell for the classical [closure in a loop](http://stackoverflow.com/q/750486/1048572) mistake
Comment: Take a look at my answer below for a more readable code, you may want to change your code for better maintainability
Answer: I'm still trying to understand the details of your code. But I think you want to:

Get the users group
Remove the group owner from the users ids
Get the users
Remove users that don't have phone or "are claimed"
Send an sms to the filtered list

And looks like your members field is an array of strings, not an array of pointers.
Take a look at this and try to understand what's happening:
app.post('/send_sms_group', function(req, res) {
  var to_group = req.body.to;
  var from = req.body.from;
  var message = req.body.message;

  // Get the group
  var groupQuery = new Parse.Query(Groups);
  groupQuery.get(to_group)
  .then(function(group) {
    var owner = group.get('groupOwner'),
        userIds = group.get('members'),
        usersQuery = new Parse.Query(Parse.User);

    // Remove the group owner
    userIds = userIds.filter(function(user) {
      return user !== owner.id;
    });

    // Get the users
    usersQuery.containedIn('objectId', userIds);
    return usersQuery.find();
  })
  .then(function(users) {
    // Remove users without phone or "are claimed"
    users = users.filter(function(user) {
      return user.get('phone') && !user.get('isClaimed');
    });

    // Send SMS for each user
    var smsPromises = users.map(function(user) {
      return twilio_client.sendSms({
        to: user.get('phone'),
        from: from,
        body: message
      };
    });

    return Parse.Promise.when(smsPromises);
  })
  .then(function() {
    res.json(200, {'status': 'success'});
  }, function(err) {
    console.error(err);
    res.json(400, err);
  });
});

Comment: Marking this correct, because it works a lot quicker and more efficient for sure. There are a few errors in it I had to fix that I list below for others who might come along later:

Change to usersQuery.containedIn("objectId",userIds);
Comment: Right, I updated the answer with the fix. I actually didn't test the code, is there anything else you had to do before it work?


Probability question about sharing range of quantity

Question: Suppose we have 10 Boxes, John shares into 7 of them, and Mike shares into 5 boxes.
**The Question :**what is the expected number of boxes are shared between John and Mike?
using equation :7*5 /100 =0.35? then 3.5 is the avg or expected value
Comment: The expected number of shared boxes is $0.35$? It has to be at least $2$: There are $10$ boxes, John shares $7$ of them, leaving only $3$ that Mike can share without John. Since Mike shares $5$ boxes, he must share at least $2$ of the $7$ boxes that John share.
Answer: Let a count for those of John alone, b count for those shared by John and Mike, c count for those of Mike alone. Then we have a+b=7,b+c=5, a+b+c=10. Solving we get a=5,b=2 and c=3. The probability is 2/10.
Comment: at least 2, and at maximum =5 so avg = expected = (2+5 )/2=3.5
Comment: why decreasing my rank.?? whyyyyyy