Is there any way to use AddSingleton in ApplicationInitialization under the ABP framework?

Question: I'm using the ABP framework, and want to register a singleton class for global use. but it needs some other class. So I want the OnApplicationInitialization function to register it.
 public override void OnApplicationInitialization(ApplicationInitializationContext context)
{
     var settingManager = context.ServiceProvider.GetService<ISettingManager>();
     var cloudStorageProviderManager = context.ServiceProvider.GetService<ISlideCloudStorageProviderManager>();
      var cloudProvider = await settingManager.GetOrNullGlobalAsync(CloudStorageSettings.CloudProvider);
      var slideCloudStorage = cloudStorageProviderManager.Resolve(cloudProvider);

      // how to  register slideCloudStorage.
}

Answer: This seems to be an XY Problem.
Is there any way to register a singleton class that needs some other class? (Problem X)
Yes, you can use AddSingleton in ConfigureServices with a function as an implementation factory.
public override void ConfigureServices(ServiceConfigurationContext context)
{
    context.Services.AddSingleton(serviceProvider =>
    {
        var settingManager = serviceProvider.GetService<ISettingManager>();
        var cloudStorageProviderManager = serviceProvider.GetService<ISlideCloudStorageProviderManager>();
        var cloudProvider = settingManager.GetOrNullGlobal(CloudStorageSettings.CloudProvider);
        return cloudStorageProviderManager.Resolve(cloudProvider);
    });
}

Is there any way to use AddSingleton in ApplicationInitialization under ABP framework? (Solution Y)
No, there is no supported way.


Why is the sixth sometimes considered a dissonance which needs preparation?

Question: I'm currently reading F. A. Gore Ouseley's Treatise on Harmony, which is a nice book from which to learn common-practice harmony (from a mid-19th century perspective).
However, I'm a bit baffled by his treatment of suspensions (p. 95 et seq.). He seems to consider the sixth as a dissonance by suspension, which resolves into the fifth. Why does he do this? Was this a standard way of treating the sixth, or is it an idiosyncrasy on the part of Gore Ouseley?
Link to the book
Answer: I feel like this answer with only restate you know and is in the book, but...
If consonance and dissonance as stated in the book are considered synonymous with stable and unstable, I think the concept is clear.
Root position chords are stable and synonymous with consonant.
Inverted chords are unstable and synonymous with dissonant.
That all stated pretty clearly in chapter VIII, item 2.
The part that follows about a sixth as a suspension resolving to a fifth does seem odd. The point would seem to regard inverted chords as not bona fide chords...

...so that second chord is not iii6 but V with a suspension.
Why?
I did a quick scan of the chapters before this. It looks like it teaches a rule of the octave kind of harmony. It shows how to harmonize a bass line where the harmonies are predominantly tonic and dominant chords only.
If you want to analyze harmony in terms of tonic and dominant, then the chord of the sixth example above - where the sixth is considered a suspension - is not really regarded as an inverted mediant iii6 but as a dominant V with a suspension.
That's my quick impression. Call the sixth a suspension so the chord can be interpreted as a dominant.

EDIT
Some questions stick in my mind, like this one.
I stumbled upon this today...

...from Kostka & Payne, Tonal Harmony, the still call the sixth a consonance, but I think it's clear how this connects with Ouseley and regarding the tone forming the sixth is a non-chord tone and the proper chord isn't the inverted chord of the sixth.
Also, I was playing this sequence drill from Fenaroli's "rules"...

https://drive.google.com/file/d/0B1tf9xeI3NRBcklRbjZSM0g4cUE/view
...if you look at the first three half notes in the bass, the chords are G: I V6 IV6. That means the E5 in the soprano has a dual role, an escape tone from the initial tonic, but a suspension on V6. This is from a book about figured bass so it contains no chord analysis. But, I think it is clear there is no vi6 chord in the first bar. It isn't explicitly called a "dissonant sixth" but it has the feel of an escape tone, a non chord tone.
So, most non chord tones are dissonant. But some non chord tones of the sixth aren't technically dissonant, but their not fitting the chord lends them a kind of tension similar to dissonance. Ouseley calls this a dissonance of the sixth. It's "dissonant" simply because it isn't a member of a root position chord.


Ajuda para migrar de Actionbar.Tabs para ViewPager por causa da API 21

Question: Pelo que eu entendi de leve, a hospedagem de tabs na actionbar ficou obsoleta na API 21. Ainda não entendi muito bem porque (se alguém explicar melhor eu agradeço) mas o que posso fazer é me adaptar.
Fiz uma pesquisa e descobri algumas alternativas como a Sliding Tabs do Google Play com ViewPager, apesar de eu nunca ter usado ViewPager porque a Actionbar.Tab me servia muito bem.
Mas estou com alguns problemas e dúvidas na implementação porque essa ferramenta parece ser muito boa para tabs estáticas. O caso é que o meu app tem as tabs muito dinâmicas. Em virtude de ser um app de chat com cada conversa sendo exibida por um fragment, novas tabs surgem e são removidas a todo momento.
Eu não consegui alinhar muito bem a estratégia do ViewPager com este cenário. Percebi que a maneira como o adapter identifica a tab selecionada é muito diferente do tablistener da actionbar e também não encontrei métodos que adicionassem ou removessem tabs no adapter ou no SlidingTabs. Pensei em armazenar os fragments em um Arraylist para ser usado pelo adapter mas não sei se o adapter identificaria quando eu removesse ou adicionasse um fragment de lá.
Outra questão que dinamiza as tabs é que os nicks dos usuários relativos à conversa são exibido nelas, e esse nick também pode mudar a qualquer momento. Não sei ao certo quando o método getPageTitle() é chamado.
Pensando nessas diferenças decidi vir aqui pedir ajuda pois talvez haja até uma alternativa melhor para este caso que eu ainda não conheço ou alguma boa prática que deixe esse cenário viável.
Qualquer ajuda é bem vinda. Desde já, muito obrigado.
Answer: Olá, primeiro eu gostaria de dizer sobre a minha experiência em relação a Fragments dinâmicos dentro do ViewPager e posso te dizer que não é uma boa idéia. Não tenho idéia de como é o seu app mas se conselho fosse bom (rsrs) eu diria pra você pensar em como funcionam a maioria dos apps de mensagens (hangouts, fb messenger, whatsapp, telegram, etc.), onde existe um Fragment que lista as conversas e outro Fragment/Activity que mostra a conversa. Também penso na usabilidade, por exemplo: Eu tenho 10 Tabs/Conversas abertas e pra poder abrir a 9º eu preciso ficar rolando o ViewPager até chegar lá O_o
Mas esclarecendo como funciona o ViewPager, você deve pensar na estrutura dele. Primeiro o xml:
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.astuetz.PagerSlidingTabStrip
        android:id="@+id/sliding_tabs"
        android:layout_width="match_parent"
        android:layout_height="?actionBarSize"
        android:layout_gravity="top"
        android:textSize="16sp"
        android:background="@color/color_primary"
        app:pstsIndicatorColor="@color/color_primary_darker"
        app:pstsTextAllCaps="false"
        app:pstsIndicatorHeight="2dp"
        app:pstsPaddingMiddle="false"/>

    <android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="0px"
        android:layout_weight="1"
        android:background="@android:color/white"/>

</LinearLayout>

Bem simples onde você indica onde ficará as Tabs (título ou qualquer layout que você quiser) e o seu ViewPager que é onde serão adicionados todos os seus Fragments.
Depois, no Fragment/Activity que você quiser implementar o ViewPager você deve criar um Adapter para ele e setar o ViewPager no SlidingTab:
mPager = (ViewPager) v.findViewById(R.id.viewpager);
mPagerTab = (PagerSlidingTabStrip) v.findViewById(R.id.sliding_tabs);
mPager.setAdapter(new ViewPagerAdapter(getActivity().getSupportFragmentManager(), tabtitles, mDrawable));
mPagerTab.setViewPager(mPager);

E um exemplo simples de um FragmentPagerAdapter:
public class ViewPagerAdapter extends FragmentPagerAdapter {

    final int PAGE_COUNT = 3;
    private String titles[];

    public ViewPagerAdapter(FragmentManager fm, String[] titles) {
        super(fm);
        titles = titles;
    }

    @Override
    public Fragment getItem(int position) {
        switch (position) {
            case 0:
                return SampleFragment.newInstance();
            case 1:
                return SampleFragment.newInstance();
            case 2:
                return SampleFragment.newInstance();

        }
        return null;
    }

    public CharSequence getPageTitle(int position) {
        return titles[position];
    }

    @Override
    public int getCount() {
        return PAGE_COUNT;
    }

}

O que determina a quantidade de Fragments no ViewPager, neste* caso é o field PAGE_COUNT;
É possível sim você ficar mudando a quantidade de Fragments no seu Adapter para isso você precisa criá-lo passando como parâmetro a quantidade de Fragments que você quer e uma lista com os Fragments que você deseja utilizar. Ou você também pode criar esses métodos dentro do Adapter, modificá-los e informar ao controlador pelo método notifyDataSetChanged(); do Adapter.
Neste exemplo eu usei o framework https://github.com/jpardogo/PagerSlidingTabStrip
Comment: Então, no meu caso esse PAGE_COUNT já não poderia ser final, ele vai variar.
E pra eu entender melhor, caso eu queira adicionar ou remover uma tab, da certo eu ter um Arraylist para armazenar os fragments e caso ocorra alguma alteração, eu chamo o notifyDataSetChanged()?
Comment: Isto mesmo. Funciona da mesma forma como você pode fazer em uma ListView com um BaseAdapter
Comment: Olhando dessa forma pode até ficar mais simples do que com actionbar.tabs. Isto é, se funcionar.
Comment: Rafael, como eu faço para saber o indice ou titulo da tab selecionada?
Comment: Você pode usar o método `getCurrentItem()` do ViewPager que retorna um inteiro.
Comment: Você poderia me dizer qual a diferença dessa sliding tabs do jpardogo para a do astuetz e qual eu deveria usar e pq?
Muito obrigado Rafael.
Comment: Basicamente a do jpardogo é baseado no Material Design e a do astuetz no Tema Holo (tema padrão do ICS, JB e KK)


Proving a numerical inequality without using a calculator

