How to send custom object using serialization?

Question: I'm new to Java. I need to send over socket the file content, together with a double number. My idea is to wrap these two fields into a custom object. Since object File is not serializable, how to send/recv this custom object? Thanks in advance. PS: The sending party will decide if it needs to send the file according to the value of the "double" number. For example:
class MyObject{
    double number;
    File file;
}

When sending, the logic is something like this:
MyObject my = new MyObject();

if(my.number > 0){
    my.file = open_file(aaa.jpg);
}else{
    //Not opening any file
}

send(my);

Comment: The `File` object in java represents the _path_ of a file, **not** its content. You would need to send the contents of a `FileInputStream` over your socket.
Comment: firstly, thanks for your attention. Yes. I know. It's just pseudo code. The idea of the logic is that I don't need to send the file every time. It depends on the value of the number.
Answer: Here is a quick example application that sends data to itself over Sockets.
public class App {

    private static final AtomicInteger port = new AtomicInteger(-1);
    private static final AtomicBoolean read = new AtomicBoolean(true);

    private static final class SocketReader implements Runnable {

        @Override
        public void run() {
            try {
                final ServerSocket serverSocket = new ServerSocket(0);
                System.out.println("Connected on " + serverSocket);
                synchronized (port) {
                    port.set(serverSocket.getLocalPort());
                    port.notifyAll();
                }
                while (read.get()) {
                    try (final Socket socket = serverSocket.accept()) {
                        final DataInputStream dis = new DataInputStream(socket.getInputStream());
                        System.out.println(dis.readDouble());
                        byte[] buffer = new byte[1024];
                        int numRead;
                        while ((numRead = dis.read(buffer)) != -1) {
                            System.out.print(new String(buffer, 0, numRead, "UTF-8"));
                        }
                    }

                }
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }

        }
    }

    private static final class SocketWriter implements Runnable {

        private final double d;
        private final File file;

        public SocketWriter(double d, File file) {
            this.d = d;
            this.file = file;
        }