Question: I want to prove $2^{28}>5^{11}$. It reduces to proving $28 > 11.\log_25$. But how should I verify it theoretically without using a calculator?
I was looking for a general theorem verifying such inequalities but apparently some numerical calculations are unavoidable.
Comment: Please edit to include your efforts.  Note that $2^7>5^3$.
Comment: Alternatively:
$$ 2^{28} = 2^{10(2.8)} > 10^{3(2.8)} = 10^{8.4} $$
and
$$ 5^{11} = \frac{10^{11}}{2^{11}} < \frac{10^{11}}{10^{3(1.1)}} = 10^{7.7} $$
Answer: Since $\;2^7=128>125=5^3\;,\;$ it follows that
$\left(2^7\right)^4>\left(5^3\right)^4\;,$
$2^{28}>5^{12}>5^{11}\;,$
hence ,
$2^{28}>5^{11}\;.$
Answer: As an alternative, similarly to the hint given by Gregory in the comments, we have
$$2^{28}>5^{11} \iff 2^{28}2^{11}>5^{11}2^{11}\iff 2^{39}>10^{11}$$
and
$$2^{39}=\left(2^{10}\right)^{3.9}>\left(10^{3}\right)^{3.9}=10^{11.7 }>10^{11}$$


How do I add a customized parameter to image links

Question: Lets say I have image fields in my node. When I get that fields values in the twig it returns the image URL without any issue.
file_url(node.field_image.entity.uri.value)

But now I want to add a specific parameter (lets say ?param=0) to the end of that link. Without hard coding the parameter in the twig file is there a way to write a hook that adds that parameter for all the image links in every node. So if I have to change the param I only need to change it from one place.
Comment: How is the image link created ? is it another field ? Link to itself as a bigger image ?
Comment: @GiorgosK No this is an normal image field in the node. I want to know how to add a param without putting it like `file_url(node.field_image.entity.uri.value)?param=0`. Is there a way to do this like globally. If I change from one place it should apply to all the images.
Answer: You can do this with a preprocess function THEMENAME_preprocess_field and check whether the field is an image and it has a URL
function THEMENAME_preprocess_field(&$variables) {
  if($variables["element"]["#field_type"] == "image"){
    if(isset($variables["items"][0]["content"]["#url"])){
      $variables["items"][0]["content"]["#url"]->setOption('query', ['param' => '0']);
    }
  }
}


Is it possible to redirect all subdomains except www to a specific directory?

Question: I would like any directory *.example.com (bar.example.com, foo.example.com, etc..) to direct to the folder /home/user/htdocs/subdir/
www.example.com and example.com should remain unaffected.
Is this possible with htacecss, or another route?
Answer: You could do this by setting up two virtual hosts via the Apache configuration. For example:
NameVirtualHost *:80

<VirtualHost *:80>
  DocumentRoot /home/user/htdocs
  ServerName www.example.com example.com
</VirtualHost>

<VirtualHost *:80>
  DocumentRoot /home/user/htdocs/subdir
  ServerName *.example.com
</VirtualHost>

Answer: After the declaring in your Apache configuration file the directives for www.example.com and example.com, you can set an extra VirtualHost entry with any subdomain as ServerName and a wildcard ServerAlias like so to point every subdomain there.
<VirtualHost *:80>
  DocumentRoot /home/user/htdocs/subdir
  ServerName foobar.example.com
  ServerAlias *.example.com
</VirtualHost>

Note: You must declare a servername (any would do)


Combining animation frames to save space

Question: I'm working on a project that uses a lot of graphics files.  We've got about 500 60x60 PNG files making up several different animations (about 80), and taking up about 2MB of space.  In the code, I just draw each frame one by one to render an animation.  As an example, one of the animations is made up of 3 frames, each about 4 KB in size.  My question is whether there is anything we can do to decrease the size of these images.
We're relying pretty heavily on the transparency in the images, so converting to JPG is out.  Converting to GIF was an option, but the quality of the rendered images was too low, so I don't think we can use that.
PNGCrush saved us about 20 KB across all images, so didn't help that much.
Between each frame of an animation there isn't a lot of change in the data.
Answer: You can turn all the images to JPG and create another B&W image for each image that acts as the alpha channel that can also be a JPG (These should be very compressible), just manage the transparency yourself.
You can also convert all the images to one big byte array and apply a LZ variation (LZO/ZLIB should work just fine) on the array, this should save you, at least, 15%.
Answer: You could use JPEG2000 to store the images. It has a very good compression and supports alpha just like PNG (and it has both lossy and lossless modes), but it uses wavelets which demand floating-point processors (in case that is a problem).
Another possibility is to:

Convert the first image to JPEG and the alpha channel to B/W JPEG.
Calculate the delta (difference) from first to second image.
Compress the delta (again as JPEG).
If it's big at high quality, lower the quality.


Carregar Google Maps sem internet - Android

Question: Estou criando um app utilizando a activity padrão do google maps no android studio, a aplicação já está completa, porém gostaria que ela funcionasse sem internet, vi que o app do google maps tem essa funcionalidade, mas ainda não vi nenhuma aplicação de terceiros fazendo isso, é possível? Alguém tem alguma informação a respeito?
Comment: Imagino que tenha que fazer o download do mapa para o dispositivo, veja se isso ajuda: https://support.google.com/maps/answer/6291838?co=GENIE.Platform%3DAndroid&hl=en
Answer: Dá para você fazer isso usando uma classe chamada TileProvider, que trata de criar uma coleção de imagens exibida sobre os blocos do mapa básico. Sendo assim, aí vai da criatividade, você pode gravar na memória do dispositivo ou num cartão SD em formato .ZIP. Desta forma, você pode criar uma lógica para toda vez que não houver internet, consultar este bloco de imagens para reconstruir o mapa.

Uma TileOverlay define uma coleção de imagens adicionada sobre os
  blocos do mapa básico. Também é possível usar sobreposições de blocos
  para adicionar recursos ao mapa, fornecendo imagens de bloco
  transparentes. É necessário fornecer os blocos para cada nível de zoom
  que você pretende oferecer. Se você tiver blocos suficientes em
  diversos níveis de zoom, poderá complementar os dados de mapa da
  Google para o mapa completo.

Exemplo:
GoogleMap map; // ... declara um mapa
TileProvider tileProvider; // ... cria um tile provider
TileOverlay tileOverlay = map.addTileOverlay(
     new TileOverlayOptions().tileProvider(tileProvider));

Chamando o GoogleMap.addTileOverlay():
TileProvider tileProvider = new UrlTileProvider(256, 256) {
  @Override
  public URL getTileUrl(int x, int y, int zoom) {

    /* Define the URL pattern for the tile images */
    String s = String.format("http://my.image.server/images/%d/%d/%d.png",
        zoom, x, y);

    if (!checkTileExists(x, y, zoom)) {
      return null;
    }

    try {
      return new URL(s);
    } catch (MalformedURLException e) {
        throw new AssertionError(e);
    }
  }

  /*
   * Check that the tile server supports the requested x, y and zoom.
   * Complete this stub according to the tile range you support.
   * If you support a limited range of tiles at different zoom levels, then you
   * need to define the supported x, y range at each zoom level.
   */
  private boolean checkTileExists(int x, int y, int zoom) {
    int minZoom = 12;
    int maxZoom = 16;

    if ((zoom < minZoom || zoom > maxZoom)) {
      return false;
    }

    return true;
  }
};

TileOverlay tileOverlay = mMap.addTileOverlay(new TileOverlayOptions()
    .tileProvider(tileProvider));

Esta imagem descreve um pouco o que acontece:

A Google Maps API divide as imagens de cada nível de zoom em um
  conjunto de blocos de mapa quadrados, organizados em uma grade. Quando
  um mapa muda para uma nova localização ou para um novo nível de zoom,
  a Maps API determina quais blocos são necessários e converte essa
  informação em um conjunto de blocos a recuperar.

Existe um projeto OSMDROID que suporte para Java nativo para Android e para Xamarim, que já é um empurrão pra você trabalhar com Mapa offline. Dê uma lida mais para saber a respeito e instale o aplicativo de Mapas e Navegação — OsmAnd para você ter mais noção do funcionamento.
 Detalhes

Sobreposição de blocos
Coordenadas e Projeções
Exemplos de uso do MapTileProviderBasic
Como usar a biblioteca osmdroid
Comment: Perfeito Cleidimar, ótimas informações, vou dar início ao estudo, obrigado.


Webpack and external (vendor) .css

Question: I'm slowly bringing Webpack into an existing project. At this point we won't require .css files. However, I would like Webpack to still process them.
I would like Webpack to just load the file, pass it to whatever .css loader is required (Stylus in our case), and output a .css file.
None of the combinations of ExtractTextPlugin, raw and file loaders, passing loaders into other loaders work, Webpack inevitably throws
Module build failed: ParseError: ...bootstrap-theme.min.css:5:1996
   1| /*!
   2|  * Bootstrap v3.3.5 (http://getbootstrap.com)
   3|  * Copyright 2011-2015 Twitter, Inc.
...
expected "indent", got ";"

Is it even possible to process external files with Webpack like this?
Various combinations tried:
  {
    test:   /\.(styl|css)/,
    loader: 'raw!stylus'
  }

  {
    test:   /\.(styl|css)/,
    loader: 'file!stylus'
  }

  {
    test:   /\.(styl|css)/,
    loader: ExtractTextPlugin.extract('file', 'raw!stylus')
  }

  {
    test:   /\.(styl|css)/,
    loader: ExtractTextPlugin.extract('style-loader', 'css-loader!stylus-loader')
  }

Answer: You don't need to pass your css files through the stylus loader, only the .styl files.
I've managed to make it work with this configuration:
module.exports = {
  entry: {
    name: './test.js'
  },
  output: {
    filename: './bundle.js'
  },
  module: {
    loaders: [
      {
        test: /\.css$/,
        loaders: ['style', 'css']
      },
      {
        test: /\.styl$/,
        loaders: ['style', 'css', 'stylus']
      },
      {
        test:/\.(woff2?|eot|ttf|svg)$/,
        loader: 'url'
      }
    ]
  }
}

And then you can import/require your css files as such:
require('./test.css');
require('./node_modules/bootstrap/dist/css/bootstrap.min.css');

Comment: That's the thing: I don't want to `require` them yet. But, I guess, there's no way around that with webpack
Answer: You could also add your CSS as an extra entry point of name:
module.exports = {
  entry: {
    name: [
      './test.js',
      './test.css',
    ],
  },
  /* … */
};

Webpack and external (vendor) .css


Qual é a finalidade do while(*variavel) e if(!*variavel) nas declarações "while" e "if"?

Question: No Code Review há uma implementação de uma lista simplesmente encadeada que eu estou utilizando.
Porem, na resposta de um dos usuários, ele fez algumas modificações na lista, e teve uma modificação em particular que me deixou com dúvidas.
A modificação que o usuário fez foi no procedimento add():
void add(struct LinkedList *list, int value) {
    if(list->firstElement == NULL) {
        struct Element *newElement;
        newElement = malloc(sizeof(struct Element));

        newElement->value = value;
        newElement->nextElement = NULL;

        list->firstElement = newElement;
    } else {
        struct Element *lastElement;

        lastElement = list->firstElement;

        while(lastElement->nextElement != NULL) {
            lastElement = lastElement->nextElement;
        }

        struct Element *newElement;
        newElement = malloc(sizeof(struct Element));

        newElement->value = value;
        newElement->nextElement = NULL;

        lastElement->nextElement = newElement;
    }
}

Para:
void add(List* head, int value) {
    while(*head)
        head = &head[0]->next;
    *head = malloc(sizeof **head);
    if(!*head) abort();
    **head = (Node){0, value};
}

E minha dúvida esta na declaração while e if, que estão declaradas da seguinte forma como mostra abaixo:
while(*head)

e:
if(!*head)

É a primeira vez que eu vejo uma declaração do while e if como esta acima, utilizando ponteiro.

Pergunta
Eu gostaria de saber o que essas declarações while(*head) e if(!*head) significam e qual é a finalidade de uma declaração deste tipo com ponteiro em comandos de controle do fluxo?
Answer: No código em questão, List está definido como
typedef node* List;

Logo, head é na verdade ponteiro de ponteiro para um nó, e *head, por consequência, guarda um ponteiro para nó. A parte do while poderia ser escrita explicitamente como
while (*head != NULL)
    head = &((*head)->next)

Ou seja, anda-se na lista até chegar ao fim dela (indicado por NULL). Analogamente, a parte do if pode ser escrita como
if (*head == NULL) abort();

Como vem logo após o malloc, está verificando se o mesmo devolveu NULL (essa verificação não era feita no código original).
Sobre a finalidade, acredito que a vantagem da implementação no código em questão, por meio de ponteiros de ponteiro, visa a evitar escrever duas versões de add() (uma com lista vazia e outra caso contrário), bem como não é necessário mandar o último elemento apontar para o novo após inseri-lo.


Preencher combobox com ajax

Question: Olá, tenho uma página que mostra uma lista de usuários do sistema em uma tabela. No topo da página, tenho 3 combobox que filtram os resultados da tabela sem refresh. Preciso popular o segundo e o terceiro combo dinâmicamente e, ao mesmo tempo, ir mudando os resultados da tabela. Só que travei antes de começar a tabela rs O segundo combo eu consegui preencher de acordo com o primeiro, porém o terceiro eu não consigo popular... Alguem pode me ajudar ?
Segue o código:
if($funcao == 'combo1') {

    $sql = "select codfilial, nome from filial where codempresa=$codempresa order by nome;";
    $rst = my_query($connR, $sql);

    $selectfilial = "<option></option>" . getOptionSelect($rst, 'codcliente', 'nome');
    echo $selectfilial;

    exit;
}

if($funcao == 'combo2') {

    $sql = "select codequipe, nome from equipe where codempresa=$codempresa and codfilial=$codfilial order by nome";
    $rst = my_query($connR, $sql);

    $selectequipe = "<option></option>" . getOptionSelect($rst, 'codequipe', 'nome');
    echo $selectequipe;

    exit;
}

No seu formulário coloque também o evento onchange no select da filial. (Antes não funcionava porque você estava reescrevendo-o com jQuery):
<form class="form-inline" method="post" name="formpesq" action="/personificar_usuario.php" id="formpesq" style="margin-bottom: 0.25em; padding-top: 0.25em;">
    <input type="hidden" name="funcao" id="funcao" value="pesquisa"/>

        Empresa
        <select class="form-control" name="codempresa" id="codempresa" data-target="filial" style="width: 250px;"><?=$selectempresa?></select>

        Filial
        <select class="form-control" name="filial" id="filial" data-target="equipe" style="width: 250px;"></select>

        Equipe
        <select class="form-control" name="equipe" id="equipe" style="width: 250px;"></select>

</form>

Obs.: O código é mais conceitual, não foi testado e pode conter erros.
Comment: Que lindo, funcionou *-* Muito obrigada pela ajuda @KaduAmaral ! Bjs
Comment: Oi Kadu. Não funcionou... Está aparecendo no console que a função buscarDados() não está definida =(
Comment: @Donnathegirl atualizei o código Javascript e o formulário. Removi os eventos das marcações HTML e coloquei em um observador de eventos do jQuery. Faça essa atualização no teu código e me diz o que acontece. ;)

Preencher combobox com ajax


Creating a List View and Thumbnail view in Drupal 7 view

Question: I created a view but I am hoping to create two possible viewings of it.
Basically, it's showing it in either List View or Thumbnail View. Now, one option would be to create two views and showing one of them by default and hiding the other; hence toggling each when the button is pressed. But I was hoping to find some more efficient less resource intensive solution.
Thumbnail view

List view

Thanks.
Answer: You could create one view with 2 pages or blocks depending on how you are setting up your view. Then have one show list view and the other show thumbnail view. You could then use tabs to switch between the 2 views.
Answer: I agree with @n30r3b3l. The easiest way to do this is to create multiple "displays" within a single view. To do this, simply click the add  "+ Add" button in the top left are of the views edit page. You can rename each display. You will need to watch out for one thing, though. When you edit things in one display, the default setting is that the change will affect all displays.
You can override this setting on the edit form. Like so:


Kafka in the TensorFlow: Failed to consume:Broker: No more messages

Question: I want to use the kafka api in the tensorflow 1.7,however I got the error that Failed to consume:Broker: No more messages. I don't know how to fix this problem.
import tensorflow as tf
import tensorflow.contrib.kafka as kafka
temp =  kafka.KafkaDataset(topics='bt1_meeting_appeventlog_oracle:0:0:-1',group="None",
                           servers="kafka1:9092,kafka2:9092,kafka3:9092")
iterator = temp.make_one_shot_iterator()
#iterator = temp.make_initializable_iterator()
next_element = iterator.get_next()
with tf.Session() as sess:
    print(sess.run(next_element))

then I got the error :
InternalError (see above for traceback): Failed to consume:Broker: No more messages
 [[Node: IteratorGetNext_13 = IteratorGetNext[output_shapes=[[]], output_types=[DT_STRING], _device="/job:localhost/replica:0/task:0/device:CPU:0"](OneShotIterator_4)]]

Answer: As I meet the same problem when testing TensorFlow's Kafka client. In my case, setting eof tag of the KafkaDataset to True will solve this problem.
Tensorflow uses librdkafka as its c++ Kafka client. In librdkafka, EOF is treated as an error by default. By setting EOF to True will solve this problem.


Nice example where a series without a unit root is non stationary?