        @Override
        public void run() {
            try {
                while (port.get() < 1) {
                    synchronized (port) {
                        port.wait();
                    }
                }
                try (final Socket clientSocket = new Socket("localhost", port.get());
                        final DataOutputStream dos = new DataOutputStream(clientSocket.getOutputStream())) {
                    System.out.println(clientSocket);
                    dos.writeDouble(d);
                    try (final FileInputStream fis = new FileInputStream(file)) {
                        byte[] buffer = new byte[1024];
                        int bytesRead;
                        while ((bytesRead = fis.read(buffer)) != -1) {
                            dos.write(buffer, 0, bytesRead);
                        }
                    }
                    dos.flush();
                }
            } catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
        final double d = 2.35;
        final File f = new File(new File(System.getProperty("user.home"), "Downloads"), "readme.txt");
        final ExecutorService executorService = Executors.newSingleThreadExecutor();
        final Future<?> future = executorService.submit(new SocketReader());
        new SocketWriter(d, f).run();
        read.set(false);
        executorService.shutdownNow();
        try {
            future.get();
        } catch (ExecutionException ex) {
            throw new RuntimeException(ex);
        }
    }
}

First we send the double serialised, then it sends the contents of a random file in my Downloads directory.
Another Thread, meanwhile, echos all that to the console.
Comment: thanks. I also know it's possible to send the two fields like this way. But the point is how to wrap it into an custom object.
Comment: You can always read your `File` into a `String` or `byte[]` and send it - that would require holding the whole file in memory however - a little expensive. From your comment - the reader can close the stream if it doesn't want the `File`...
Comment: Hi. I ran your code. It worked when the file is readme.txt. When I replace it with a.jpg, it didn't work. The reader was blocked in `line = bufferedReader.readLine()`. Could you please tell me how to solve it?
Comment: This code does not work. It uses both an ObjectInputStream and a BufferedReader on the same socket. Both these buffer, and they will both steal data from each other. Untested guesswork. -1
Comment: @EJP this is untrue. Check the source code for `ObjectInputStream`. The `readDouble` method reads the stream header then exactly 8 bytes in order the read the `double`.
Comment: @EJP further, [this](http://stackoverflow.com/questions/3365261/does-a-buffered-objectinputstream-exist) SO post suggests that `ObjectInputStream` is not buffered in any case.
Comment: @bmorris (1) `ObjectInputStream` uses a 1k buffer, at least part of the time, including `readDouble()`. The answer you cited doesn't appear to know that. (2) `BufferedReader` uses a buffer of 4k `chars`, all the time. There's no actual reason to use `ObjectInput/OutputStream` here at all:  `DataInput/OutputStream` would work much better. It is also *incorrect* to use a `BufferedReader` as the input is being written as bytes by the peer. It should be an `InputStream`, preferably the same `DataInputStream` that was used to write the `double.`
Comment: @EJP I have changed the example as you suggest - using `DataInput/OutputStream`.


PS script stops after first else statement

Question: Trying to start multiple processes all at once, but the script fails after my first 'else' statement. I tried doing a try/catch over the entire thing to get errors, but it still fails on my test machine since Slack isn't installed. Should I be using something else to get this to run all the lines non-stop? Or should this be re-organized to test paths first and then proceed based on that?
$Dropbox = Get-CimInstance -Namespace "root\cimv2\sms" -Query "select * from sms_installedsoftware" | Where-Object {$_.ProductName -like "Dropbo*"}
$Dropboxapp = $app.installedlocation
$Slack = Get-CimInstance -Namespace "root\cimv2\sms" -Query "select * from sms_installedsoftware" | Where-Object {$_.ProductName -like "Slack*"}
$SlackApp = $slack.installedlocation
$Office = Get-CimInstance -Namespace "root\cimv2\sms" -Query "select * from sms_installedsoftware" | Where-Object {$_.ProductName -like "Office*"}
$OfficeApp = $Office.installedlocation

Start-Process "Chrome.exe" "www.google.com"
if ($SlackApp){
    start-process $env:USERPROFILE\AppData\Local\slack\slack.exe}
        else
            {write-host "Please Install Slack"}

if ($Dropboxapp){
    start-process "C:\Program Files (x86)\Dropbox\Client\dropbox.exe"}
        else
            {write-host "Dropbox does not appear to be installed"}

if ($OfficeApp){
    Start-Process Outlook.exe}
        Else
            {write-host "Office appears to be uninstalled or damaged"}

Answer: I suspect the second if block isn't firing because the second line of code should read:
$Dropboxapp = $$Dropbox.installedlocation

I have a feeling the 3rd If block doesn't fire because the query is wrong.  Office might be something like "Microsoft Office..."  So change to something like:
$Office = Get-CimInstance -Namespace "root\cimv2\sms" -Query "select * from sms_installedsoftware" | Where-Object {$_.ProductName -like "*Office*"}

Notice the extra "*"  My concern is "Microsoft Office" won't match "Office*" but it will match "*Office*"
Also it's a good practice to move filtering left.  Usually this is for performance though in this case that's not a problem.  Would look something like:
$Office = Get-CimInstance -Namespace "root\cimv2\sms" -Query "SELECT * FROM sms_installedsoftware WHERE ProductName LIKE '%Office%'"

Let me know if this helps.  Thanks.
Comment: The * is required for selection in the SMS_Installedsoftware, you're first note is 100% true. I had the wrong variable from earlier when the script was only going to do one program. This fixed it :)

Office variable works great, I don't much care what product is installed so it's very open ended.
Comment: I meant I added an extra "*" I modified the answer to reflect that.  Also typically you want to move filtering as far left as possible.  With WMI you can Spec a WQL query, so I added that example too.
Answer: Switch the order of the 'if' conditionals, or try one at a time and comment out others.  Also maybe put some logging in between things to see execution.  More likely this is a problem with logic tests of individual statements, rather than cadence or flow.
HTH
Comment: I removing the debugging in this to make it shorter. It makes it through just fine, but assigns 'yes' to every value, even though I type in 'no' in the parameter prompt


Polymer - Atribuir um valor padrão para uma content tag

Question: Eu estou criando um elemento Polymer com essa estrutura::

  <template>

      <content select="img"></content>
      <content select="h1"></content>

    <content></content>

  </template>

</polymer-element>

Para atribuir um valor padrão para o atributo src do elemento <content select="img"> eu adicionei o script:
Polymer({
   srcimg: 'default-picture.png'
});

Quando renderizado no browser o atributo é preenchido no  shadow DOM mas não no elemento  dentro do elemento <e-card>. Como fazer o elemento  assumir o valor atribuido pelo script caso ele não seja atribuído deliberadamente?
Answer: João Paulo, não acredito ser boa prática alterar conteúdo do "insertion point" à partir de seu componente pois isto destroi o encapsulamento. O "insertion point" serve para implementar injeção de dependência e permitir que o cliente especifique conteúdo a ser inserido em pontos definidos do layout do componente. Seguramente deve existir outra forma de implementar o que você deseja sem ferir o principio do encapsulamento ao qual o Polymer se propõe a fornecer no seu framework.
De qualquer forma segue o código para acessar e manipular a imagem substituindo o valor do atributo src.
OBS: testei apenas no GoogleChrome
O que você precisa é deste script:

O código completo aparece abaixo:
<!doctype html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=yes">
  <meta name="apple-mobile-web-app-capable" content="yes">

  <link rel="import" href="../polymer/polymer.html">

  <polymer-element name="my-element" attributes="">
    <template>

        <content select="img"></content>

        <content select="h5"></content>

        <content></content>
        Finalização do Componente - Footer

    </template>

  </polymer-element>

  <my-element>

Teste do Elemento

fig. 1 - network workgroup example

  </my-element>


Plugin calendario wordpress

Question: gente estou precisando urgente de um plugin de calendario free, que seja parecido com esse aqui
http://revistagloborural.globo.com/eventos.html
Alguem tem alguma sugestão ?
vlwww
Comment: O objetivo desta comunidade não é este, então sua pergunta provavelmente será fechada em breve. Se você tentar implementar um *plugin* semelhante ou obter algum erro durante sua utilização, sua pergunta será bem-vinda aqui.
Answer: Esse calendário está parecendo do plugin flatpickr. https://chmln.github.io/flatpickr/
Recomendo fortemente, é o melhor plugin que já utilizei!

flatpickr("#inline", {
 inline: true,
 weekNumbers: true
})
<link href="https://unpkg.com/flatpickr/dist/flatpickr.min.css" rel="stylesheet"/>
<link href="https://chmln.github.io/flatpickr/bower_components/flatpickr/dist/themes/material_green.css" rel="stylesheet"/>

<input class="flatpickr" type="text" placeholder="Select Date.." id="inline">

Plugin calendario wordpress


menu não fixa ao rolar a pagina

Question: quero que meu menu fique fixo assim que atingir o topo da pagina porem não estou obtendo sucesso com isso não sei onde estou errando segue meu código abaixo:

                <video id="Video1" class="bgvid" loop muted>
                    <source src="video/animacao-lol.mp4" type="video/mp4" />
                    desculpe mais seu navegador não suporta este formato ou esta desatualizado :(
                </video>

Olá amigos somos a Tec Mov !

dolor sit amet, consectetur adipiscing elit. Sed at risus neque.
Cras sit amet ligula
                    ut justo commodo porta id ut enim. Nulla est lectus, mollis sit amet vehicula id, volutpat eget mauris.

                 <button>Vamos Começar ?</button>

Home

Sobre

Galeria

Eventos

Equipe

Contato

O css do menu mais o do fixar:
   .menu-header{
        margin-top: 0px;
        position: absolute;
        top: auto;
        bottom: 0px;
        background-color: #fff;
        /*border-bottom: 5px solid #000;*/
        box-shadow: 0 4px 8px -1px #d7d7d7;
        width: 100%;
        height: 80px;

    }

    .menu{
        margin: 30px auto;
        text-align: center;

    }

    .menu li{
        display: inline;
    }

    .menu li a {
        margin: 15px;
        color: #000;
        font-family: 'Source Sans Pro', sans-serif;
        font-size: 1.1em;
        transition:0.3s;
    }

     .menu li a:hover {
         font-weight: bold;
         transition:0.3s;
    }

.fixar{
    top: 0;
    left: 0;
    position: fixed;
}

    @import url(http://fonts.googleapis.com/css?family=Dancing+Script);
    @import url(http://fonts.googleapis.com/css?family=Scada);
    @import url(http://fonts.googleapis.com/css?family=Source+Sans+Pro);
    html,
    body {
      margin: 0;
      padding: 0;
    }
    body {
      background-color: #FDFDFD;
    }
    a {
      text-decoration: none;
      outline: none;
    }
    .text-center {
      text-align: center;
    }
    button {
      cursor: pointer;
      outline: none;
    }
    ul li {
      list-style-type: none;
    }
    header {
      position: relative;
      top: 0;
      overflow: hidden;
      width: 100%;
      height: 90%;
      min-height: 850px;
    }
    video {
      height: 760.4375px;
      width: 100%;
      z-index: -1;
      position: absolute;
      top: 0;
      left: 0;
      -webkit-transform: scaley(1.72);
      -o-transform: scaley(1.72);
      -ms-transform: scaley(1.72);
      -moz-transform: scaley(1.72);
      transform: scaley(1.72);
      z-index: -2;
    }
    #bg-video {
      position: absolute;
      top: 0;
      left: 0;
      width: 100%;
      height: 100%;
      background-image: url(../images/overlay.png);
      z-index: -1
    }
    .texto-header {
      position: absolute;
      top: 30%;
      left: 50%;
      margin-left: -280px;
      width: 600px;
      text-align: center;
      z-index: 2;
      color: #FFF;
    }
    .texto-header h1 {
      font-family: 'Dancing Script', cursive;
      font-size: 3.5em;
    }
    .texto-header p {
      /*font-family: 'Scada', sans-serif;*/
      font-family: 'Source Sans Pro', sans-serif;
      font-size: 1em;
      line-height: 20px;
    }
    .texto-header button {
      color: #fff;
      background: transparent;
      border: 2px solid #fff;
      width: 220px;
      height: 50px;
      font-family: 'Source Sans Pro', sans-serif;
      font-size: 1.2em;
      border-radius: 5px;
      margin-top: 5%;
    }
    .texto-header button:hover {
      color: #000;
      background-color: #fff;
    }
    .menu-header {
      margin-top: 0px;
      position: absolute;
      top: auto;
      bottom: 0px;
      background-color: #fff;
      /*border-bottom: 5px solid #000;*/
      box-shadow: 0 4px 8px -1px #d7d7d7;
      width: 100%;
      height: 80px;
    }
    .menu {
      margin: 30px auto;
      text-align: center;
    }
    .menu li {
      display: inline;
    }
    .menu li a {
      margin: 15px;
      color: #000;
      font-family: 'Source Sans Pro', sans-serif;
      font-size: 1.1em;
      transition: 0.3s;
    }
    .menu li a:hover {
      font-weight: bold;
      transition: 0.3s;
    }
    .fixar {
      z-index: 9999;
      position: fixed;
      left: 0;
      top: 0;
      width: 100%;
    }
    /********************************************************************************

                                    CORPO-1

*********************************************************************************/
    .barra {
      border: none;
      width: 25%;
      height: 2px;
      background-color: #000;
      margin-top: 2%;
    }
    .corpo-1 {
      margin-top: 10%;
      text-align: center;
      font-family: 'Source Sans Pro', sans-serif;
    }
    .corpo-1 > h1 {
      font-size: 1.5em;
      font-weight: bold;
    }
    .tamanho {
      -webkit-transform: scale(0.6);
      -o-transform: scale(0.6);
      -ms-transform: scale(0.6);
      -moz-transform: scale(0.6);
      transform: scale(0.6);
      border: 5px solid #000;
      border-radius: 50%;
      padding: 10px;
    }
    .info h1 {
      margin-top: -3%;
      font-size: 1.5em;
    }
    .info p {
      line-height: 7px;
    }
    .info {
      text-align: center;
      margin-top: 5%;
    }
    .info li {
      display: inline;
      float: left;
      width: 33%;
      height: 380px;
    }
    #btn-info {
      margin-top: 7%;
      text-align: center;
      clear: both;
      background-color: transparent;
      border: 2px solid #000;
      width: 220px;
      height: 50px;
      font-family: 'Source Sans Pro', sans-serif;
      font-size: 1.1em;
      border-radius: 5px;
    }
    #btn-info:hover {
      background-color: #000;
      color: #fff;
    }
<!doctype html>

  <meta charset="utf-8">
  <title>Nova Era Team</title>
  <meta http-equiv="content-type" content="text/html; charset=utf-8" />
  <meta name="description" content="" />
  <meta name="keywords" content="" />

  <link rel="stylesheet" href="css/style-home.css" />
  <link rel="stylesheet" href="css/reset.css">

      <video id="Video1" class="bgvid" loop muted>
        <source src="video/animacao-lol.mp4" type="video/mp4" />desculpe mais seu navegador não suporta este formato ou esta desatualizado :(
      </video>

Olá amigos somos a Tec Mov !

dolor sit amet, consectetur adipiscing elit. Sed at risus neque.

Cras sit amet ligula ut justo commodo porta id ut enim. Nulla est lectus, mollis sit amet vehicula id, volutpat eget mauris.

      <button>Vamos Começar ?</button>

Home

Sobre

Galeria

Eventos

Equipe

Contato

Quando precisar de algo

                 conte conosco para...

Adipiscing a commodo ante nunc accumsan interdum mi ante adipiscing. A nunc lobortis non nisl amet vis volutpat aclacus nascetur ac non.

Lorem curae eu ante amet sapien in tempus ac. Adipiscing id accumsan adipiscing ipsum.

Filmagem

Lorem ipsum dolor sit amet, consectetuer elit.

Vestibulum at purus sed erat suscipit.

Cras facilisis viverra wisi. Class sociosqu...

Fotografias

Lorem ipsum dolor sit amet, consectetuer elit.

Vestibulum at purus sed erat suscipit.

Cras facilisis viverra wisi. Class sociosqu...

Preços justos

Lorem ipsum dolor sit amet, consectetuer elit.

Vestibulum at purus sed erat suscipit.

Cras facilisis viverra wisi. Class sociosqu...

      <button id="btn-info">Conheça mais sobre nós...</button>

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

teste

Comment: Você já verificou se realmente está adicionando a classe: "fixar"?
Comment: Você importou o jQuery?
Comment: como assim porque eu coloquei ela no meu css e dei um addClass nao deveria ir ?
Comment: Você fez um "if" se cair dentro da condição do if que é pra adicionar, você debugou pra verificar se realmente está caindo no if e está adicionando a classe.
Comment: entao amigo mais como eu posso debugar um html tipo eu nem sabia que dava pois eu ja fiz um projeto html em uma ide e mesmo nela nao consegui debugar
Comment: Caro amigo você vai debugar no console do seu navegador, dentro do seu "if" logo acima de onde você adiciona a classe coloque um console.log('caiu no if'); e essa mensagem vai ser exibida no console do seu navegador!
Comment: fiz aqui amigo e nao apareceu nada
Comment: aparece esse erro : Uncaught ReferenceError: $ is not defined
Comment: nao a unica coisa que tem de jquery no meu código e isso que eu postei e mais nada
Comment: Coloque isso no seu
Comment: coloquei amigo e nao funcionou :
Comment: Aparece o mesmo erro no console?
Comment: GET file:///C:/Users/felipe.silva/Desktop/prototipo/tecmov/ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js net::ERR_FILE_NOT_FOUND
index.html:15 Uncaught ReferenceError: $ is not definedindex.html:15 (anonymous function)
Comment: @Kirito Eu ja respondi sua duvida a 30 minutos atras, você viu?
Comment: @Kirito coloque isso em seu código  , o Jquery precisa SEMPRE ser a primeira importação, antes dos css e de qualquer outro JavaScript, não é uma regra, mas ameniza e muito esse tipo de problema.
Answer: Mudei seu código.
Troque seu JS para:
var nav = $('.menu-header');
var num = $('.menu-header').offset().top;

$(window).bind('scroll', function() {
     if ($(window).scrollTop() > num) {
         nav.addClass('fixar');
     }
     else {
         num = $('#outermainmenu').offset().top;
         nav.removeClass('fixar');
     }
});

Nessas duas linhas abaixo eu pego seu elemento e pego a posição do mesmo. O menu.
var nav = $('.menu-header');
var num = $('.menu-header').offset().top;

Depois nas linhas abaixo eu verifico se na rolagem da página chegou no topo do MENU. Se sim, aplica a classe para fixar o menu no topo.
Além disso no seu CSS, coloquei um width:100% na class .fixar.
OBS: E não esqueça de importar o jQuery. Percebi nos comentários que você não fez isso. Use o LINK que os outros membros te passaram.
Comment: obrigadoooooo vc e "foda"
Comment: seria esse o arquivo que teria que importar
Comment: Exatamente. Coloque ele antes de fechar a TAG `body`. E coloque seu código JS num arquivo separado e importe também abaixo dessa linha. Ou coloque o código abaixo dessa linha.
Answer: Acho que sua resposta esta neste link aqui, mas de qualquer forma observe o ".fixar"
    .fixar {
    position:fixed;
    margin-top: 0px !important;
}

Como fixar um "menu horizontal" no topo da janela ao rolar a página?
Exemplo funcional:
ou apenas importe o jquery em seu código:
Comment: vi sim roberto e agradeço ainda sim li os outros exemplo que tu me mandou e nao funcionou
Comment: Se você utilizar o framework Bootstrap não tera este problemão todo, ou importe o jquery para o seu codigo de forma correta:  ''
Comment: @Paulo Roberto da Silva entao amigo vou editar meu post ´para v er como esta meu código atualmente
Comment: @Kirito coloque seu código HTML e CSS completos ai para Eu fazer um teste aqui.
Comment: ta ai amigo olha ficou meio bagunçado ai mais na minha tela ta tudo arrumandinho depois irei usar media queries mais enfim nao sei se eu to errando em algo
Comment: e so exibir la o meu trocho do codigo que acabei de postar
Comment: @Kirito o Diego Souza ja resolveu o seu problema, marque como resposta se der certo para você e vote nas demais respostas que lhe ajudaram.

menu não fixa ao rolar a pagina


Discard unsaved changes to view in D8

Question: I made a bunch of changes to a D8 view and have not saved it yet. I decided I don't want to go through with these changes and I want to discard all unsaved changes. How do I do this?
Comment: Click Cancel instead of Save.
Comment: @Kevin OMG. Navigating away doesnt work but [Cancel] does. No wonder why googling the problem yielded no results. It was right in front of my face. Post it as an answer and ill mark it.
Comment: Drupal 7 or Drupal 8?
Comment: Have you tried going 'Back to site'?
Comment: @AjayReddy D8. I updated the question to include version.
Comment: @Sheedo, yes. I tried that. Unfortunately, the changes are still persisted but not "saved."
Comment: Click cancel button next to save
Answer: You simply need to click on the Cancel button nearby the Save button

Discard unsaved changes to view in D8


F5 works, CTRL + F5 doesnt...?

Question: I have a simple solution with a windows client and a website. The website exposes a web service that the windows client consumes. So far so good. Here's the weird part. When running my solution in VS, the call to the web service doesn't work when I hit CTRL F5 unless I run it with a simple F5 first. So each time I open the solution in a new VS session, I have to run it in debug (F5) at least once before it works without debugging (CTRL F5).
This makes no sense to me. Has anyone else run into an issue like this? Any ideas would be greatly appreciated!
Thanks!
Ian
Comment: Define 'doesn't work'. Does it raise an exception? Is the return value unexpected? Doesn't it run at all? What (doesn't) happens?
Comment: I would recommend changing your post title.  Something like "Visual Studio Debugging webservices" or something like that.
Answer: For your webservice (which i assume is in its own project), do you have it set to use the local Web Development Server or IIS?  This can be found in the project properties.
It sounds like you are using a Web Development Server (called Casini) and that does not start up until you run it with debug.  Does a little icon appear in the system tray when  you do that?  It should.  That shows that a webserver is now running and the webservice can be accessed by your client app.
The client app project is probably set as you startup project.  You can also set the solution to have multiple startup projects.  By doing this, you ensure that both projects start when debugging (which is what you want in your example).  You can set this by right clicking o the solution, go to properties, and then to Common Properties - Startup Project.  In there, choose "multiple startup proejcts" radio button and select both projects to start.  This will also ensure that Visual studio attaches to both running processes which is required for debugging.
The instructions assume you are using VS2008.  Hope this helps!

F5 works, CTRL + F5 doesnt...?


Random Forest creating normal distribution out of not normal data

Question: Im experiementing with machine learning and my target vairable has a distribution shown below

Not your standard normal distribution. When I train a random forest model on it the predictions from the model follows the below distribution

which is not the same sort of distribution at all. I was under the impression that random forest models are robust to having data which isnt normally distributed? Is it because my training dataa doesnt have enough representation in the extremes? Any thoughts how I can correct this would be great
Answer: The point of a machine learning model isn't to output the same distribution, it's to minimize prediction error. Of course, if the prediction error is zero for every input, then the input and output distributions will be the same, but this reasoning doesn't work the other way around. Discrepancy in input and output distribution just implies that the model is imperfect; the degree of mismatch might characterize some amount of model misfit, but that's best measured by the usual statistics such as mean squared error, etc.
If the prediction error of this model isn't small enough for your needs, then you'll need to do some combination of make a better model, collect more data, or gather more informative features.
Answer: Prediction models aim to answer questions about conditional distributions, (P(y|X)), not about marginal distributions (P(y)).  As others have posted before just looking at marginal distribution of predicted and true data is not sufficient to say anything about the quality of a model. As a simple toy example consider random sampling from the target distribution as a 'model' -- then the marginal plots will almost perfectly match, yet your model is only doing random predictions.
FWIW the distribution of marginal labels suggests there are 2-3 groups of observations, characterized by your features hopefully, that make up the marginal distributions you observe.  This comes from the fact of 2-3 bumps in what looks like a mixture distribution of $P(y) = \sum_{j=1}^{J} P(y | S=s_j) \cdot P(S = s_j)$, where $S$ is some hidden state.  Ideally your features map to those states, i.e., $P(S | X)$ is not independent.
Answer: Random forests are robust to having data which isn't normally distributed but that doesn't mean that the predictions won't be pulled to the natural center of your data to minimize the rmse.
Looks like your features may not be good enough to partition the data to follow the real distribution so you should look at getting better features or doing some feature engineering.
Edit to add some more thoughts:
It does look like your target is made of a mixture distribution which can be visibly seen.  So you may want to look into separating the two distributions and look for any correlations, may reveal some useful insights that you may not be accounting for in the model.


Specifying a beta prior distribution

Question: I need help trying to understand how values can be used in a beta distribution to represent priors/posterior probabilities. I'm aware that there are similar questions that have already been asked about beta distribution, but they don't really ask what I'm having trouble with.
In the following example we have:
p = a prior
D: Some data, with 16/20 success
and two parameters , (1.1,1.3).
I know that using R we can plot the data:
p <- seq(from = 0, to = 1 , len = 10)
plot(p,dbeta(p,1.1,1.3)

What I'm having trouble understanding is how the parameters relate to the rest of the information?
Do the parameters represent the prior probabilities, and if so, in order to find the posterior probability, could i just use the Bayes theorem?
Would I need to make an opinionated guess for the priors in order to find the posterior probabilities, or is that what the two parameters represent in this case?
Answer: The beta distribution has pdf
$$p(\theta \,|\, a, b) \propto \theta^{(a-1)} (1 - \theta)^{(b - 1)}$$
The beta distribution can be used to describe prior beliefs about a proportion, $\theta$.
You can think of $a$ (called shape1 in dbeta()) and $b$ (called shape2 in dbeta()) in the prior as if they were previously observed data, in which there were $a$ successes and $b$ failures in a total of $a + b$ experiments.
For example, a $\text{Beta}(16, 4)$ prior corresponds to having 16 successes and 4 failures in previously observed data. The $\text{Beta}(16, 4)$ distribution is depicted below. The $\text{Beta}(16, 4)$ distribution is peaked at $0.8$ ($=16 / 20$), but values between $0.6$ and $1$ are also probable.

Specifying a beta prior distribution


How do I create a function that takes binary as input and generates certain Cartesian coordinates based on the binary value and index?

Question: Given an input such as 00111011, I would like to generate a set of Cartesian coordinates such as:
$$\{(0, 2), (1, 2), (2, 2), (3, 2), (4, 3), (5, 3)\}$$

I can easily write a computer program that does it, but I was curious if it's possible to write a mathematical function that does the same thing.
Sadly, I don't even know where to begin with this one.
Maybe something like this:
Let $B$ be a binary string such as 001111011. Let $i \in \mathbb{Z}$. Let $B_i$ represent the value of the string at index $i$.  We want to define a function $f:B\to\mathbb{N}\times \mathbb{N}$.
Not sure how to proceed from here. Any ideas?
Comment: $x_i = \sum\limits_{j<i} B_j$ and $y_i = i - x_i$.
Answer: Suppose our sequence is $B_1,B_2,\ldots$. Then $f:\mathbb{N}\to\mathbb{N}^2$ is only defined for $i$ when $B_i=1$. When $B_i$ is equal to $1$, note that the $x$-value is just the number of $1$s before it -- that is, $\sum\limits_{j<i}B_j$, and the $y$-value is just $i-x$-value (as achille hui mentioned in comments).
Therefore, for any $n$ such that $B_n=1, f(n)=\left(\sum\limits_{j<i}B_j,\,\,i-\sum\limits_{j<i}B_j\right)$, and your set of coordinates is just the range of $f$.


JSON property of Enum type does not like `null` check

Question: In my Angular application, I have a very simple enum named AlertType. I also have an API response object and one of its properties is of this enum type. Like below:
export class ScanAlertModel {
    public alertId: string;
    public alertType: AlertType
}

I have certain scenarios in which this alertType property is not set. I am attempting to test those using Jasmine. In my Angular application, to be able to filter an Array<AlertModel> for alert that do not have an alerttype attached to them, I am simply able to apply a filter like below:
this.scanAlerts.filter((a) => ((a.alertType === null)
This works ok. But, my tests that attempt to test this filtering (as part of a bigger functional test) fail to filter out records correctly, when my JSON contains ScanAlertModel entities that do not have alertType at all.
Clearly, this has confused me. Any help would be appreciated. thanks.
Answer: First, if alertType is sometimes not present, declare it as optional with :?, like so:
export class ScanAlertModel {
    public alertId: string;
    public alertType?: AlertType;
}

The reason your filter doesn't always work is that if the property is not set, it will not be strictly equal to null.
A better check would be to use hasOwnProperty():
this.scanAlerts.filter(alert => !alert.hasOwnProperty('alertType'));


NFS server Windows 2008 - mounting via linux - input/output error help

Question: I want to try mounting a folder with NFS - I set up the NFS sharing on a windows 2008 R2 server, specified hosts in the NFS permissions (by IP address) and mounted via /etc/fstab
it mounts, but when I try to list the folder, I get 'input/output error'
the owner/group on the local mount point look weird too?
drwx------  2 4294967294 4294967294 4096 2011-02-10 19:15 data/
I mounted in /etc/fstab as:
10.0.6.55:/share$ /media/data nfs soft,intr,rsize=8192,wsize=8192
What am I doing wrong?
Answer: The issue was on the Windows Server side and it could not map the unix account to AD.
This blog post+comments led me to the solution.
http://blogs.msdn.com/b/sfu/archive/2007/04/19/mounting-nfs-share-on-nfs-client.aspx
Answer: In the NFS settings in windows NFS Share settings, checking allow Unmapped users access radio box allows it to work.
Answer: UID/GID mapping can be messed up, but you could try and chown the mount to yourself
Comment: can you post how you configured the NFS in windows? especially the NFS share screenshots
Comment: tried mounting with a specific gid/uid, didnt work.  any other ideas?
Comment: I meant mount as root, and then chown the mount to root
Comment: tried that no luck same issue.


cant send using postfix from external ip address

Question: i have postfix set up as a satellite to listen on port 587
i can send email outside fine trough the postfix(ubuntu) box from the local network with no problems
when i try to connect to the postfix(ubuntu) box from a external ip and send mail
it spits back a 554 5.7.1 Relay access denied error
i can telnet to it fine, just cant send mail
this is my main.cf :
smtpd_banner = $myhostname ESMTP $mail_name (Ubuntu)
biff = no
append_dot_mydomain = no
readme_directory = no

smtp_sasl_auth_enable = yes
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtp_sasl_security_options =
smtp_use_tls = no

myhostname = cotiso-desktop
alias_maps = hash:/etc/aliases
alias_database = hash:/etc/aliases
myorigin = /etc/mailname
mydestination = mydomainname.com, cotiso-desktop, localhost.localdomain, localhost
relayhost = smtp.mydomainname.com
mailbox_size_limit = 0
recipient_delimiter = +
inet_interfaces = all
inet_protocols = all

there is no security set up yet, i'm just trying to get it working first
any ideas?
thanks in advance
thanks pQd
i tried with a fixed external ip and it works, but i would like to let more people use it regardless of whether they're connected from, do i have to install something else in order to get it to work?
Comment: Small comment: this is one area where 'get it working first, add security later' is dangerous: you may become an open relay. You will need to add the right commands to log in to your telnet session.
Answer: If your external clients don't have fixed IPs you'll have to autheticate them somehow. Have a look at this: http://www.postfix.org/SASL_README.html
Answer: is external ip fixed? if so add it in main.cnf as below:
mynetworks=127.0.0.0/8, 18.104.22.168/32

Answer: To enable particular user related with username (not ip address, if user uses dhcp)
smtpd_recipient_restrictions = check_sender_access hash:/etc/postfix/maps/access-allowed-outside-senders, reject_unknown_recipient_domain, reject_non_fqdn_recipient, reject_unauth_pipelining, permit_mynetworks, reject_unauth_destination, reject
/etc/postfix/maps/access-allowed-outside-senders: firstname.lastname@example.com OK
This way, email@example.com is allowed to send mail outside of your domain, even if he is outside of your network.


Limit of Inner Products in Hilbert Space

Question: Let $H$ be an infinite dimensional Hilbert space. Then there exists an orthonormal basis $\{e_{i}\}_{i = 1}^{\infty}$. Suppose we know that $\lim_{k \rightarrow \infty}(f_{k}, e_{j}) = (f, e_{j})$ for each $j$ where $\{f_{k}\}$ are such that $\|f_{k}\| = B$ and $f$ some function in $H$. Why is it that $\lim_{k \rightarrow \infty}(f_{k}, g) = (f, g)$ for every $g \in H$?
Comment: Fix an $\epsilon$. Finite sums of basis vectors can approximate $g$ to any precision, that is, there exists $\{g_{n}\}_{n = 1}^{\infty}$ and an $N$ such that $\|g_{N} - g\| < \epsilon$. Then $\lim_{k \rightarrow \infty}(f_{k}, g_{N}) = (f, g_{N})$. We also have have that $|(f_{k}, g_{N} - g)| \leq \|f_{k}\|\|g_{N} - g\| < B\epsilon$. Therefore $\lim_{k \rightarrow \infty}(f_{k}, g_{N}) = \lim_{k \rightarrow \infty}(f_{k}, g)$. Then $$(f, g_{N}) = \lim_{k \rightarrow \infty}(f_{k}, g_{N}) = \lim_{k \rightarrow \infty}(f_{k}, g).$$ Is this the right track?
Comment: @Sam: no, every Hilbert space has an orthonormal basis, whether finite or infinite-dimensional, and whether separable or not. Of course, what is true is that the OP wrote a countable basis, and that is equivalent with the space being separable.
Comment: @QPT: yes, that's what I did in some more detail in my answer.
Comment: @Martin: gah, sorry I omitted the countable detail
Answer: Write $g=\sum_j\alpha_je_j$. Fix $\varepsilon>0$. Then there exists $j_0$ such that $\|\sum_{j>j_0}\alpha_je_j\|<\varepsilon$. Note that $g-\sum_{j\leq j_0}\alpha_je_j=\sum_{j>j_0}\alpha_je_j$.
\begin{align}
|(f_k-f,g)|&=|(f_k-f,\sum_{j\leq j_0}\alpha_je_j)+(f_k-f,\sum_{j>j_0}\alpha_je_j)| \\ \ \\
&\leq|(f_k-f,\sum_{j\leq j_0}\alpha_je_j)|+|(f_k-f,\sum_{j>j_0}\alpha_je_j)|\\ \ \\
&\leq|(f_k-f,\sum_{j\leq j_0}\alpha_je_j)|+\|f_k-f\|\,\|\sum_{j>j_0}\alpha_je_j\|\\ \ \\
&\leq|(f_k-f,\sum_{j\leq j_0}\alpha_je_j)|+(B+\|f\|)\,\varepsilon\\ \ \\
&\leq\sum_{j\leq j_0}|\alpha_j|\,|(f_k-f,e_j)|+(B+\|f\|)\,\varepsilon
\end{align}
Taking $\limsup_{k\to\infty}$, we get (notice that the sum on the right is finite)
$$
\limsup_{k\to\infty}|(f_k-f,g)|\leq(B+\|f\|)\,\varepsilon.
$$
As $\varepsilon$ was arbitrary, we conclude that the limit exists and is zero, i.e.
$$
\lim_{k\to\infty}(f_k-f,g)=0.
$$
By the way, we are only using that $\|f_k\|\leq B$ (not equality). Also there's no requirement that the space be infinite-dimensional or separable, i.e. it works for any Hilbert space.
Comment: Is separability not to ensure that we actually have a countable orthonormal basis?
Comment: Yes, if for some reason you need a countable basis. Not the case here.
Answer: Suppose $g$ is such that $\lim\limits_{k\rightarrow\infty} (f_k,g)\ne(f,g)$. Then, without loss of generality, we may assume that $\Vert g\Vert=1$ and that there is an $\alpha>0$ such that for some  subsequence of $(f_n)$, say $f_{n_k}$ we have $ (  f_{n_k}-f , g   )\ge \alpha$ for all $k$.
Let $\epsilon>0$. Write $g=\sum\limits_{i=1}^\infty \alpha_i e_i$ and choose $M$ so large that $g_c=\sum\limits_{i=M+1}^\infty \alpha_i e_i$ has norm less than $\epsilon$.  Then for each $k$
$$\eqalign{
\alpha\le  (\,f_{n_k}-f, g\, ) &= \sum_{i=1}^M\alpha_i  ( f_{n_k}-f, e_i ) + ( f_{n_k}-f , g_c ).\cr
 }
$$
Select $K$ so large that  $\sum\limits_{i=1}^M\alpha_i (f_{n_K}-f,e_i) \le \alpha/2$.
Then we have
$$
\alpha/2\le  ( f_{n_K}-f , g_c).
$$
This implies the norm of $f_{n_K}-f$ is at least $\alpha/(2\epsilon)$.
But, as  $\epsilon$ was arbitrary, this contradicts the bound on the norms of the $f_k$.


AOP not invoked by annotation

Question: I am trying to invoke a AOP method for every method that is annotated with @Timed.
My AOP MyTracer.java
@Aspect
public class MyTracer {

  private static final Tracer tracer = Tracing.getTracer();
  private static final Logger log = Logger.getLogger(MyTracer.class.getName());

  @Around("@annotation(timed)")
  public Object trackExecutionTime(ProceedingJoinPoint proceedingJoinPoint, Timed timed) throws Throwable {
    String methodName = proceedingJoinPoint.getSignature().getName();
    log.info("Using AOP for method name" + methodName);
    log.info("Using AOP for param name" + timed.label());
    return output;
    }
  }
}

My Annotation
Timed.java
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface Timed {
  String label() default "label";
}

Finally my business code
HelloWorld.java
  @Override
  @Timed(label = "myMetrics")
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
    log.info("Servlet called");
    PrintWriter out = resp.getWriter();
    out.println("Hello, world - Flex Servlet");
  }

At runtime, I am getting logs from the servlets but not the MyTracer class.
Answer: Ok, I figured it out. The build.gradle was missing the following. I replaced
compile group: 'org.aspectj', name: 'aspectjtools', version: '1.6.2'

with
buildscript {
  repositories {
    maven {
      url "https://plugins.gradle.org/m2/"
    }
  }
  dependencies {
    classpath "gradle.plugin.aspectj:gradle-aspectj:0.1.6"
  }
}

project.ext {
  aspectjVersion = "1.8.2"
}

apply plugin: "aspectj.gradle"

Comment: you can mark it as an answer if it solved your problem

AOP not invoked by annotation


Taylor's series when x goes to infinity

Question: Let $f(x) = \frac {x^3}{(x+1)^2}$. Find constants a, b, c, so that $f(x) = ax + b + \frac cx +  o(\frac 1x)$ as $x$ goes to $\pm \infty$. So i know that i can't take Taylor series as $x$ goes to infinity. So i am assuming i have to make some kind of substitution. I tried making $x = \frac 1u$ but i get nowhere.
$$f(x) = \frac {x^3}{(x+1)^2} = x^3(x+1)^{-2}=\frac{1}{u^3}(1 + \frac 1u)$$
$$\lim_{u\to 0}\frac{1}{u^3}(1 + \frac 1u) = \lim_{u\to 0}\frac{1}{u^3}(1 - \frac 2u  + \frac{3}{u^2} + o({u^3})) =\lim_{u\to 0} u^3 - \frac {2}{u^4} + \frac{3}{u^5} + o(\frac 1u)    = \lim_{u\to 0} \frac{1}{x^3} - 2x^4 + 3x^5 + o(x^5)$$
Thanks.
Comment: You lost somewhere power -2. You can do this using long division too (dividing x^3 by x^2 + 2 x + 1).
Comment: Technically this is not a Taylor's series, as it contains terms like $\frac{1}{x}$, when Taylor's series all terms must be polynomial.
Answer: Here is how you approach the problem. Put $x=\frac{1}{t}$ and then find the Laurent series at the point $t=0$
$$ f(x) = \frac {(1/t)^3}{(1/t+1)^2}=\frac{1}{t(1+t)^2} ={t}^{-1}-2+3\,t-4\,{t}^{2}+5\,{t}^{3}+ ( {t}^{4}) .$$
Now, substitute $t=1/x$ in the above expansion. See related problem.
Note: Note that, you only need to find the Taylor series of $\frac{1}{(1+t)^2}$ at $t=0$, since
$$ \frac{1}{t(1+t)^2}= \frac{1}{t} \frac{1}{(1+t)^2} .$$
Comment: I have all ready used binomial theorem, as you can see in original post but when i plug in $\frac 1x$ i cant get what is required from  me.
Comment: @GovernmentFX: I am going to add some materials.
Answer: I would start off here by using long division to simplify things a bit:
$$
\frac{x^3}{(x+1)^2}=\frac{x^3}{x^2+2x+1}=\cdots=x-2+\frac{3x+2}{x^2+2x+1}.
$$
Heuristically speaking, it is clear that as $x\rightarrow\infty$, that last bit is $\frac{3}{x}+o(\frac{1}{x})$.  So, this would suggested that
$$
\frac{x^3}{(x+1)^2}=x-2+\frac{3}{x}+o\left(\frac{1}{x}\right)\text{ as }x\to\infty.
$$
Having used long division / heuristics to find the answer, now it is only a matter of justifying it; and, that shouldn't be too bad.

Taylor's series when x goes to infinity


VBA Macro based on a specified column named "Carrier" creates or split the column values into a new workbook

Question: I am very new to VBA Macro, I am trying to create a macro that split data based on a specific column and creates a new workbook for each column values.
Below is my code which gives a lot of errors I am confused to deal with it... the below code is too lengthy is there any way possible to short main is the proper output
Sub ExportData()

'Declare variables
Dim ArrayItem As Long
Dim ws As Worksheet
Dim ArrayOfUniqueValues As Variant
Dim SavePath As String
Dim ColumnHeadingInt As Long
Dim ColumnHeadingStr As String
Dim rng As Range

'Set the worksheet to
Set ws = Sheets("POL")

'Set the save path for the files created
SavePath = "C:\Folder"

'Set variables for the column we want to separate data based on
ColumnHeadingInt = ActiveWorkbook.Worksheets("POL").Match(Range("Carrier").Value, Range("POL[#Headers]"), 0)
ColumnHeadingStr = "POL[[#All],[" & Range("Carrier").Value & "]]"

'Turn off screen updating to save runtime
Application.ScreenUpdating = False

'Create a temporary list of unique values from the column we want to
'separate our data based on
Range(ColumnHeadingStr & "").AdvancedFilter Action:=xlFilterCopy, _
    CopyToRange:=Range("UniqueValues"), Unique:=True

'Sort our temporary list of unique values
ws.Range("UniqueValues").EntireColumn.Sort Key1:=ws.Range("UniqueValues").Offset(1, 0), _
    Order1:=xlAscending, Header:=xlYes, OrderCustom:=1, MatchCase:=False, _
    Orientation:=xlTopToBottom, DataOption1:=xlSortNormal

'Add unique field values into an array
'ArrayOfUniqueValues = Application.WorksheetFunction.Transpose(ws.Range("IV2:IV" & Rows.Count).SpecialCells(xlCellTypeConstants))
ArrayOfUniqueValues = Application.WorksheetFunction.Transpose(ws.Range("UniqueValues").EntireColumn.SpecialCells(xlCellTypeConstants))

'Delete the temporary values
ws.Range("UniqueValues").EntireColumn.Clear

'Loop through our array of unique field values, copy paste into new workbooks and save
For ArrayItem = 1 To UBound(ArrayOfUniqueValues)
    ws.ListObjects("POL").Range.AutoFilter Field:=ColumnHeadingInt, Criteria1:=ArrayOfUniqueValues(ArrayItem)
    ws.Range("POL[#All]").SpecialCells(xlCellTypeVisible).Copy
    Workbooks.Add
    Range("A1").PasteSpecial xlPasteAll
    ActiveWorkbook.SaveAs SavePath & ArrayOfUniqueValues(ArrayItem) & Format(Now(), " YYYY-MM-DD ") & ".xlsx", 51
    ActiveWorkbook.Close False
    ws.ListObjects("POL").Range.AutoFilter Field:=ColumnHeadingInt
Next ArrayItem

ws.AutoFilterMode = False
MsgBox "Finished exporting!"
Application.ScreenUpdating = True

End Sub

Border got added to all the empty cells also
I coded like this
'Autofit

                Sheets("POL").UsedRange.Columns.AutoFit

                'Sorting the range to compact the data.
                With .Parent.Sort
                    .SortFields.Clear
                    .SortFields.Add Key:=RngRange02.Columns(DblCarrierColumnRelativeColumn), _
                                    SortOn:=xlSortOnValues, _
                                    Order:=xlAscending, _
                                    DataOption:=xlSortNormal
                    .SetRange RngRange02
                    .Header = xlYes
                    .MatchCase = False
                    .Orientation = xlTopToBottom
                    .SortMethod = xlPinYin
                    .Apply
                End With

                'Apply Border

                With Sheets("POL").UsedRange.Borders
                  .LineStyle = xlContinuous
                   .Weight = xlThin
                   .ColorIndex = xlAutomatic
                 End With

I have added 3 more set that changes the sheetname and autofits the column in all excel sheet. All it is working but the problem is with the border which is applying to the empty cells also
Comment: Which error do you get and in which line? Please [edit] your question to include that information.
Comment: First I got an error on line "SavePath = "C:\Folder"  then I checked the path and did changes "SavePath = "C:\Folder" like this then now I am getting an error on line "ColumnHeadingInt = ActiveWorkbook.Worksheets("POL").Match(Range("Carrier").Value, Range("POL[#Headers]"), 0)"  stating object not found error code I saw was 91 ... Since I am new to VBA Macro it is getting more comicated for me so sought it out.
Comment: Your SavePath is missing and end backslash. It won't solve your problem, but it should give you another one if you don't correct it.
Comment: I recommend not to use `.Activate` and to `ActiveWorkbook` where ever possible. Also for **every** of your range objects should be specified in which workbook and worksheet they are eg `ws.Range` or `ThisWorkbook.Worksheets("Sheet1").Range`. If you just write `Range` Excel cannot reliably tell which workbook and worksheet you mean this range to be in, so be as specific as possible and this will prevent a lot of trouble already. Give it a try and update your code in the question if you still get errors.
Comment: Worksheets("POL").Match does not exist. Use Excel.Worksheetfunction.Match and fill it accordingly.
Comment: Some1 please answer
Comment: Did you try the suggestions from the comments? If yes please update the code in your question. Note that we can assist you to fix your issues but the one who needs to do it is actually you. We showed up 3 issues that need to be fixed.
Comment: everything thing tried nothing worked
Comment: Some 1 please help
Comment: Be patient Jay. I've already wrote down some code that might help you. Still not ready though. And i've also other things to do that actually pay my bills. :)
Answer: Try this:
Sub ExportAndSave()

    'Declarations.
    Dim RngSourceData As Range
    Dim RngTarget As Range
    Dim RngRange01 As Range
    Dim RngRange02 As Range
    Dim StrCarrierColumnHeader As String
    Dim StrSavePath As String
    Dim StrMultipleFileMessage As String
    Dim DblCarrierColumnRelativeColumn As Double
    Dim DblCounter01 As Double
    Dim DblCounter02 As Double
    Dim WkbSource As Workbook
    Dim WkbTarget As Workbook

    'Turning off screen updating.
    Application.ScreenUpdating = False

    'Setting variables.
    Set WkbSource = ActiveWorkbook
    Set RngSourceData = WkbSource.Sheets("POL").Range("I1:J6")
    StrCarrierColumnHeader = "Carrier"
    StrSavePath = "C:\Folder\"

    'Setting DblCarrierColumnRelativeColumn to determine what column within RngSourceData _
    contains the StrCarrierColumnHeader. If no such column is found, the subroutine is terminated.
    On Error Resume Next
    DblCarrierColumnRelativeColumn = Excel.WorksheetFunction.Match(StrCarrierColumnHeader, RngSourceData.Rows(1), 0)
    If Err <> 0 Then
        MsgBox "The range " & RngSourceData.Rows(1).Address(False, False) & " contains no column headed " & StrCarrierColumnHeader & ". The subroutine is terminated", vbCritical, "Error"
        Application.ScreenUpdating = True
        Exit Sub
    End If
    On Error GoTo 0

    'Setting RngRange01 to cover the data in the carrier column.
    Set RngRange01 = RngSourceData.Columns(DblCarrierColumnRelativeColumn).Resize(RngSourceData.Rows.Count - 1).Offset(1, 0)

    'Covering each cell in RngRange01.
    DblCounter01 = 0
    For Each RngTarget In RngRange01.Cells

        'Checking if the code had already met the carrier of RngTarget.
        If Excel.WorksheetFunction.CountIf(RngSourceData.Parent.Range(RngRange01.Cells(1, 1), RngTarget), RngTarget.Value) = 1 Then

            'Cheking if any file dedicated to the given carrier already exists for today.
            If Dir(StrSavePath & RngTarget.Value & Format(Now(), " YYYY-MM-DD ") & ".xlsx") = "" Then
                'If no such file exists, it is created and saved.
                Set WkbTarget = Workbooks.Add
                WkbTarget.SaveAs StrSavePath & RngTarget.Value & Format(Now(), " YYYY-MM-DD ") & ".xlsx"
            Else
                'Is it does exist, the name is "shifted".
                DblCounter02 = 2
                Do Until Dir(StrSavePath & RngTarget.Value & Format(Now(), " YYYY-MM-DD ") & "(" & DblCounter02 & ")" & ".xlsx") = ""
                    DblCounter02 = DblCounter02 + 1
                Loop
                'Carrier and relative file are copied in StrMultipleFileMessage.
                StrMultipleFileMessage = StrMultipleFileMessage & vbCrLf & RngTarget.Value & " in " & RngTarget.Value & Format(Now(), " YYYY-MM-DD ") & "(" & DblCounter02 & ")" & ".xlsx"
                Set WkbTarget = Workbooks.Add
                WkbTarget.SaveAs StrSavePath & RngTarget.Value & Format(Now(), " YYYY-MM-DD ") & "(" & DblCounter02 & ")" & ".xlsx"
            End If

            'Setting RngRange02 to target the range in the new file where RngSourceData will be copied.
            Set RngRange02 = WkbTarget.Sheets(1).Range("A1").Resize(RngSourceData.Rows.Count, RngSourceData.Columns.Count)

            With RngRange02

                'Copying values.
                RngSourceData.Copy RngRange02

                'Filtering the range to clear the list of unwanted data.
                .AutoFilter Field:=DblCarrierColumnRelativeColumn, Criteria1:="<>" & RngTarget.Value
                .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0).ClearContents
                .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0).ClearFormats

                'Removing the filter.
                .AutoFilter

                'Sorting the range to compact the data.
                With .Parent.Sort
                    .SortFields.Clear
                    .SortFields.Add Key:=RngRange02.Columns(DblCarrierColumnRelativeColumn), _
                                    SortOn:=xlSortOnValues, _
                                    Order:=xlAscending, _
                                    DataOption:=xlSortNormal
                    .SetRange RngRange02
                    .Header = xlYes
                    .MatchCase = False
                    .Orientation = xlTopToBottom
                    .SortMethod = xlPinYin
                    .Apply
                End With

            End With

            'Saving and closing WkbTarget.
            WkbTarget.Close savechanges:=True

        End If

        'Setting DblCounter01.
        DblCounter01 = DblCounter01 + 1
    Next

    'Enabling screen updating.
    Application.ScreenUpdating = True

    'Reporting if any carrier had its data reported in a "twin" file.
    If StrMultipleFileMessage <> "" Then
        StrMultipleFileMessage = "The following carriers had already one or more dedicated files at the given path. Their data were saved accordingly to this list:" & vbCrLf & vbCrLf & StrMultipleFileMessage
        MsgBox StrMultipleFileMessage, , "Multiple dedicated files"
    End If

End Sub

You will probably have to edit the setting of some variables (RngSourceData for sure i'd say).
Comment: Hi, @Evil Blue Monkey appreciate your efforts. However, the output is not in the order I have pasted all the output in the above question with screenshots. Firstly, for a few carries, it creates a temp file in the folder as highlighted above and the output inside the created excel sheet is not the same as what it is in the original sheet. Like in the original sheet the top row and last column are highlighted the split data should be exactly same as what it is in the original sheet. please help
Comment: Ok, the format problem can be solved. In my code i just copied the values, not the formats. Reguarding the temp files: i think it's due to their name. They have points. I'll check if it's possible to make them as xlsx files even if they have points in their name.
Comment: `WkbTarget.SaveAs StrSavePath & RngTarget.Value & Format(Now(), " YYYY-MM-DD ") & "(" & DblCounter02 & ")", 51` is missing the file extension. Just change to `… & "(" & DblCounter02 & ").xlsx", 51`
Comment: Yep, yep. Already done it, thank you. ;) I thought that since 51 was specified, there would have been no need. And i didn't expect any points in the name. I've just put the ".xlsx" and removed the 51 since clearly there is no need for it. Anyway, Jay Sameer: try it now. Any other request?
Comment: Thanks a lot @ Evil Blue Monkey and @Peh it works.... much appreciated. thanks a lot...
Comment: Hi @EvilBlueMonkey the macro is not adding the border in the extracted file I have given a condition after "With condition set"   'Apply Border

                With Sheets("POL").UsedRange.Borders
                  .LineStyle = xlContinuous
                   .Weight = xlThin
                   .ColorIndex = xlAutomatic
                 End With
but this is applying to all employ rows also
Comment: Please see my edits above in the question section... @EvilBlueMonkey
Comment: You are applying it to the UsedRange. Try to better define your range. Maybe `With Sheets("POL").Range(Sheets("POL").Range("A1"), Sheets("POL").Cells(Sheets("POL").Range("A1").End(xlDown).Row, Sheets("POL").Range("A1").End(xlToRight).Column)).Borders`.
Comment: @EvilBlueMonkey Hi it's not working... actually the main POL sheet has border so when a new file is created that border goes off cant we do something for that when it creates new file the data border should be as it is
Comment: This is getting too much out of topic and i am not sure what's your problem now. The code i wrote should copy formats too. You should open another question with the code you are using and explain your problem better.
Comment: Ok @EvilBlueMonkey I will open another question... anyways thanks for the guidance this module is working great


AS3 : how can I store tiled map editor's data efficiently in an AS3 class

Question: Please let me describe my question with details.
Lets say I will create a game with 500 different maps.
Each of these maps are containing 80x40 16px tiles.(unfortunately it's necessary to parse per 16px)
But in game , I'm gonna create 32px tiles per 4 16px tiles.
I store every embedded tmx file in a class with static methods.
Here is my question, which of the following 2 options I should chose;
1- Should I convert the tmx data into as3 data ( into an array which contains tiles' data) each time player enters a different map.
2- Should I convert all maps' data at the beginning of the game, then whenever player enters a different map, I directly take the array and create the map from it.
I am asking this because I'm not sure if it's a problem to keep 500 arrays with the size of 80x40. (would it tire ram too much? )
Answer: Option 1 is better.You can load map config data before you enter a map, and it's not necessary to store all config data in the memory, you can store 10 map config data which are recently used(like LRU cache algorithm).
In my experience, if your map config data is a xml,you can transfer it to a byteArray to reduce its size and decompress when loaded.


Call to 'AnsiReplaceStr' is ambiguous

Question: Após trocar o RAD Studio XE8 para o RAD Studio 10 Seattle obtive o seguinte erro:
[bcc64 Error] Unit1.cpp(425): call to 'AnsiReplaceStr' is ambiguous
System.StrUtils.hpp(51): candidate function
System.AnsiStrings.hpp(82): candidate function

Código original:
UniTable1->FieldByName("chuva")->AsFloat =
                StrToFloat(chuva, ".", ",");

Answer: Resolvi informando a função que estou utilizando AnsiString
Código alterado:
UniTable1->FieldByName("chuva")->AsFloat =
                StrToFloat(AnsiString(chuva), ".", ",");

Call to 'AnsiReplaceStr' is ambiguous


What does the "harmonic" knob do on a software instrument?

Question: In GarageBand I'm using a software instrument called "Screamlead" which has several knobs as follows:

Some of these, like "glide" and "overdrive," remind me of adjustments on synthesizers.  Is "harmonic" also a synthesizer specific adjustment?  Or is does it apply to software instruments more generally?  What exactly does it do?  Can I emulate its effect on a subtractive (or other) synthesizer?
Comment: 'Harmonic' isn't a common name for a synthesizer control, and even knowing what 'harmonics' are doesn't make it obvious exactly what this control does. Is this an instrument that comes with garageband?
Comment: @topomorto yes, this instrument comes with GarageBand.  Your concern is exactly why I'm wondering what it does.  There doesn't appear to be a tooltip or anything that tells me.
Answer: A harmonic is a pitch that is an integer multiple of the fundamental frequency. In other terms: on an acoustic string instrument, when you play a note, say 110 Hz, the string would resonate  mostly at 110 Hz, but it would also have simultaneous resonances at approximately 220, 330, 440Hz and so on, that get progressively weaker. Those simultaneous resonances are harmonics. Here is a graph that somewhat explains it, the x axis is Hz, the y axis amplitude (volume) Now on your softsynth, there are three things that knob could do:

Amplify all harmonics, or some of them. This would make the sound brighter, to put it simply.
Change which harmonics are accentuated. This would change the character of the sound, hard to be any more specific.

Change the pitches of the harmonics. This is unlikely. It would certainly allow for some weird sounds.

I suggest playing with your knob, see what happens to the sound. If necessary, use a spectrometer to figure it out. Or if there is a manual of the thing, maybe that could help.
Answer: Don't worry too much about the labels on this sort of instrument.  The knobs do what your ear tells you they do.  I think we can assume 'Harmonic' boosts high frequencies, 'Depth' low ones.  Am I right?   They aren't standard terms from classic subtractive synthesis, where you basically have a choice of waveforms, a filter and ADSR envelopes to play with.


Como tirar barra de um modal

Question: Olá, como tiro essa barra cinza de cima do modal ??

$(function()
    {
        var dialog, form,
        dialog = $( "#painel_fazer_upload" ).dialog
        ({
          autoOpen: false,
          height: 520,
          width: 500,
          modal: true,
        });

        $( "#painel_upload" ).button().on( "click", function()
        {
          dialog.dialog( "open" );
        });
    });

Comment: Olá @lucas-carezia! Qual o plugin para gerar o modal você esta usando?
Comment: code.jquery.com/jquery-1.10.2.js e code.jquery.com/ui/1.11.4/jquery-ui.js
Answer: É possível fazer a remoção do fundo e da borda cinza do titulo do modal sobrescrevendo o CSS original do jQuery UI da seguinte maneira:
.ui-dialog-titlebar{
    //tira a cor de fundo cinza
    background: transparent;
    //tira a cor da borda
    border: none;
}

Não se esqueça de adicionar estas linhas logo após a inclusão do arquivo de CSS do jQuery UI para que estas regras da classe sejam reescritas.
Outra opção é altera-las direto no arquivo CSS se for possível.
Answer: Deves fazer isso com CSS. A classe que tem essa div é .ui-dialog-titlebar e se usares CSS fica automáticamente invisivel para todos os dialog. Podes fazer assim:
.ui-dialog-titlebar{
  visibility: hidden !important;
}

Exemplo: http://jsfiddle.net/gb7w37de/1/
Se o que queres é mudar a côr podes mudar parametros no CSS como background-color, border, ou específicamente border-color.
Podes também fazer isso com JavaScript/jQuery. Nesse caso algo como $('.ui-dialog-titlebar').css('visibility', 'hidden'); ou aplicar uma classe de CSS.
Exemplo via JavaScript: http://jsfiddle.net/gb7w37de/
Comment: Funcionou bem, eu tenho outra duvida diferente da pergunta, caso eu queira fechar manualmente a janela, qual código devo usar ??
Comment: @LucasCarezia nesse caso podes usar `$( "#painel_fazer_upload" ).dialog('close');`

Como tirar barra de um modal


Is there a way to calculate exponent $n$ in matrix vector product: $w=M^nv$

Question:
Find $n$ for given square matrix $M$ and vectors $v,w$ in $$w=M^nv$$

Trial (updated)
(as vujazzman suggested)
Jordan normal form:
$$ w = (A J^n A^{-1})v$$
$$ A^{-1}w = J^n A^{-1}v$$
After this solve $J_{i,i}^n$ for diagonal elements ($\lambda^n$) not zero or unity.
Problem: In trials with known $n$ no row was equal at left an right side for this equation. (edit: I missed a factor before result)

with numbers:
$$M=\begin{pmatrix} -6 & 0 & 1 & 1 \\  0 & 5 & 1 & 1 \\  1 & 0 & 4 & 0 \\ 1 & 1 & 2 & 3\end{pmatrix} $$
$$v= \begin{pmatrix}1 \\ 3 \\ 4 \\ 7 \end{pmatrix}$$
$$\text{just for testing } n=5$$
$$\rightarrow w=M^5 v = \begin{pmatrix}3069 \\ 39932 \\ 5908 \\ 23189 \end{pmatrix}$$
$$M=AJA^{-1}$$
$$A=\begin{pmatrix} -11.1983 & 0.1078 & 0.3311 & 0.0927 \\  -0.1876 & -0.3812 & -3.9066 & 2.2532 \\  1.0992 & -0.0757 & 2.3579 & 0.0630 \\ 1 & 1 & 1 & 1\end{pmatrix}$$
$$J=\begin{pmatrix} -6.1875 & 0 & 0 & 0 \\  0 & 2.5753 & 0 & 0 \\  0 & 0 & 4.1404 & 0 \\ 0 & 0 & 0 & 5.4718\end{pmatrix}$$
$$A^{-1}=\begin{pmatrix} -0.0878 & -0.0009 & 0.0068 & 0.0096 \\  -0.0099 & -0.3327 & -0.8920 & 0.8068 \\  0.039 & -0.0197 & 0.3788 & 0.0169 \\ 0.0587 & 0.3533 & 0.5064 & 0.1667\end{pmatrix}$$
$$\text{insert in } A^{-1}w = J^n A^{-1}v$$
$$\begin{pmatrix}-39.875883 \\ 121.33529 \\ 1963.52008 \\ 21144.0205 \end{pmatrix}=\begin{pmatrix} -6.1875 & 0 & 0 & 0 \\  0 & 2.5753 & 0 & 0 \\  0 & 0 & 4.1404 & 0 \\ 0 & 0 & 0 & 5.4718\end{pmatrix}^{n=5}\begin{pmatrix}0.0044 \\ 1.0712 \\ 1.6136 \\ 4.3108 \end{pmatrix}$$
now (just for testing) computed with $n=5$
$$\begin{pmatrix}-39.875883 \\ 121.33529 \\ 1963.52008 \\ 21144.0205 \end{pmatrix}=\begin{pmatrix}-39.875883 \\ 121.33529 \\ 1963.52008 \\ 21144.0205 \end{pmatrix} \text{ q.e.d.}$$
Now its working...

To be complete: computing of $n$ if not known
$$21144.0205/4.3108=5.4718^n$$
$$\log_{5.4718}(4904.894799)=\log(4904.894799)/\log(5.4718)=n$$
$$\rightarrow n=5$$
Comment: @vujazzman and is there a correct version? It is only a post about what did not work.
Comment: Can you give a specific example? It's unlcear what the problem is
Answer: Lets first make a weak assumption on $M$, lets suppose it has an eigenvalue $\lambda$ which is not zero or a root of unity. In this case, $n$ can be determined (or determined not to exist), by taking the Jordan normal form of $M = AJA^{-1}$ and considering the resulting equation $A^{-1}w = J^n (A^{-1}v)$. There is a row of $J^n$ consisting of $\lambda^n$ in one entry and the rest zeros. Due to the conditions on $\lambda$, there will be at most one solution for $n$. If there is a solution, check it in the original equation. In this case $n$ is the unique solution. Otherwise, there is no solution.
If $M$ doesn't satisfy the condition, the situation is more complicated, but in any case you still want to first reduce the problem by taking the Jordan decomposition. Enumerating all what can happen is probably still possible, you essentially need to answer the original problem for $M$ a Jordan block with root of unity or zero eigenvalue.
Comment: Did some test case. For known $n$ the equation $J^n(A^{-1}v)-A^{-1}w =0$ vector with size of $M$. In test case that was not the case for any row. $M$ had positive eigenvalues (and some negative).
Comment: The row is the last row of the jordan block for that eigenvalue. If you are taking a random example, for instance, then $M$ is diagonalizable. So you diagonalize and solve the equation for $n$ corresponding to any of the rows.
Comment: After copy all that numbers from example I noticed they are equal. Before I computed the difference from left and right side. I missed the $1e-10$ factor before the result... Thank yo for the answer, sorry for the inconveniences


Deciphering the series of numbers shown for songs in a hymn book

Question: Consider almost any song in a church hymn book. Either at the top just above the ledger lines or at the bottom near the credits is a series of numbers usually a set of four to six numbers such as 87 87 87 or 10 10 10 10 10 or 88 88 88. They are not necessarily all the same number. What do those numbers mean? What part of music theory discusses them?
Answer: The numbers you are referring to are most likely hymn meters.  No, not a scale of how well the hymn was received, or how loud it should be, but actually an indication of the meter of the hymn. (Wikipedia has a good article on hymn meters.) The numbers themselves refer to the meter (number of syllables) of each line.
Thus, 87.87.87 would mean the first line has a phrase of 8 syllables followed by a line of seven syllables.  The second and third lines would be the same.
In theory, one could mix and match the words and musics from all hymns with the same numbers.  Thus, (using the 87.87.87 example), one could sing the words from "Christ Is Made the Sure Foundation" (Latin/Percell, Methodist hymn #559) to the melody from "Angel from the Realms of Glory" (Montgomery/Smart, Hymn #220).
The 10 10 10 10 example is interesting as the 10 stands for 10 syllables, not 1 syllable followed by a strange non-syllabic utterance.  In this case, the meter is 4 lines of 10 syllables each.
BTW, many hymnals actually include an index of Meters (Metrical Index) which lists the meters and gives the hymns that use them.  The index also shows the Hymn Tune (note progressions) that are used.  (For instance, "Angels from the Realms of Glory" and "Easter People, Raise Your Voices" both use 87.87.87 and the Regent Square.)
Comment: Good answer. One note: the "note progression" you talk about is simply called the "hymn tune". There are many well-known hymn tunes used underneath different texts to form different hymns: Hyfrydol, CWM Rhondda, Aurelia, Duke Street, The Ash Grove, Kingsfold, Greensleeves... I could go on. The hymn tune's name usually comes from the first historically-popular text to use the hymn.
Comment: Very interesting.  Oddly enough when I read your example titles I got The Servant Song stuck in my head, which upon inspection turns out to have 8/7 verses as well.
Comment: @KeithS I knew there was a better name.  I just couldn't seem to find / recall it.  Thanks.


Android SwipeGesture working only in one direction,i have no clue why?

Question: i am making a music player for android but i recently updated it with swipe gestures but the thing is that only one gesture(bottom swipe is working) i checked the swipe gesture class and nothing seems to be wrong in that
here is the code of my implementation
LinearLayout LL=(LinearLayout) findViewById(R.id.LL);
LL.setOnTouchListener(new OnSwipeTouchListener() {
            public void onSwipeTop() {
                mp.stop();
                mp.release();
            }
            public void onSwipeRight() {
                mp.stop();
                mp.release();

            }
            public void onSwipeLeft() {
                mp.stop();
                mp.release();

            }
            public void onSwipeBottom() {
                mp.stop();
                mp.release();
            }
        });

and here is my  class for swiping
public class OnSwipeTouchListener  extends Activity implements OnTouchListener{

    private final GestureDetector gestureDetector = new GestureDetector(new GestureListener());

    public boolean onTouch(final View view, final MotionEvent motionEvent) {
       // super.onTouch(view, motionEvent);
        return gestureDetector.onTouchEvent(motionEvent);
    }

    private final class GestureListener extends SimpleOnGestureListener {

        private static final int SWIPE_THRESHOLD = 70;
        private static final int SWIPE_VELOCITY_THRESHOLD = 60;

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;
            try {
                float diffY = e2.getY() - e1.getY();
                float diffX = e2.getX() - e1.getX();
                if (Math.abs(diffX) > Math.abs(diffY))
                {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD)
                    {
                        if (diffX > 0)
                        {
                            onSwipeRight();
                        }
                        else
                        {
                            onSwipeLeft();
                        }
                    }
                }
                else
                {
                    if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD)
                    {
                        if (diffY > 0)
                        {
                            onSwipeBottom();
                        } else {
                            onSwipeTop();
                        }
                    }
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return result;
        }
    }

    public void onSwipeRight() {
    }

    public void onSwipeLeft() {
    }

    public void onSwipeTop() {
    }

    public void onSwipeBottom() {
    }
}

Comment: But in my case swipe is working in one direction....can you debug the code??if not why are you posting such questions with totally different approach???first i have to understand his code,then his problem and then change it suiting to my needs and then check if its working for me or not...
Answer: Seems like there was no problem with the code....but the problem was with the  view,the xml file..
the linear layout was not filling the whole space...so the only swipe which was working was the bottom swipe...and that too only in the top region.(where the linear layout existed)......


Intuition behind simple complex number loci problems

Question: I have been looking at some complex number locci problems and I was wondering how would one intuitively think about them. The one I have in mind is what is the locus of $\arg{\frac{z-1}{z}} =\alpha$ given that $\alpha$ is such that  $0<\alpha<\frac{\pi}{2}$. First, I thought of letting $z=a+bi$ and then see what the locus of $z$ is algebraically. I got that it is going to be a circle, however, when I checked the answer I was wrong as the answer was the circle above the real axis. Here is the image from the answers:
My attempt at thinking about it visually
We have $\arg{\frac{z-1}{z}}=\arg{z-1}- \arg{z}= \alpha$. So we want to find the points on the argrand diagram s.t the angle between $z-1$ and $z$ is equal to $\alpha$. In trying to apply this diagrammatically, I ploted a general point $z$ and then $z-1$. I plotted $\alpha$ but from there I got stuck as how to proceed.
Could someone give me some insight into how to interpret the problem more visually and intuitively?
Thanks in advance.
Answer:
As seen from the diagram, the inner angle $\alpha$ of the triangle is the difference between the outer angle $\arg(z-1)$ and the other inner angle $\arg(z)$, i.e.
$$\alpha = \arg(z-1) - \arg(z) =  \arg\frac{z-1}z$$
For constant $\alpha$, the vertex of $\alpha$ follows the circumference of the red circle, but only above the $x$-axis. It can be shown similarly that the subtended angle below the $x$-axis is $\arg\frac{z}{z-1}\ne \alpha$, thus excluded.
Comment: Hi, thanks for the answer! Could you explain to me how one arrives that the locus will be a circle non-algebraically?
Comment: Also, I know this is a stupid question, but, why is $z-1$ intersecting at one as shouldn't the lines $z and $z-1$ start from the origen and have their real coordinate being displaced by 1?
Comment: @MathsWizzard - note that on a circle, any angle subtending a fixed chord, in this case from 0 to 1, is the same. So, given the constant $\alpha$, the locus is along the red circle
Comment: @MathsWizzard - regarding z-1, complex numbers can also be viewed as vectors in the Argend plane and z-1 is the difference between the vector z and 1, an arrow from 1 to z.
Comment: all clear now, thank you for taking the time to explain this to me.


Confusing Parametrization

Question: Problem:

Determine whether the following statement is true:
The line $y=3x$ can be parameterized as $$x=\cos (2t)$$
$$y=3\cos(2t)$$
$$-\infty<t<\infty$$

Plugging in for $y$ and $x$ in the equation $y=3x$, I get $3\cos(2t)=3\cos(2t)$, which is true for all $-\infty<t<\infty$. But I am wrong. I need help understanding how to solve this problem.
Answer: Due to the fact that $\cos(2t)\in[-1,1]$, the line $y = 3x$ is not parametrized by $x = \cos(2t)$ and $y = 3\cos(2t)$. In fact, what is being parametrized is the line segment
$$L = \{(x,y)\in[-1,1]\times[-3,3]\mid y = 3x\}$$

Confusing Parametrization


Probability of overlap of areas in 2D space

Question: Assuming I observe, in a unit square, $n_1$ circles of area $A_1$ (non-overlapping amongst themselves) and $n_2$ circles of area $A_2$ (again, non-overlapping) and that each of the centres is uniformly distributed across the square (well, I guess that can't be precisely true given the non-overlapping constraint), is there an expression for the proportion of the first circles that overlap with at least one of the second type of circles.
The actual situation is observed cancer cells and pores on a microscope slide, to which the above seems a good approximation.
In the 1D case, I'd like to think that for each line segment (1D equivalent of a circle) of the first group, there's an interval of size $A_1+ A_2$ before the end of each segment of the second type to place the start of the interval so that they would overlap, and so $n_2(A_1+A_2)$ of the unit interval would result in an overlap.  That seems to be true for the first segment of the first group, but it won't necessarily hold for further segments as the non-overlapping criterion breaks the independence, so I'm probably looking at this (and the 2D case) from the wrong angle.
Updated thoughts
Maybe this is the way to look at it?  There's a total area $n_1A_1$ covered by type 1, and $n_2A_2$ covered by type 2, out of a total area of 1.  So an expected area of $n_1A_1n_2A_2$ is covered by both, and divide this by $A_1$ to give the number of type 1's that would be needed to cover that area, and divide by $n_1$ to get the proportion of type 1's that are in the double-covered area.  So if 7% of a slide's area is covered by spores, then 7% of cells are hit by spores?
Comment: Are the middles of the circles within the square, or the whole circles?
Comment: The circles are going to be small compared to the square (and also reasonably sparse, not taking more than 10% of the available area), so I'm hoping it doesn't make too much difference - but to be accurate, this is a square subregion so it's possible that even the centre of a circle is outside (but no further than the circle's radius away from) the boundary.
Comment: Are the $n$'s generally big?
Comment: 10% .. is that the total area of the circles, or the area of each?
Comment: That's of the total area.  So no more than 10% of the square is covered by circles of type 1, and no more than 10% is covered by type 2 circles.
Comment: And $n$ will be in the hundreds
Answer: An easy procedure would be to calculate the chance that two given circles $c_1$ (in the set $C_1$, of area $A_1$) and $c_2$ are overlapping and use the number of combinations of a circle of each group resulting in a number $N$ overlaps.
I'm assuming that you mean that each circle in the first group has area $A_1$ and each in the second $A_2$.
My procedure does simplify some issues concerning borders and overlap of multiple circles. I assume the circles are relatively small and few.
The chance of a circle $c_1$ of area $A_1$ to have overlap with another circle $c_2$ of area $A_2$ within an area of $1$, is the area given by the possible positions of the centre of $c_2$ causing an overlap with some given $c_1$. This area forms a circle with a radius equal to the sum of the radii of $c_1$ and $c_2$. Since $A = \pi r^2$, $r = \sqrt{A/\pi}$ and so the area under consideration is $A_{\text{overlap}} = \pi (\sqrt{A_1/\pi} \cdot \sqrt{A_2/\pi})^2$. The ratio of this area to the total area gives the chance $P_{\text{overlap}}(c_1, c_2) = A_{\text{overlap}} / A_{\text{total}}$.
The expected number of overlaps is $E(N) = \sum\limits_{n=0}^{M} nP(N=n)  $, where $M=\min(n_1,n_2)$ is the maximum number of overlaps assuming that no circle is overlapping multiple others.
When we further ignore the fact that circles in $C_2$ that don't overlap circles of $C_1$ shouldn't overlap amongst themselves, we can say that
$P(N=n) = {n_1\choose n}{n_2\choose n}n! (P_{\text{overlap}})^n (P_{¬ \text{overlap}})^{n_2-n} $.
Here ${n_1\choose n}{n_2\choose n}n!$ gives the number of possibilities for $n$ pairwise combinations from groups $n_1$ and $n_2$
When assuming that each two circles of $C_1$ are at a distance between them that leaves a space for a non-overlapping circle of $C_2$ between them (so we assume that for each circle in $C_1$ its area of overlap doesn't overlap with the area of overlap with any other area of overlap of a circle in $C_1$), then the chance of a circle $c_2$ of area $A_2$ having no overlap with any circle of $C_1$ is
$P_{¬ \text{overlap}} = (A_{\text{total}}- A_{\text{overlap}}*n_1)/A_{\text{total}}$
Since $A_{\text{total}} = 1$, we then have $P(N=n) = {n_1\choose n}{n_2\choose n}n! (A_{\text{overlap}})^n (1- A_{\text{overlap}}*n_1)^{n_2-n}$, where $A_{\text{overlap}} = \pi (\sqrt{A_1/\pi} \cdot \sqrt{A_2/\pi})^2$
There have been a lot of simplifications and/or assumptions along the way, but I think they are not so bad given that the circles are small and sparse.
I know this answer isn't very formal and precise, but I hope it helped.


ImageView layout on custom ViewGroup only moves "bounding box", not image

Question: I am trying to position an ImageView within a custom ViewGroup. Using the Graphical Layout in Eclipse, I can see that the bounding box is placed where I want, but the image itself stays at (0,0) of the parent.
Am I missing a measure- or layout-related call for the ImageView, or doing the layout positioning wrong? How can the image be separated from its layout boundaries?
Here's a screenshot of what I'm describing: http://dl.dropbox.com/u/13477196/gameboard.png
And the code bits from the ViewGroup:
public class GameViewGroup extends ViewGroup {
...
    @Override
    public void onLayout(boolean changed, int l, int t, int r, int b) {
        for (int col = 0; col < COLS; ++col) {
            for (int row = 0; row < ROWS; ++row) {
                ImageView image = (ImageView) findViewById(pieceId[col][row]);
                final Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();

                final int imgLeft = l + (int) board.getVertexX(col) - (bitmap.getWidth() / 2);
                final int imgTop = t + (int) board.getVertexY(col, row) - (bitmap.getHeight() / 2);
                final int imgRight = imgLeft + bitmap.getWidth();
                final int imgBot = imgTop + bitmap.getHeight();

                image.layout(imgLeft, imgTop, imgRight, imgBot);
            }
        }
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        // Draw the game board from cache
        canvas.drawBitmap(cachedBitmap, 0, 0, null);

        // Draw the pieces
        for (int col = 0; col < COLS; ++col) {
            for (int row = 0; row < ROWS; ++row) {
                ImageView image = (ImageView) findViewById(pieceId[col][row]);
                image.draw(canvas);
            }
        }
    }
...
}

I use XML to attach the ImageViews to the custom ViewGroup:
<?xml version="1.0" encoding="UTF-8"?>
<GameViewGroup
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/game_view"
    android:layout_height="fill_parent"
    android:layout_width="fill_parent"
    tools:context=".GameActivity">

    <ImageView android:id="@+id/piece1"
        android:src="@drawable/piece"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="visible"
        android:contentDescription="@string/piece" />
...

Answer: I added the following under the call to image.layout() in onLayout():
image.setPadding(imgLeft, imgTop, imgRight, imgBot);

And that positioned the image in exactly the same place as the bounding box in the Eclipse Graphical Layout.
However, when launching the app on my device, it still doesn't work.


How do I manage core and module updates along with config management between environments?

Question: I've set up a dev site, a test site, and a public site. Dev and Test are in two separate virtual machines (VLAD) and Public is on a shared Dreamhost account. I've successfully used the Configuration management tool to get all three of these environments in sync by installing it once, then copying the files (git) from one to the other environments, and exporting/importing the database information. Now it is time for me to update something like Drupal core from 8.0.3 to 8.0.4 and I am unsure exactly how that should happen with relation to getting that update on the other two environments. So, the main question is: how should I migrate/deploy/manage the upgrade between environments taking into consideration the need for UUID and CMI to stay intact?
Should I update one environment, lets say dev, using whatever chosen tool I have handy (like drush up --security-only or download the new version, and hit update.php in the browser, etc.) then copy those files from dev to test and re-export/import the database info? Or, should I update each of them individually? I suppose the thing I'm most worried about is will that break configuration management? Maybe I don't need to export/import database files and instead just export/import config changes after updating drupal or some contrib module into the dev site.
I've read what feels like 50 different posts about CMI and how to use it and how Drupal 8 makes some of this so much better and I totally agree about the information that actually gets managed by that tool but I can't seem to find information about how to deal with upgrading core and modules between these different environments. If I'm just not reading the right doc or blog post correctly and you can point me to one that is great. If you can answer directly here that is great too. And, maybe I'm just not "getting it" so please feel free to set me straight.
My question may be similar to the one posed here but it isn't exactly worded the same, so, again, I may just be missing the easy answer here.
Answer: Yes, the referenced issue is related but I think this deserves a separate answer.
I agree this situation isn't fully satisfactory, but it's not too much of a problem.
In most environments, it won't be possibly to avoid manual configuration changes on production entirely. For example, contact forms are configuration (and not just a single file but 3 + 2 * number_of_fields) and users will likely create new ones without going through staging.
That basically means that you have to live with the situation that there can always be changes on production that are different from what happened on staging/dev. And that you have to treat the configuration on production as the master, unless you're deploying specific changes.
My process for deploying configuration changes usually looks like this:

Do the changes, commit them to a feature branch.
Export the configuration from production and commit it to whatever branch you use for that (for me, that's usually a branch called "production")
Merge your changes into that. Resolve conflicts if necessary.
Deploy the code to production.
Verify the configuration changes, make sure that ther are only known changes that know you prepared for deployment.
Import the configuration.

Module updates add the additional problem of update functions. If you have those, you need to run them between steps 4 and 5. Usually, those aren't a big problem unless they create new configuration with new UUID's. Then you have a problem if you want to import the same configuration entities from the staging config since those would have different UUID's and it would lead to deleting and re-creating them. You have to merge back the changed configuration from production before you can do that.
In general, I'd recommend to not mix module updates with feature/configuration deployments. Do module updates first, export the configuration again, then deploy again with new configuration.
Note that enabling new modules isn't affected by this, unless the module is installed by an update function. But if you deploy new modules through an updated core.extension module list, the config system supports that explicitly by taking the new configuration from your configuration export and not the module's clean default installation. So it's perfectly supported to enable a module on staging, customize its default config (not just simple configuration but also views and so on) and then deploy it to production.
Comment: Thank you, that makes me feel more confident in going for it in that order without breaking things.


Write modbus register with pymodbus

Question: I'm new to programming.
I need to write modbus registers using python and I have no experience with pymodbus.
What is the way to actually start and communicate with a modbus server?
Im able to read the registers from this modbus server using a software I found on the internet.
How can I read the registers and write to them using pymodbus module? I literally dont know where to start.
Thanks for the answers!
Comment: modbus has some section such as tcp, rtu, udp protocol, [this](http://pymodbus.readthedocs.io/en/latest/) is a full document and they have many example.
Answer: <code>from pymodbus.client.sync import ModbusTcpClient as ModbusClient

try:
    client = ModbusClient(host='IP',port='502')
    request = client.read_holding_registers(0x00,5,unit=1)
</code>

Write modbus register with pymodbus


Store data permanently in a variable (javascript)

Question: Is it posibble to store data to your web page permanently or after page refresh?
<code>$('<li>').text(post).prependTo('.userPosts');
//store the data whenever the an <li> is added to the <ul class="userPosts">
</code>
i have created a jsfiddle for it http://jsfiddle.net/bgb4h2g1/1/
any ideas can be helpful. thanks!
Comment: Save it in a cookie or local storage.
Comment: Define permanently.  Even after the user closes the webpage, clears cookies, history, or any other method?
Comment: Not on the client side you can't. Your data would have to be stored on server via file or db.
Answer: The javascript context lives ONLY for the lifetime of the page in the browser.  As soon as the user moves to another page, the entire javascript context is thrown away.  So, Javascript variables themselves do not persist beyond the lifetime of the page in the browser.
Thus, to make a value persist, you have to store it somewhere and then load it from that location the next time that page is viewed.  The data can be stored either in the browser or on the server.
In the browser, you can store it in a cookie or in LocalStorage.
On the server, you can use Ajax to push a value to the server to be stored by the server however it deems to store it (in a database, in memory, etc...).  If storing on the server, you will also have to know which user you are storing it on behalf of because the server serves the needs of many viewers.
If storing it in the browser, then you would usually have some javascript that runs at page initialization time that would load the data from the cookie or LocalStorage.
If storing on the server, you can either insert the data into the page as it is requested by the browser (part of the page generation) or you can have Javascript in the page request the data from the server via Ajax.


Hypothesis testing in python not equal sizes

Question: I have two samples(n1= 25,  n2= 35) with N(mu = 70, sd =10) and I am trying to test
H0:mu1-mu2=0
for variances unknown. This is the code I am working on it but I can not get the result because of inequal lengths.
<code>rvs1 = stats.norm.rvs(loc=70,scale=10,size=25)
rvs2 = stats.norm.rvs(loc=70,scale=10,size=35)
stats.ttest_rel(rvs1,rvs2)
</code>
Answer: I think what you need is stats.ttest_ind instead of stats.ttest_rel.
stats.ttest_rel is for related samples and stats.ttest_ind is for independent samples. Since you have two different values for the size they are two independent samples. They may be coming from the same population but they are different so you need to use stats.ttest_ind.


Use Different HTTP Protocols per Browser in Apache

Question: I am trying to use http/2 for everything except Safari because of some strange behavior we are seeing when using http/2 with any version of Safari we have handy. I cannot figure out how to set up Apache to allow it, however. Can anyone shed some light on why the following doesn't work?
BrowserMatchNoCase Safari NOHTTP2
# Chrome includes both Safari and Mozilla in its User Agent
BrowserMatchNoCase Chrome !NOHTTP2

<IfDefine NOHTTP2>
    Protocols http/1.1
</IfDefine>
<IfDefine !NOHTTP2>
    Protocols h2 h2c http/1.1
</IfDefine>

That is currently in /etc/apache2/mods-enabled/http2.conf. I have no experience with IfDefine or BrowserMatch, so I'm not sure if I am doing this correctly (given that it isn't working, it would seem I am not). Every browser I test it on still has http/2 enabled with the above config as well as any others I have tested.
I have also tried SetEnvIfNoCase User-Agent instead of BrowserMatch, and various options other than IfDefine such as If and Directory, but all of these throw "Protocols not allowed here" errors when running the configtest.
I am running Apache 2.4.25 on Debian 9.6.
Comment: I think that proper approach would be to fix the Safari issue, because I don't see any HTTP/2 issues with any Safari I have around me.
Answer: I suspect you can't do what you want because by the time you've worked out what browser the client is using you've already negotiated the protocol and received a request; the User-Agent is submitted as a request header.
Your first <IfDefine> block would only work if you ran the httpd binary passing -DNOHTTP2 as an extra argument and that would restrict the protocol to HTTP/1.1 for all clients. Because the define is unset it's defaulting to the second block which is enabling all of the protocols. See https://httpd.apache.org/docs/2.4/mod/core.html#ifdefine
Comment: After quite a bit of testing last week, I have come to this same conclusion and your explanation makes complete sense. It's unfortunate because I cannot figure out how to solve the Safari issue, but it does seem correct


Sql - Explicit order of WHERE conditions?

Question: Is there any way to explicitly state the order for WHERE conditions to take place?  I realize that the query optimizer will look at all parts of the WHERE clause to determine the most efficient way to satisfy the query, as stated in these answers:
Does order of where clauses matter in SQL
SQL - Does the order of WHERE conditions matter?
However, is there no way to check for a condition that other conditions will rely on? One of the answers from those threads touches on what I'm after, but doesn't offer a solution:
select *
from INFORMATION_SCHEMA.TABLES
where ISNUMERIC(table_name) = 1 and CAST(table_name as int) <> 0

This can fail because the CAST can be evaluated before determining whether the table_name field is numeric (and therefore throw an error for invalid casting).
Surely there must be a way to achieve this?
Answer: Using a derived table:
SELECT *
FROM (
      SELECT *
      FROM INFORMATION_SCHEMA.TABLES
      WHERE ISNUMERIC(table_name)=1
     ) AS i
WHERE CAST(table_name AS INT)<>0

Alternatively, and most likely run in order, you can use a CASE statement:
SELECT *
FROM INFORMATION_SCHEMA.TABLES
WHERE 0<>(CASE WHEN ISNUMERIC(table_name)=1
          THEN CAST(table_name AS INT)
          ELSE 0 END)

It should be noted that for SQL Server there exist situations where the CASE-trick will fail. See the documentation on CASE, Remarks:

The CASE statement evaluates its conditions sequentially and stops with the first condition whose condition is satisfied. In some situations, an expression is evaluated before a CASE statement receives the results of the expression as its input. Errors in evaluating these expressions are possible. Aggregate expressions that appear in WHEN arguments to a CASE statement are evaluated first, then provided to the CASE statement. For example, the following query produces a divide by zero error when producing the value of the MAX aggregate. This occurs prior to evaluating the CASE expression.
WITH Data (value) AS
(
SELECT 0
UNION ALL
SELECT 1
)
SELECT
   CASE
      WHEN MIN(value) <= 0 THEN 0
      WHEN MAX(1/value) >= 100 THEN 1
   END
FROM Data ;

I suspect this might also be true for other RDBMS implementations.
Comment: Not pretty, but I'll take it. Thanks!
Answer: I think you are asking if evaluation can short-circuit - it might help to read this:
Is the SQL WHERE clause short-circuit evaluated?
So, you probably need to evaluate the first condition before attempting the second.  In MSSQL, you could use a CTE to do the first.  Or, another option might be to use a CASE to only perform the second under certain conditions.