Question: I've seen several times people reject the null in an augmented Dickey-Fuller test, and then claim that it shows their series is stationary (unfortunately, I cannot show the sources of these claims, but I imagine similar claims exist here and there in one or another journal).
I contend that it's a misunderstanding (that rejection of the null of a unit root is not necessarily the same thing as having a stationary series, especially since alternative forms of nonstationarity are rarely investigated or even considered when such tests are done).
What I seek is either:
a) a nice clear counterexample to the claim (I can imagine a couple right now but I bet someone other than me will have something better than what I have in mind). It could be a description of a specific situation, perhaps with data (simulated or real; both have their advantages); or
b) a convincing argument why rejection in an augmented Dickey-Fuller should be seen as establishing stationarity
(or even both (a) and (b) if you're feeling clever)
Comment: $X_n = (-1)^n$ with probability 1.
Comment: @cardinal Well, that certainly would get a rejection by the ADF test (edit: yep, it does), and it's clearly nonstationary (a root on the unit circle, but not a root equal to 1 which the ADF detects); so that would count.
Comment: Note that ADF test has variants where trend is included. If the null is rejected, the series is trend-stationary, i.e. stationary if the trend is removed, but not stationary nevertheless.
Comment: +1. Glen_b, would a linear trend + stationary AR(1) noise count as a counter-example?
Answer: Here is an example of a non-stationary series that not even a white noise test can detect (let alone a Dickey-Fuller type test):

Yes, this might be surprising but This is not white noise.
Most non-stationary counter example are based on a violation of the first two conditions of stationary: deterministic trends (non-constant mean) or unit root / heteroskedastic time series (non-constant variance).  However, you can also have non-stationary processes that have constant mean and variance, but they violate the third condition: the autocovariance function (ACVF) $cov(x_s, x_t)$ should be constant over time and a function of $|s-t|$ only.
The time series above is an example of such a series, which has zero mean, unit variance, but the ACVF depends on time.  More precisely, the process above is a locally stationary MA(1) process with parameters such that it becomes spurious white noise (see References below): the parameter of the MA process $x_t = \varepsilon_t + \theta_1 \varepsilon_{t-1}$ changes over time
$$\theta_1(u) = 0.5 - 1 \cdot u,$$
where $u = t/ T$ is normalized time.  The reason why this looks like white noise (even though by mathematical definition it clearly isn't), is that the time varying ACVF integrates out to zero over time.  Since the sample ACVF converges to the average ACVF, this means that the sample autocovariance (and autocorrelation (ACF)) will converge to a function that looks like white noise.  So even a Ljung-Box test won't be able to detect this non-stationarity.  The paper (disclaimer: I am the author) on Testing for white noise against locally stationary alternatives proposes an extension of Box tests to deal with such locally stationary processes.
For more R code and more details see also this blog post.
Update after mpiktas comment:
It is true that this might look just like a theoretically interesting case that is not seen in practice.  I agree it is unlikely to see such spurious white noise in a real world dataset directly, but you will
see this in almost any residuals of a stationary model fit.  Without going into
too much theoretical detail, just imagine a general time-varying model
$\theta(u)$ with a time varying covariance function $\gamma_{\theta}(k, u)$. If you fit a constant model $\widehat{\theta}$, then this estimate will be close to the time average of the true model $\theta(u)$; and naturally the residuals will now be close to $\theta(u) - \widehat{\theta}$, which by construction of $\widehat{\theta}$ will integrate out to zero (approximately). See Goerg (2012) for details.
Let's look at an example
library(fracdiff)
library(data.table)

tree.ring <- ts(fread(file.path(data.path, "tree-rings.txt"))[, V1])
layout(matrix(1:4, ncol = 2))
plot(tree.ring)
acf(tree.ring)
mod.arfima <- fracdiff(tree.ring)
mod.arfima$d

## [1] 0.236507

So we fit fractional noise with parameter $\widehat{d} = 0.23$ (since $\widehat{d} < 0.5$ we think everything is fine and we have a stationary model).  Let's check residuals:
arfima.res <- diffseries(tree.ring, mod.arfima$d)
plot(arfima.res)
acf(arfima.res)

Looks good right?  Well, the issue is that the residuals are spurious white noise.  How do I know?  First, I can test it
Box.test(arfima.res, type = "Ljung-Box")
##
##  Box-Ljung test
##
## data:  arfima.res
## X-squared = 1.8757, df = 1, p-value = 0.1708

Box.test.ls(arfima.res, K = 4, type = "Ljung-Box")
##
##  LS Ljung-Box test; Number of windows = 4; non-overlapping window
##  size = 497
##
## data:  arfima.res
## X-squared = 39.361, df = 4, p-value = 5.867e-08

and second, we know from literature that the tree ring data is in fact locally stationary fractional noise: see Goerg (2012) and Ferreira, Olea, and Palma (2013).
This shows that my -- admittedly -- theoretically looking example, is actually occurring in most real world examples.
Comment: +1, very nice example! I'm interested though are there any real life examples of such series?
Comment: @mpiktas I added an update to the post that should answer your question.
Comment: Thanks for the example. I found though few mistakes in your blog and in the paper of Ferreira et al. In your blog you state that the $\gamma_1(u)=\theta(u)$, when in fact it is $\sigma(u)\sigma(u-1/T)\theta(u)$. Also the sample ACF, i.e. $\hat\gamma_1$ converges to 0, not because $\int_0^1\theta(u)du=0$, but because $\int_0^1\theta(u)\sigma^2(u)du=0$, i.e. $\sigma(u)$ must be chosen in accordance with $\theta(u)$ for the statement to hold. In Ferreira et al, the definition (4) lacks $\varepsilon_t$.
Comment: Your given example says that when we have time-varying model, fitting non-time varying model would lead to incorrect inference. But this is far from saying that each real time series can be be modelled with time-varying model. On the other hand your test can be applied to test for the presence of time-variation. Thanks again for an interesting insight.
Comment: @mpiktas thanks for pointing that out.  I corrected it in blogpost as well.  In that case it just happened to work the same way out since $\sigma(u)^2$ is  even around the mid point $0.5$ (with $T \rightarrow \infty$).

And re practice: I didn't say *every* time series can be modelled that way.  But in practice when someone models it with their favorite stationary ARFIMA model, then they already assume that it is in this class of family. (stationary models are a probability zero subset of locally stationary ones).
Answer: Unit root testing is notoriously difficult. Using one test is usually not enough and you must be very careful about the exact assumptions the test is using.
The way ADF is constructed makes it vulnerable to a series which are simple non-linear trends with added white noise. Here is an example:
library(dplyr)
library(tseries)
set.seed(1000)
oo <- 1:1000  %>% lapply(function(n)adf.test(exp(seq(0, 2, by = 0.01)) + rnorm(201)))
pp <- oo %>% sapply("[[","p.value")

> sum(pp < 0.05)
[1] 680

Here we have the exponential trend and we see that ADF performs quite poorly. It accepts the null of unit root 30% of the time and rejects it 70% of the time.
Usually the result of any analysis is not to claim that the series is stationary or not. If the methods used in analysis require stationarity, the wrong assumption that the series is stationary when it is actually not, usually manifests in some way or other. So I personally look at the whole analysis, not only the unit root testing part. For example the OLS and NLS works fine for non-stationary data, where non-stationarity is in the mean, i.e. trend. So if somebody wrongly claims that the series is stationary and applies OLS/NLS, this claim might not be relevant.
Comment: (+1) not only, but also for the neat way to avoid the loop in the simulation! Not that it matters for the overall conclusion, but: there seem to be 320 out of 1000 *acceptances* ($p>0.05$), no?
Comment: I like dplyr too. For this code it is unnecessary, loading magrittr is sufficient.
Comment: Ah yes, I confused the signs. I fixed the answer accordingly. Thanks for noticing!
Comment: Why didn't you use `sapply(oo, "[[","p.value")` ?
Comment: Well I used it, only with pipe syntax. I like pipes :)
Comment: so you loaded dplyr because you like pipes?
Comment: Ah right, that makes sense
Answer: Example 1
Unit-root processes with a strong negative MA component are known to lead to ADF tests with empirical size far higher than the nominal one (e.g., Schwert, JBES 1989).
That is, if
$$
Y_t=Y_{t-1}+\epsilon_t+\theta\epsilon_{t-1},
$$
with $\theta\approx-1$, the roots of the AR and MA part will almost cancel, so that the process will resemble white noise in finite samples, leading to many false rejections of the null, as the process still has a unit root (is nonstationary).
Below is an example for the ADF test that you mentioned. [Schwert simulates that much more extreme empirical sizes could be generated with less extreme MA structures if you looked at the coefficient statistic $T(\hat\rho-1)$ or the Phillips-Perron test instead, see his tables 5-10.]
library(urca)
reps <- 1000
n <- 100
rejections <- matrix(NA,nrow=reps)

for (i in 1:reps){
  y <- cumsum(arima.sim(n = n, list(ma = -0.98)))
  rejections[i] <- (summary(ur.df(y, type = "drift", selectlags="Fixed",lags=12*(n/100)^.25))@teststat[1] < -2.89)
}
mean(rejections)

Example 2
Processes that are mean-reverting but not stationary. For example, $Y_t$ might be an AR(1) process with AR coefficient less than one in absolute value, but with an innovation process whose variance changes permanently at some point in time ("unconditional heteroskedasticity"). The process then does not have a unit root, but is also not stationary, as its unconditional distribution changes over time.
Depending on the type of variance change, the ADF test will still reject frequently. In my example below, we have a downward variance break, which makes the test "believe" that the series converges, leading to a rejection of the null of a unit root.
library(urca)
reps <- 1000
n <- 100
rejections <- matrix(NA,nrow=reps)

for (i in 1:reps){
  u_1 <- rnorm(n/2,sd=5)
  u_2 <- rnorm(n/2,sd=1)
  u <- c(u_1,u_2)
  y <- arima.sim(n=n,list(ar = 0.8),innov=u)
  rejections[i] <- (summary(ur.df(y, type = "drift"))@teststat[1] < -2.89)
}
mean(rejections)

(As an aside, the ADF test "loses" its pivotal asymptotic null distribution in the presence of unconditional heteroskedasticity.)
Comment: @Glen_b, that (I hope) could be an answer to your first paragraph, but not really to the title of your question - is there a discrepancy or a lack of understanding on my part?
Comment: "That" = Example 1
Comment: It depends on what "unit root" is defined to be. I originally learned it as "root on the unit circle" (a root of modulus 1) but it now seems to be (and in the context of the ADF test relates to) a root of the characteristic polynomial *actually equal to 1*. Even if I have the wrong sense in the title your answer responds to the intended question, so think it's okay.
Comment: My point is probably not clearly phrased: In the title you look for examples of series "without a unit root", whereas the first paragraph (to me) sounds like looking for examples in which rejecting is wrong. My first example is one for the latter case, in which ADF is likely to reject, although the process does have a unit root.
Comment: Ah, sorry, I wasn't thinking about it properly. Yes, strictly it's not in keeping with either interpretation of the title, but it still responds to the broader question in the body. (Titles necessarily are less nuanced, so this isn't an issue.) ... I think it's a very interesting answer, and if anything serves my real purpose better than what the title asks for.


Unity:Stop camera follow player?

Question: I am following Survival Shooter unity tutorial and in the tutorial the down given code is used to make the camera follow the player.The code is working but how can i alter it so that it stops following the player at a given X and Y point.
code
public Transform target;            // The position that that camera will be following.
public float smoothing = 5f;        // The speed with which the camera will be following.

Vector3 offset;                     // The initial offset from the target.

void Start ()
{
    // Calculate the initial offset.
    offset = transform.position - target.position;
}

void FixedUpdate ()
{
    // Create a postion the camera is aiming for based on the offset from the target.
    Vector3 targetCamPos = target.position + offset;

    // Smoothly interpolate between the camera's current position and it's target position.
    transform.position = Vector3.Lerp (transform.position, targetCamPos, smoothing * Time.deltaTime);
}

Answer: Simply stop updating his position:
private bool followPlayer = true;
void FixedUpdate ()
{
    if(followPlayer){
        // Create a postion the camera is aiming for based on the offset from the target.
        Vector3 targetCamPos = target.position + offset;

        // Smoothly interpolate between the camera's current position and it's target position.
        transform.position = Vector3.Lerp (transform.position, targetCamPos, smoothing * Time.deltaTime);
    }
}

Change the value of followPlayer to false and it will stop following
Answer: To determine if the player is at given point, you need to check distance between the player and the point, e.g:
public Transform target;                // player position
public Transform stopingPoint;          // stopping point position
public double tolerance;                // the "radius" of stopping point

private bool followPlayer = true;

    ...

void FixedUpdate ()
{
    if(!followPlayer)
        return;
    followPlayer = Vector3.Distance(target.position, stopingPoint.position) <= tolerance;

    ...

Unity:Stop camera follow player?


Notation: What does $[0,1]^2 \backslash [0,0.5]^2 $ mean?

Question: The context of the of the problem is computing a integral in two variables. So I guess: $[0,1]^2  \backslash [0,0.5]^2 = (0.5,1] \times (0.5,1] $
But I wonder, why one has just not written the latter from the beginning.. not everyone is so secure to just use definitions / notation without worries.
I hope someone knows this and can clarify this.
(The only other place I have seen this notation, was in Python :P )
Comment: Hint: Consider the point $P=(.3,.8)$. Decide whether $P$ is in $[0,1]^2$, in $[0,0.5]^2$, in $(0.5,1] \times (0.5,1]$.
Comment: No it should be the union of three squares, think about it.
Comment: Graphically, this is the unit square (with sides $[0,1]$) with the bottom left corner removed.
Answer: It means
$$
[0,1] \times [0,1] \setminus [0, 0.5] \times [0, 0.5]
$$
where the $\setminus$ means the difference between sets.

(Large version)
The bluish big square is $[0,1]^2$ and the redish small one $[0,0.5]^2$.
The set difference is that upside down $L$.
The inner sides (top side of red and right side of red) are removed, so
there the boundary of the difference is open.
BTW: $(0.5,1]^2$ is the greenishish upper right small square, with left and lower sides open.
Comment: I did not expect the Spanish inquisition.
Comment: I'm trying to make the point that being the "fastest gun in the west" is less important than posting complete answers.
Comment: You could *at least* explain that this is not equal to $(0.5,1]^2$... OP seems to be confused about this and I'm not sure your answer really helps.
Comment: And why did you post your answer before it was complete?
Comment: So do mine, but I at least try to post a complete answer as a first attempt... But I can see this discussion isn't leading anywhere useful.
Comment: I am preparing an image right now.
Comment: I am into Kaizen (the art of incremental improvements). My posts suffer lots of edits.
Comment: Nah, nothing against good critique.
Answer: $[0,1]^2$ is the unit square, while $[0, 0.5]^2$ is the quarter of the square that includes the corner at the origin.  So $[0,1]^2\setminus[0,0.5]^2$ is the other three-fourths of the square, a (roughly) ell-shaped region (or exactly the shape of the L-tromino).  This is distinct from what you've written, $(0.5, 1]\times (0.5, 1]$, which would be $([0,1]\setminus[0,0.5])^2$ — this is exactly like saying that $a^2-b^2$ isn't the same as $(a-b)^2$ in algebra.


How to get the following upper and lower bounds of $E[\sup_{n\geq 0} M_n]$?

Question: Define a martingale $\{M_n\}$ with respect to filtration $\{\mathcal{F}\}_n$ such that $M_n = P(A|\mathcal{F}_n)$ for $n\geq 0$. Assume that $P(A) = 1/2$, $A\in \mathcal{F}_\infty$ and $A$ is independent of $\mathcal{F}_0$. How to show
\begin{equation}
\frac{3}{4}\leq E[\sup_{n\geq 0} M_n]\leq \frac{1+\log 2}{2}?
\end{equation}
I have already shown that
\begin{equation}
P\left(\sup_{n\geq 0} M_n\geq m\right)\leq \frac{1}{2m}.
\end{equation}
It seems that the upper bound can be obtained by doing integral. But, how about the lower bound?
Thanks!
Answer: For the lower bound notice that on $A^{c}$ $\sup_n M_n \geq 1/2$; and on $A$, by Lévy's zero–one law, $\sup_n M_n =1$. Therefore, $$E (\sup_n M_n) \geq \frac{1}{2}\cdot \frac{1}{2} +\frac{1}{2}\cdot 1=\frac{3}{4}$$
From Doob's maximal inequality $ \mathbb{P}(\sup_n M_n \geq t )\leq \min(1,\frac{1}{2t})$ for all $t \in [0,1]$. Therefore,
\begin{align}
E (\sup_n M_n) &\leq \int_{0}^{1}\min(1,\frac{1}{2t})\mathop{dt}  \\
&=\frac{1+\ln (2)}{2}
\end{align}


Evaluation of Indefinite Integral resulting in Hypergeometric Function

Question: I am attempting to derive the result:
$$ \int \left(1+x^n\right)^{-1/m}dx= x\,_2F_1\left(\frac 1m,\frac 1n;1+\frac 1n;-x^n\right)$$
First, I start off with the binomial expansion of the integrand to get:
$$\int\sum_{k=0}^{\infty}\frac{(1/m)_k}{k!}\left(-x^n\right)^kdx  $$
Then, I pull out a $-1$ and interchange summation and integration:
$$\sum_k\int (-1)^k\frac{(1/m)_k}{k!}x^{nk}dx  $$
$$ \sum_k (-1)^k\frac{(1/m)_k}{k!}\frac{x^{nk+1}}{nk+1} $$
$$ x\sum_k \frac{(1/m)_k}{k!}\frac{(-x^n)^k}{nk+1}  $$
So, I'm just right there, but not sure how to express this series in the general form of a hypergeometric series with the two additional Pochhammer symbols.  I even typed this last series into Mathematica, and it returned the Hyper. Function. What am I missing, or how do I transform this last series into the desired form?
Comment: More generally, if the ratio of two consequtive terms is a rational function of $k$, the series can always be reduced to a generalized hypergeometric one.
Comment: Yes! I had just figured that out
Comment: You can use the identity $\frac{(\gamma)_k}{(\gamma+1)_k} = \frac{\gamma}{\gamma+k}$ to simplify the sum.
Comment: Interesting @O.L. I'm finding that this function and series comes up everywhere
Comment: What are n,m? integers or real numbers?
Answer: Deriving from integral approach is easier:
\begin{align}
\int(1+x^n)^{-\frac{1}{m}}~dx
&=\int_0^x(1+t^n)^{-\frac{1}{m}}~dt+C\\
&=\int_0^{x^n}(1+t)^{-\frac{1}{m}}~d(t^\frac{1}{n})+C\\
&=\dfrac{1}{n}\int_0^{x^n}t^{\frac{1}{n}-1}(1+t)^{-\frac{1}{m}}~dt+C\\
&=\dfrac{1}{n}\int_0^1(x^nt)^{\frac{1}{n}-1}(1+x^nt)^{-\frac{1}{m}}~d(x^nt)+C\\
&=\dfrac{x}{n}\int_0^1t^{\frac{1}{n}-1}(1+x^nt)^{-\frac{1}{m}}~dt+C\\
&=x~_2F_1\left(\dfrac{1}{m},\dfrac{1}{n};1+\dfrac{1}{n};-x^n\right)+C
\end{align}
Comment: Ah cool! I didn't think of doing it this way. Thank you
Answer: I was in the end able to derive the correct expression as...
$$\frac{(1/n)_k}{(1+1/n)_k}=\frac{\frac1n(\frac1n+1)(\frac1n+2)\cdots(\frac1n+k-1)}{(1+\frac1n)(1+\frac1n+1)(1+\frac1n+2)\cdots(\frac1n+1+k-2)(\frac1n+1+k-1)} =\frac{1}{nk+1}$$


Django fails to find static files served by nginx

Question: I know this is a really noobish question but I can't find any solution despite finding the problem trivial.
I have a django application deployed with gunicorn. The static files are served by the nginx server with the following url : myserver.com/static/admin/css/base.css. However, my django application keep looking for the static files at myserver.com:8001/static/admin/css/base.css and is obviously failing (404).
I don't know how to fix this. Is it a django or an nginx problem ? Here is my nginx configuration file :
server {
    server_name myserver.com;

    access_log off;

    location /static/ {
        alias /home/myproject/static/;
    }

    location / {
        proxy_pass http://127.0.0.1:8001;
        proxy_set_header X-Forwarded-Host $server_name;
        proxy_set_header X-Real-IP $remote_addr;
        add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"';
    }
}

Thanks for the help !
Answer: I don't know why you have this in your configuration. It doesn't do anything.
        proxy_set_header X-Forwarded-Host $server_name;

Anyway, you are not passing on the Host header, which is the most likely reason I can think of why your URLs are being mangled.
Try setting that:
        proxy_set_header Host $http_host;

Comment: The first line you mentionned is part of the nginx configuration file recommended in the digitalocean tutorial, I just copied/pasted it. What you have suggested didn't change anything. Is it an nginx of django problem ? Should nginx serve the files on port 8001 or should django serve files from myserver.com instead of myserver.com:8001 ?
Answer: First ensure that you have debug disabled in your settings.py
DEBUG = False
Check your path to static files and url (ex.)
`STATIC_URL = '/static/'
STATICFILES_DIRS = {
  "/home/myproject/static/",
}`
Define your static url in nginx (ex):
location /static/ {
 alias /home/myproject/static/;
 expires 1d;
}

Answer: Is not django problem at, but nginx proxy configuration
The problem is quite similar to this one:
(I paste link directly as it is an internal link on serverfault, don't want to duplicate answers)
Removing port from nginx redirect
Maybe even adding proxy_redirect off; to the location configuration does the trick.


synchronized object set to null

Question: I have two threads Thread1 and Thread2
//Within Thread1
synchronized(obj1)
{
    obj1 = null;
}

//Within Thread2
synchronized(obj1)
{
    do something
}

If jvm first executes thread1 and sets obj1 to null, then will thread2 see that change immediately or will it take time and jvm could still run the thread2 synchronized block since obj1 is not yet null?
Comment: @KorhanÖztürk He couldn't try himself, any type of concurrency related issue is non deterministic.  These types of comments are extremely frustrating when the context isn't known.
Answer: This will almost certainly break the synchronization abstraction -- I wouldn't be confident that thread2 will see the change immediately.  You should never change the reference of the object you're synchronizing on, much less set it to null, which will cause a NullPointerException on any further attempts to synchronize on it.
Answer: First let me emphasise that modifying a variable that is used for synchronization is a terribly bad thing. obj1 should be final and never be touched if it is used as a monitor.
That being said, back to your question:
If JVM first executes Thread1, it synchronizes on obj1, sets it to null and the thread exits. The second thread wants to synchronize on obj1, NullPointerException will be thrown. Because the modification of obj1 was made in synchronized block, it is guaranteed that Thread2 will see updated value (so: NullPointerException is guaranteed).
If Thread1 is interrupted after obtaining the lock on obj1 but before clearing the reference, Thread2 will lock on obj1 and wait until Thread1 finished. Then it will successfully enter the monitor because the object previously referenced by obj1 still exists.
Comment: since obj1 is being used in the synchronized condition and not in the synchronized block, is it not possible that both the threads try to synchronize at the same time and thread1 enters first and thread2 caches the value of obj1. when thread1 exits thread2 takes the value of obj1 from the cache and enters the synchronized block and sees the change within the synchronized block
Comment: @Tomsaz I didn't get this statement of yours _If Thread1 is interrupted after obtaining the lock on obj1 but before clearing the reference, Thread2 will lock on obj1 and wait until Thread1 finished_ Now first of all we interrupts thread only when they are blocked and anyway if they are not blocked the interrupting them has no effect, right? Basically I never see a case where thread1 will relinquish the lock without completeing the synchronized block or without wait() getting called on that lock itself. IOW, when and why would thread2 get the lock but would still wait for thread1 to finish.
Comment: The `NullPointerException` is *not* guaranteed. Performing a write in a `synchronized` block only guarantees visibility for threads subsequently entering a `synchronized` block for the same object, but not for the read happening *before* entering the `synchronized` block. So without other synchronization, the second thread may throw a `NullPointerException` or not, that's unpredictable. Only when it dereferences the variable again within the `synchronized` block, the `NullPointerException` is guaranteed.
Answer: synchronized synchronizes on the object, and not the reference. By setting obj1 (a reference) to null, thread2 can't synchronize on the object formerly pointed to by obj1, you'll get a NullPointerException instead.
Answer: A quick fix is to make the object a simple array of 1 element and refer to the array for synchronization, e.g.,
Object[] obj1 = {null};
The element can be null without impacting the existence of the array.  Granted, this still breaks the "rule" of not using the object itself in synchronization, but unless your code complicates matters elsewhere, this quick fix should work as expected.
Answer: The change is immediate. When Thread 1 "owns" the lock, it can change the value of obj1 at will. Thread 2 has to wait until Thread 1 releases the lock. It will definitely see obj1 == null

synchronized object set to null


Function that has per MacLaurin series $\sum_{n=0}^\infty \frac{x^{4n+1}}{4n+1}$

Question: What is the function of the MacLaurin series:
$$\sum_{n=0}^\infty\frac{x^{4n+1}}{4n+1}$$
I think is a complex function, but I have no idea how to start. Is it already discovered?
Comment: Welcome to Mathematics SE. Take a [tour](https://math.stackexchange.com/tour). You'll find that simple "Here's the statement of my question, solve it for me" posts will be poorly received. What is better is for you to add context (with an [edit](https://math.stackexchange.com/posts/4719032/edit)): What you understand about the problem, what you've tried so far, etc.; something both to show you are part of the learning experience and to help us guide you to the appropriate help. You can consult [this link](https://math.meta.stackexchange.com/q/9959) for further guidance.
Comment: This series has a rather simple expression in terms of inverse trigonometric and inverse hyperbolic functions, so I'd recommend try to find it yourself. If you are not able to solve it, post your efforts and you'll probably get help.
Answer: This function is $$f(x) =\int_0^x\frac{1}{1-t^4}dt.$$ Why? Give it a try.
Comment: Yeah, i Know. I give this form to not make too easy for the guy of the question.
Comment: Obtaining a closed form is not difficult. See my answer.
Answer: See that
$$f'(x)=\sum_{n=0}^\infty x^{4n}$$
This is just a geometric series, with common ratio $x^4$ and hence provided $|x^4|<1$ we get
$$f'(x)=\frac{1}{1-x^4}$$
Hence
$$f(x)=\int_0^x f'(s)\mathrm ds=\int_0^x\frac{1}{1-s^4}\mathrm ds$$
As given by Guillermo.
Introduce a partial fraction decomposition:
$$\frac{1}{1-s^4}=\frac{1}{(1+s^2)(1-s^2)} \\ =\frac{A}{1+s^2}+\frac{B}{1-s^2}$$
We see that
$$(1+s^2)B+(1-s^2)A=1 \\ B+A+s^2(B-A)=1$$
This means that we must have $B=A=1/2$. Therefore
$$f(x)=\frac{1}{2}\int_0^x\frac{1}{1+s^2}\mathrm ds+\frac{1}{2}\int_0^x \frac{1}{1-s^2}\mathrm ds$$
Which, assuming $x\in(0,1)$, is
$$\boxed{f(x)=\frac{1}{2}\big(\arctan(x)+\operatorname{arctanh}(x)\big)}$$


How can I filter an index view using REST?

Question: I have a custom content type called 'Regions', which simply has a title field. Example values are: Asia, North America, Ocenia, etc.
I've set up a view for this list and a REST export for it, so /regions gives me a simple list:
[{"title":"Asia"},{"title":"North America"},{"title":"South America"},{"title":"Ocenia"}]
I want to filter the results, so I added a contextual filter on the title field, making /regions/Asia show only Asia:
[{"title":"Asia"}]
How do I implement a wildcard search? Something like as should match Asia and amer should match both North America and South America. I'd like to do something like /regions?title=Asia
I referred to this guide on setting up contextual filters, but the following doesn't seem to work for me:

This query works as a SQL LIKE statement so you can send just a piece of the name and Views will try to find all records LIKE that argument, example, I have a brand called Land Rover but if I just send Land as an argument it will work http://dev-cars-api.pantheonsite.io/api/cars/Land

The URL in the quote is no longer online, so I can't check if it actually works. For me, only entering a full, matching item title works. I can't even specify a title with spaces, so /regions/North+America is also blank for me.
My Drupal version is 8.4, running on PHP 7.1.
Answer: The solution is to add a search filter to the view.
In the view settings, under Filter Criteria, you'll see Content: Published (= Yes) and Content: Content type (= Regions) (or whatever your view is for).

Click add. In that box that shows all the fields you can add, type Search: Search Keywords.
Tick Expose this filter to visitors, to allow them to change it.
(optional) Rename the Filter Identifier from keys to query or terms or whatever you see fit.
Save the view.

You'll then be able to make a GET http://example.com/api/regions/?_format=json&keys=my+search+string!


Table body is comming from Html but not from Javascript

Question: I am creating a table from JavaScript tag and second one from method by using document.createElement() .There are two ways by which I am creating One by using Javascript.
var dropDownTable = document.createElement('table');
    dropDownTable.id = "myTable";
    //dropDownTable.className = "myTable";
    var headerTr = document.createElement('tr');
    headerTr.className = 'header';
    var innerTr = document.createElement('tr');
    var innerTd = document.createElement('td');
    innerTr.appendChild(innerTd);
    dropDownTable.appendChild(headerTr);
    dropDownTable.appendChild(innerTr);

Here I am getting this as outer.html
Outer HTML

One by using HTML tag in Javascript.
var myTable = '
' + '

' + '

' + '
';

Here I am getting this as outer.html
Outer HTML

I am wondering where I am creating tbody tag. Though I am using the same css both but different outer.html is my question. Please help me in this.
CSS
#tdiv {
    height: 30%;
    overflow-y: auto;
}

tbody {
    display: block;
}

tbody {
    max-height: 150px;
    overflow: auto;
}

#myTable {
    border-collapse: collapse;
    width: 30%;
    border: 1px solid #ddd;
    font-size: 18px;
    display: none;
    margin-top: -12px;
}

#myTable th,
#myTable td {
    text-align: left;
    padding: 12px;
    width: 10%;
}

#myTable tr {
    border-bottom: 1px solid #ddd;
    order-top: 1px solid #ddd;
}

#myTable tr.header,
#myTable tr:hover {
    background-color: #f1f1f1;
}

#myInput:focus+#myTable {
    display: block;
}

#myTable:hover {
    display: block;
}

Answer:
I am wondering where I am creating tbody tag.

The browser creates it implicitly.
https://www.w3.org/TR/html5/tabular-data.html#the-tbody-element:

Tag omission in text/html:
  A tbody element's start tag may be omitted if the first thing inside the tbody element is a tr element, and if the element is not immediately preceded by a tbody, thead, or tfoot element whose end tag has been omitted. (It can't be omitted if the element is empty.). A tbody element's end tag may be omitted if the tbody element is immediately followed by a tbody or tfoot element, or if there is no more content in the parent element.


Finding "weak ties" in network data

Question: So I am working on a new project looking at formal and informal networks between businesses in the same industry. Namely, I am looking at joint ventures, fractional acquisitions, minority share ownership, and board of director relationships between companies. I want to see if I can identify the occurrences of "weak ties" (Granovetter, 1973), meaning ties between densely interconnected clusters. However, I was not sure if software was available to do that type of cluster and then weak tie identification? I am pretty familiar with the ERGM models and the Statnet packages, but I have not seen an functionality for this in those packages. I might be able to use a latent space model (Handcock, 2006) to identify clusters and then eyeball the weak ties, but that seemed a bit arbitrary--though I might have to resort to that. Does anyone know of any better software packages or code for cluster/community detection and then the identification of weak ties?
Answer: A logical candidate is edge centrality, in igraph:
<code>edge.betweenness.estimate(graph, e=E(graph), directed = TRUE, cutoff, weights = NULL)
</code>
Comment: Oh that is brilliant. I had not considered edge.betweenness, but it makes total sense. Thanks micans.

Finding "weak ties" in network data


Construct $\mathbb{Z}(X)$

Question: Is there any way to construct the ring $\mathbb{Z}(X)$ in a computer algebra system (e.g. MAGMA, Sage), where the parameter $X$ is adjoined to $\mathbb{Z}$.
(Note that this is not a field, so I cannot use the command for computing function field of the integral domain $\mathbb{Z}[X]$.)
Thanks in advance.
Edit
Thanks to henning-makholm and sharding4 for helping to ask correct question.
Comment: @user5325: I don't understand what you mean by "adjoining of a parameter", if you want that to produce something that is neither $\mathbb Z[X]$ nor the field of rational functions over $\mathbb Z$. Can you explain what the definition of the ring you want to get is, or give an example of an element of the ring that has no inverse?
Comment: If the thing you're looking for is not a field, then what _is_ it? How does it differ from the field of fractions of $\mathbb Z[X]$? (The elements of that fraction field is what a "rational function" usually means).
Comment: @HenningMakholm, I agree, the set of rational functions **will be** a field, as I can take $f(X)=1$ and $g(X)=2$, thus $\frac{f(X)}{g(X)}=\frac{1}{2}$ will be in this set and thus eventually we can prove that it will be a field!

But as I said above, I want adjoining of a parameter.
Comment: e.g. the element $\frac{1}{X}$ will be in this ring, however the element $\frac{1}{2}$ will not be here. OK, Llet me speak from the commutative algebra point of view:
This is the localization of the ring $\mathbb{Z}[Z]$ at the element $X$. I was thinking that computationally these two are the same!
Comment: $\mathbb{Z}\otimes_\mathbb{Z} \mathbb{Q}(X)\cong \mathbb{Q}(X)$
Comment: @sharding4, thanks! So silly of me!
Comment: @HenningMakholm, what I am actually looking at is adjoining of a parameter $X$ to $\mathbb{Z}$. Is it not same as rational functions over $\mathbb{Z}$?
Comment: @user5325 There is a package for Macaulay2 that allows you to do some things with local rings.
Comment: @FredrikMeyer, I know only one package in Macaulay2, namely [LocalRings](http://www.math.uiuc.edu/Macaulay2/doc/Macaulay2-1.9.2/share/doc/Macaulay2/LocalRings/html/). But this is for localization at **maximal** ideals. Is there any other package in Macaulay2? Any other CAS?
Answer: The ring you are looking for is the Laurent Polynomial ring over $\mathbb{Z}$, namely $\mathbb{Z}[x,x^{-1}]$. This can be constructed as follows:
$$\frac{\mathbb{Z}[x][y]}{\langle xy-1\rangle}$$
This you can compute in almost all CASs.
Hope this helps.
-- Mike
Answer: I dont know how to remove answer or mark it as non-answer (without deleting it)!
The $\mathbb{Z}(X)$ is localization of $\mathbb{Z}[X]$, is absolutely correct. However the underlying multiplicative set is not $\{X,X^2,\ldots\}$, but $\mathbb{Z}$.
When you invert all non-costant polynomials, the ring you would get is $\mathbb{Z}(X)$ .
e.g. the element $\frac{1}{1+X}$ is in the ring and so is $\frac{1}{2+X}$, but $\frac{1}{2}$ is not there.
From computation point of view, I donno! Any pointers?
Hope this clarifies!
-- Mike

Construct $\mathbb{Z}(X)$


Possible to set the height of the textbox of an input type=file?

Question: Basically I have an <input type="file" /> that is inside of a div and I would like to make the textbox portion of that input fill the entire div.  Ideally the button part would be outside of the parent div and not clickable.  I have been able to set the width using size but I can't seem to set the height.  You can see an example of what i'm talking about here: http://jsfiddle.net/LrpFn/1/
I found some info on styling input type=file, but most of it is related to styling the button.  Is it possible to set the height of the textbox?
My end goal is to create a div where people can drag and drop files, so my plan is to fill this entire div with the text area of the input and then set opacity to 0.  I'm open to other suggestions as well...
Answer: Have you considered using file drop? Does not support old browsers, but does not require any input at all.
http://www.html5rocks.com/en/tutorials/dnd/basics/
Answer: There isn't much you can do to style a input[type="file"].
However, you can always place a dummy input there (which you can style as you please) and place the correct input positioned over the top, with opacity: 0 so you can't see it, but clicks on the dummy element activates the correct one.
Comment: Yeah, that's exactly what I'm trying to do.  The input I want is 300px tall though...  The event that I'm using now is `onchange`, I don't really care about clicks.  Just when the text changes.


Gsub replace the last space of an unknown length of the last string

Question: I have this data which contains tv series data
"!Next?" (1994)                     1994-1995
"#1 Single" (2006)                  2006-????
"#1 Single" (2006) {Cats and Dogs (#1.4)}       2006
"#1 Single" (2006) {Finishing a Chapter (#1.5)}     2006
"#1 Single" (2006) {Is the Grass Greener? (#1.1)}   2006
"1941" (2009) {(#1.9)}                  ????
"1942" (2011)                       2011-????

I need to divide this into series name| production date|episode name| year of release
The episode name is uneven(it might or might not be present) as can be seen above for the case of 1942(last record).Hence I would be counting characters from the last character.
Currently, I have done name| production date| but for to add a pipe(|) before the year of release is a bit tedious.
I want an output like this
"!Next?" |1994|                     |1994-1995
"#1 Single" |2006|                  |2006-????
"#1 Single" |2006| {Cats and Dogs (#1.4)}       |2006
"#1 Single" |2006| {Finishing a Chapter (#1.5)}     |2006
"#1 Single" |2006| {Is the Grass Greener? (#1.1)}   |2006
"1941" |2009| {(#1.9)}                  |????
"1942" |2011|                       |2011-????

I have got the first 2 pipes using sub but not able to get the 3rd one.
please if anyone could help
Comment: Based on the data you shared here, you could simply gsub the  `}`  with a `} |` and it should place a pipe after the episode name...and if there is no episode name, the on on the production date will serve as a divider between it and the air date.
Comment: @bethanyP but the thing is all records dont have a `}` in the data...thats the problem...hence I thought of doing it from the last character...for example the last record.. If u could help me create a regex with the help of the last character,for ex using `$`
Answer: You can use backreference for this kind of tasks (input is the vector of strings to be modified):
gsub(pattern = "([0-9?-]+$)",
     replacement = "|\\1",
     x = input)

Basically it searches for the maximum string located at the end that consists from digits, "?" and "-"; takes that string and replaces with its modified copy by preceding "|".


Question about integral the form $\frac{dx}{y}$ on elliptic curve

Question: I've learn that for every elliptic curve $E$ we can define a map $\phi:E \rightarrow C$ by integral the form $\frac{dx}{y}$ from a fixed point $P$ to any $z \in E$ along some curve.Then we quotient the free abelian group generated by these two complex numbers: $\int_{A} \frac{dx}{y}$ and $ \int_{B} \frac{dx}{y}$ to make sure the map is well-defined,where $A,B$ are two generators of the fundamental group $\pi_{1}(E)=\mathbb{Z} \bigoplus \mathbb{Z}$.
The following are my questions
1)Why this two complex numbers are $\mathbb{R}-$linearly independent?
2)Why the map $\phi$ is injective?
I've heard that we can solve this two problems by using homology theory.Is there any elementary approach?
Thank you for your answer.
Comment: Another approach to 1) is by using Riemann's bilinear relations.
Answer: Assuming you work over $\mathbb C$, i.e. with Riemann surfaces, here are some possible complex-analytic approaches.

Riemann's bilinear relations.

Let $\mathcal R$ be a smooth Riemann surface of genus $g$ and $A_1,B_1,...,A_g,B_g$ a canonical basis of cycles. For any two closed differentials $\nu,\eta$ on $\mathcal R$ we have
$$
\int_{\mathcal R}\nu\wedge\eta=\sum_{i=1}^g\left(\oint_{A_i}\nu\oint_{B_i}\eta-\oint_{A_i}\eta\oint_{B_i}\nu\right).
$$
The proof is essentially Stokes' theorem.
In particular if $\mathcal R=E$ is a (smooth) elliptic curve, $A,B$ a canonical basis of cycles on $E$ then (denoting $\omega_A=\oint_A\frac {dx}y$ and $\omega_A=\oint_B\frac {dx}y$)
$$
0<\int_E\frac{dx\wedge d\overline{x}}{|y|^2}=Im(\omega_A\overline{\omega_B})
$$
implying that $\omega_A,\omega_B$ are $\mathbb R$-linearly independent.

Abel's Theorem.

If $\int_P^{z_1}\frac{dx}y=\int_P^{z_2}\frac{dx}y$ for some $z_{1,2}\in E$ (equality modulo periods $\omega_A,\omega_B$) then by Abel's theorem there is a meromorphic function on $E$ with exactly one pole at $z_2$ and one zero at $z_1$; this would establish a bi-holomorphism with the Riemann sphere, a contradiction.
Abel's theorem in general asserts that principal divisors are characterized by vanishing of the Abel map (period map). In the elliptic case you can directly prove the claim above by using elliptic theta functions; namely for any $c\not=0$ the function (wlog $\tau:=\omega_B/\omega_A$ is in the upper half-plane)
$$
f(z)=c\frac{\vartheta(\int_{z_1}^{z}dx/y+\frac {1+\tau}2;\tau)}{\vartheta(\int_{z_2}^{z}dx/y+\frac {1+\tau}2;\tau)},\qquad\vartheta(z;\tau)=\sum_{n\in\mathbb Z}\exp(\pi i n^2\tau+2\pi in z),
$$
would be well defined (by the quasi-periodicity properties of $\vartheta$) and would have only one zero (at $z_1$) and one pole (at $z_2$) and so would establish a bi-holomorphism between $E$ and the Riemann sphere, a contradiction.


JavaScript Regex, where to use escape characters?

Question: The regex allows chars that are: alphanumeric, space, '-', '_', '&', '()' and '/'
this is the expression
[\s\/\)\(\w&-]

I have tested this in various online testers and know it works, I just can't get it to work correctly in code. I get sysntax errors with anything I try..  any suggestions?
var programProductRegex = new RegExp([\s\/\)\(\w&-]);

Comment: No need to escape parentheses in a character class. i.e. use: `/[-\s\/()\w&]/` and remember that a dash must be escaped except when at the beginning or end of the class. See: [regular-expressions.info](http://www.regular-expressions.info/) for a great tutorial.
Comment: I noticed in the jQuery.uni-form.js file that forward slashes inside a character class are not being escaped, and yet the code works fine. Is it possible that escaping forward slashes in a character class is optional? I'd like to know for the benefit of the TextMate Javascript bundle, used also by Sublime Text 2.
Comment: @ScottLahteine I think (never found any documentation on this) that only in RegEx literals `/slashes\/must/` be escaped. When using the `RegExp` constructor it does not have be be escapted
Answer: You can use the regular expression syntax:
var programProductRegex = /[\s\/\)\(\w&-]/;

You use forward slashes to delimit the regex pattern.
If you use the RegExp object constructor you need to pass in a string. Because backslashes are special escape characters inside JavaScript strings and they're also escape characters in regular expressions, you need to use two backslashes to do a regex escape inside a string. The equivalent code using a string would then be:
var programProductRegex  = new RegExp("[\\s\\/\\)\\(\\w&-]");

All the backslashes that were in the original regular expression need to be escaped in the string to be correctly interpreted as backslashes.
Of course the first option is better. The constructor is helpful when you obtain a string from somewhere and want to make a regular expression out of it.
var programProductRegex  = new RegExp(userInput);

Comment: why do you have to put one at the end, is that basically a delimeter?
Comment: Note also that you do not need to escape`()` parentheses in a character class.
Comment: @ridgerunner: Yes, and neither the forward slashes, but I kept them to maintain consistency with the original pattern.
Comment: Nice tip with the double slashes.  (boo for Javascript for being as annoying as Java in this regard)
Comment: Thank you! I have been looking for this explanation for a while!
Answer: If you are using a String and want to escape characters like (, you need to write \\( (meaning writing backslash, then the opening parenthesis => escaping it).
If you are using the RegExp object, you only need one backslash for each character (like \()
Answer: Enclose your regex with delimiters:
var programProductRegex = /[\s\/)(\w&-]/;

Comment: Probably because you're passing a RegExp literal into a RegExp constructor. If you have a RegExp literal, using the RegExp constructor isn't necessary.


Javascript Countdown Timer with User input

Question: I am trying to create a countdown timer where the user can input any combination of day, hour, minute, and seconds values and have it countdown to completion. I feel like I've got all the pieces but after a week of trying to solve this issue, I need help. I shuffle code around all with varying effects. Basically I feel like I'm missing a way to format the input data in a way I can use to subtract from the current date, but honestly I have no idea. Any input would be helpful.
Javascript:
function start() {
  var countdownTimer = setInterval('timer()', 1000);
}

function timer() {
  var d = parseInt(document.getElementById("days").value, 0);
  var h = parseInt(document.getElementById("hours").value, 0);
  var m = parseInt(document.getElementById("minutes").value, 0);
  var s = parseInt(document.getElementById("seconds").value, 0);

  var now = new Date();
  var date = now.getTime();

  addDay = now.setDate(now.getDate() + d);
  addHour = now.setHours(now.getHours() + h);
  addMinute = now.setMinutes(now.getMinutes() + m);
  addSecond = now.setSeconds(now.getSeconds() + s);

  var then = new Date(addHour + addMinute + addSecond);

  if(d > 0 || h > 0 || m > 0 || s > 0){
    var final = then - date;
    var dd = Math.floor(final/ (1000 * 60 * 60 * 24));
    var hh = Math.floor((final / (1000 * 60 * 60)) % 24);
    var mm = Math.floor((final / 1000 / 60) % 60);
    var ss = Math.floor((final / 1000) % 60);

    document.getElementById("display").innerHTML = "Time Remaining: " + dd + "D     " + hh + "H " + mm + "M " + ss + "S";

    document.getElementById("message").innerHTML = then;

    if (final < 0) {
      clearInterval(countdownTimer);
      document.getElementById("message").innerHTML = "Expired";
    }
  }else{
    document.getElementById("display").innerHTML = " ";
    document.getElementById("message").innerHTML = "Countdown Not Started";
  }
}

HTML:

  <button id="Start" onclick="start();">Start Timer</button>

  D:<input type="text" id="days" value="0" />
  H:<input type="text" id="hours" value="0" />
  M:<input type="text" id="minutes" value="0" />
  S:<input type="text" id="seconds" value="0" />

Answer: If your timer is not based on date but on a given number of days, hours, minutes and seconds, why involve dates at all ? How about
function timer(){
    var d = parseInt(document.getElementById("days").value, 0);
    var h = parseInt(document.getElementById("hours").value, 0);
    var m = parseInt(document.getElementById("minutes").value, 0);
    var s = parseInt(document.getElementById("seconds").value, 0);

    var current = ((d * 86400) + (h * 3600) + (m * 60) + s);  //the current time left in seconds
    if (current > 0) {
        //take one second away, and rerender the seconds split into d, h, m, and s in the html, which you will reuse next time timer() runs
    } else {
        //expired
    }
}

Comment: Thank you. I had considered that option and that's what I will use going forward. I initially wanted to try and take it from the current date more as a challenge, but for the practical purpose for which I need it, this is more than sufficient. Thanks again.


How to update Neural Net Parameters on fresh new data

Question: [ I asked this earlier on DS SE: here
but the question didn't receive sufficient attention there. I ask it here because I'm looking for a practical answer with some theoretical justification.
]
I have a large dataset $D_1$.
I have a Feed-forward deep Neural Network $N$, with hidden layers, that I trained on $D_1$, using MSE Loss and standard back-propagation and obtained the parameters.
Now, I know the network architecture and the learned parameters.
Next, I obtained a new batch of data, $D_2$ - it is a large dataset similar to $D_1$.
I want to again learn the parameters of $N$, as though I had trained it from scratch on $D_1 \cup D_2$, but only by training on $D_2$ and using the earlier known parameters on $D_1$.
Is this some standard problem? How can I do this?
I can obtain basic info about $D_1$ such as size of the dataset; but training is expensive.
Answer: Yes, this is a very standard problem and most commonly occurs with images/text, but clearly could occur with other types of data. For those types of data it's the most common approach, while for tabular data it's rare due to not so much data being similar to each other (but there are examples of people trying it successfully).
One common idea is to initialize the same model (or with a different final 1-2 layers if the task to be solved is different - e.g. pre-trained on ImageNet to classify images into ImageNet categories, but now being used to classify cat vs. dog on new data), load the old weights and then re-train. You might only train the last few layers (if the task is the same these are even already trained and you might only train these with a lowish learning rate). Or you might first train those and then the earlier layers. You might also wish to use increasingly lower learning rates the further the layers are from the final output. See e.g. here for a discussion.
Answer: What you're describing is essentially approached as incremental learning or online learning, where a model is updated as new data comes available without starting from scratch. In your particular case, you've already trained a model on dataset D1 and have a new batch of data, D2, and you want to update your model to perform as if it had been trained on the combined dataset D1 U D2, only using D2 for further training.
There are a few approaches you could consider:
Fine-tuning: Continue the training process with the additional data. This would involve using the parameters learned from D1 as the starting point and training the network further on D2. You would typically want to use a smaller learning rate to make sure that the model does not deviate too much from what was learned initially. Additionally, it's sometimes beneficial to freeze certain layers to preserve learned features and only train the latter layers on the new data.
Elastic Weight Consolidation (EWC): This is a technique to mitigate catastrophic forgetting which can happen when a neural network forgets the knowledge about previous data when it is trained on new data.
Whether any of these methods would give you a result equivalent to training on D1 U D2 "from scratch" is not guaranteed and would be problem-dependent. It would also be affected by the size and distribution of D1 and D2.
Theoretical Justification:
In terms of a theoretical proof, this is challenging because equivalence would depend on the optimization path taken by the neural network which is influenced by many factors including loss landscape, learning rates, batch sizes, and so forth.
However, the theoretical justification for these methods often comes from Bayesian learning principles and the theory of transfer learning. The idea is that the parameters learned from D1 form a prior distribution for the parameters that you want to learn for D1 U D2. When you start training on D2, you're updating this prior with new evidence. This is conceptually similar to Bayesian updating of belief distributions.
Further notes:

Consider the size of D2 relative to D1. If D2 is much smaller, its impact on the model might be limited unless you apply techniques like oversampling or data augmentation.

Monitor overfitting. Since the model is already trained on D1, it might overfit D2 more quickly.
Comment: You can use math typesetting with mathjax, which would make this easier to read. https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Answer: So far, there is no theoretically justified or standard way to train a typical neural network on new data without the old data that is equivalent to training on the datasets' union.
Closest today is a Bayesian modelling approach, but even then catastrophic forgetting remains, and that is then Bayesian Neural Networks (BNNs), rather than typical artificial neural networks (ANNs).
This can only occur when the parameter space is

identifiable [ref 1], meaning that the model is able to represent the observed process and is typically meant as a single parameter is point-identifiable from the information available in the observations, and
"consistent" or is a "well behaved" parameter space with a "well
behaved" update function that can converge to the true parameter.

This is discussed at length in [ref 2, Ch.6--9], specifically with regard to Bayesian modelling. Unfortunately, this is not open access.
What you are seeking in such a case is a mathematical and algorithmic formalization of inductive reasoning and inference, which has been of great interest for centuries. The Bayesian modeling approach tends to be involved in the probabilistic mathematical induction. Some relevant books of interest include ref 3 Ch. 5 & ref 4 Ch. 2.
Engineering Approaches
Theory aside, there are plenty of engineering approaches.
Given how ANNs are trained through typical back-propagation and stochastic gradient descent (SGD), having the weights of a trained ANN is typically not enough to properly adjust those weights given new data without having more information about the prior train run, such as the state of the SGD method including the learning rate or other parameters and state of the optimizer used.
As others have mentioned, you can approach this from an online learning or incremental learning fashion, however those subfields also do not have a sound theoretic solution (as requested from the bounty).
To be honest, why SGD works is still somewhat of a mystery and the reality is that there is not a sound way to use SGD (afaik) to update your weights without all of the prior training data along with the new data.
The only way you can get this, is if you constrain the space of the parameters (weights) learned through a fashion similar to Bayesian modelling. BNNs are one potential way to explore being able to update given only the most recent data, but even then there is difficulty.
In the end, the transduction approach of "re-train the model on all the data available" is the current standard.
"Hot start": Use prior weights at start of training
Issue is, as mentioned before, the initialization weights alone will not result in an equivalent model as if trained on the union of the datasets. This is mostly due to SGD being stochastic and unconstrained. If your optimization method has a temperature setting or even in general, the optimization method may quickly travel away from the initial weights, even if the new data is rather similar to the old data, and you'd rather explore further around the old local minima given the new data. This is where having the parameters and final state of the optimizer may aid in exploring around the prior local minima, rather than just providing the initial weights.
Freeze (part of) ANN then Fine-Tune
As others mentioned, freezing the weights of the trained network is doable and then training only a subset of the network or a new ANN appended to the end of the frozen one is one approach, however this is an engineering approach that has nuance in how to be done appropriately.
You could explore having an ANN frozen from $D_1$ and then rather than only having a trainable ANN at the end for fine-tuning, you could have a new ANN, say a clone of the old network, that is trained in parallel. The new model is then trained on $D_2$ as raw input along with that input run through the frozen network. This would avoid loss of possibly new relevant information in $D_2$ that was not in $D_1$.
Information Theoretic Perspective on Frozen Pre-trained Models
When you freeze the weights of the ANN trained on the first training data $D_1$, then train a "fine-tuning" layer or ANN at the end of that frozen network, meaning the penultimate layer or some earlier layers serve as the input to the fine-tuning ANN rather than the task output, you are limiting the amount of new information that is able to be learned from the new data $D_2$. This is because the frozen ANN serves as a filter of the input data.
This is related to the data processing inequality. The information you care to learn must be available in the observations (the training data), and without providing any further information, the only information to be learned to solve the task is from that training data.  When you train the ANN on $D_1$ and freeze it, the ANN was optimized for that data, and thus any new information in $D_2$ that is relevant can be filtered out when run through this network as in the fine-tuning approach.
This is the justification for the fine-tune ANN to be given both the raw data and the data run through the frozen ANN. However, this still will not be equivalent to running on all of the data together, as done in transduction.

Further Reading
Kevin Patrick Murphy's Probabilistic Machine Learning Books are open access and can be useful to get a grasp of different approaches and nuance to optimization of ANNs, as well as different approaches to address the problem of updating an ANN.

Introduction: https://probml.github.io/pml-book/book1.html

I Foundations: Ch. 8 Optimization

Advanced Topics: https://probml.github.io/pml-book/book2.html

V Discover: Ch. 32 Representation Learning

References

Lewbel, Arthur. 2019. "The Identification Zoo: Meanings of Identification in Econometrics." Journal of Economic Literature, 57 (4): 835-903. Open access preprint: https://www.bc.edu/content/dam/bc1/schools/mcas/economics/pdf/working-papers/wp957.pdf
Ghosal, Subhashis, and Aad Van der Vaart. Fundamentals of nonparametric Bayesian inference. Vol. 44. Cambridge University Press, 2017. Closed Access Google Scholar
Li, Ming, and Paul Vitányi. An introduction to Kolmogorov complexity and its applications. Vol. 3. New York: Springer, 2008. Closed Access: https://link.springer.com/book/10.1007/978-3-030-11298-1
Hutter, Marcus. Universal artificial intelligence: Sequential decisions based on algorithmic probability. Springer Science & Business Media, 2004. Closed Access: https://link.springer.com/book/10.1007/b138233 ; Public related slides: http://www.hutter1.net/ai/suaibook.pdf


How to execute Scitools Understand commands from python

Question: I want to execute Scitools Understand commands from python. It has its own shell which can be run using $ ./und and switches to und>. I want to run its commands from python. Any idea how can I do that?
Answer: First you should consider using the Python API for Ada Understand. This will be more comfortable than talking to the Understand console.
But using the console application is also possible. Ada Understand uses the standard input and output. Assuming you use Linux I have just a small demonstration for this.
create a file und.input with the contents
help
exit

And then exeucute this command
cat und.input | /opt/scitools/bin/linux64/und > und.output

This will create you the output into the file und.output.
You will not do it through files. With these files I just tried to give you evidence and a feeling that really the standard input and standard output is used. Knowing this, you need a way in Python to start a process and communicate to it over stdin and stdout. The subprocess module is a way to implement this. But there may be alternatives.
Although my demonstration above is on Linux, the Python implementation with subprocess will be the same for Windows.
Comment: Thanks. The its python API included in their own python interpreter named upython which is buggy, i.e. can not be included into vscode, it is working in terminal though.
Comment: Using upython is only one option. You can also use your own Python installation. See [here](https://support.scitools.com/support/solutions/articles/70000582852-getting-started-with-the-python-api).
Your Understand installation may not have all the Python files. In my installation they are missing. I don't know why. Maybe my version is too old. But in general it should work, as the manual says so. So you should again have a look.