MySQL LEFT JOIN using MAX & GROUP BY on joined table?

Question: I've got two tables (members and activities) and I'm trying to query the members with the latest activity for each member.  I've got it working with two queries (one to get the members and a second with a max(id) and group by(member) on the activities) and some code to merge the data.  I'm SURE it can be done with a single query, but I can't quite work it out.  Any ideas?
members table
id, name
 1, Shawn
 2, bob
 3, tom

activities table
id, member_id, code, timestamp, description
 1,         1,  123,     15000, baked a cake
 2,         1,  456,     20000, ate dinner
 3,         2,  789,     21000, drove home
 4,         1,  012,     22000, ate dessert

desired result:
id, name,  activity_code, activity_timestamp, activity_description
 1, shawn, 012,           22000,              ate dessert
 2, bob,   789,           21000,              drove home
 3, tom,   null,          null,               null

Answer: The "latest per group" problem is extremely common in SQL. There are countless examples of solutions to this very problem on this site alone.
If your timestamps are uniqe per member activity:
SELECT
  m.id,
  m.name,
  a.code activity_code,
  a.timestamp activity_timestamp,
  a.description activity_description
FROM
  members m
  INNER JOIN activities a ON a.member_id = m.id
WHERE
  a.timestamp = (SELECT MAX(timestamp) FROM activities WHERE member_id = m.id)

alternatively, if your activity ID is increasing monotonically with time:
  ...
WHERE
  a.id = (SELECT MAX(id) FROM activities WHERE member_id = m.id)

You don't need to group. But the query will benefit from an index on activities over (member_id, timestamp) or (member_id, id), respectively.

EDIT
To show any members who have not logged an activity, use a left join like this.
SELECT
  m.id,
  m.name,
  a.code activity_code,
  a.timestamp activity_timestamp,
  a.description activity_description
FROM
  members m
  LEFT JOIN activities a ON
    a.member_id = m.id
    AND a.timestamp = (SELECT MAX(timestamp) FROM activities WHERE member_id = m.id)

Note that there is no WHERE clause. Semantically, WHERE is applied after the joins are done. So a WHERE clause would remove the rows that the LEFT JOIN added, effectively giving in the same result as the original INNER JOIN.
But if you apply the additional predicate right in the join condition, the LEFT JOIN will work as expected.
Comment: This seems to be dropping my member (tom, id=3) who has never logged any activities.I tried changing INNER JOIN to LEFT JOIN.

I'm trying the second WHERE statement, my timestamps aren't guaranteed to be unique, but the id is a unique auto-incrementing field.
Comment: @ShawnMcBride See modified answer.
Comment: I personally don't like nested queries in condition. It would be much more optimized solution if you join with query that has only MAX timestamps, like answer below
Comment: @dzona When you have a proper index set, it won't matter.
Answer: SELECT
    members.id ,
    members.name,
    activities.code AS activity_code,
    activities.timestamp AS activity_timestamp,
    activities.description AS activity_description
FROM
    members
    LEFT JOIN activities
        ON members.id = activities.member_id
    LEFT JOIN
        (
            SELECT
                activities.member_id
                MAX(activities.id) AS id
            FROM activities
            GROUP BY
                activities.member_id
        ) AS t1
        ON activities.id = t1.id
WHERE
    t1.id IS NOT NULL

Comment: I think you should use a left join in both cases.
Comment: It seems to be dropping my member that has never logged any activity. I get the same result as Tomalak's query.  If I change the second JOIN to a LEFT JOIN it seems to be returning all activity records.
Comment: @ShawnMcBride `WHERE t1.id IS NOT NULL` was missing. Please, try it again.
Answer: Select max(a.id), m.name, a.activity_code, a.activity_timestamp, a.activity_description
From members m
     Left join
     activities a on a.member_id=m.id
Group by  m.name, a.activity_code, a.activity_timestamp, a.activity_description


The product of limit point compact Hausdorff spaces is not limit point compact

Question: Let $X, Y$ be limit point compact Hausdorff spaces (to be clear, a space is said to be limit point compact if every infinite subset of it has a limit point). Is it true that $X \times Y$ is limit point compact? The answer should be negative but I can't find a counterexample. Can you?
Answer: Limit point compactness is equivalent to countable compactness in $T_1$ spaces, so it suffices to find a pair of countably compact $T_1$ spaces whose product is not countably compact. In this answer you'll find a reference to the first published example of such a pair, together with a brief description; the spaces in question are not just $T_1$, but Tikhonov, being subspaces of the compact Hausdorff space $\beta\Bbb N$.
Comment: thank you for your answer, please just give me the time to put all the pieces together before accepting it :)
Comment: @user01123581321345589144...: You're welcome; take whatver time you need.


Sobre Activities em Android/Java

Question: Boa noite.
A minha duvida é simples. Meu app tem um sistema no qual eu abro 5 activities para cadastro (primeiro a activity 1, depois a 2 e assim sucessivamente. imagine que seja algo parecido com uma instalação do windows aonde tem varias janelas com "next")
Da quinta activity ela volta para a primeira, e quando o usuario precisar de um novo cadastro, o processo acontece novamente.
Este é o codigo que eu uso para passar entre as activities:
<code>Intent novaActivity = new Intent(getApplicationContext(), proximaActivity);
                novaActivity.putStringArrayListExtra("activities", activitiesSelecionadas);
                startActivity(novaActivity);
                finish();
</code>
Existe alguma possíbilidade de o aplicativo ficar muito pesado após varios cadastros?
Comment: Se da quinta activity o usuário voltar para a primeira depois de finalizar o cadastro o melhor é limpar o *Back Stack* e o problema deixa de existir.
Comment: Vou pesquisar sobre. Obrigado pela dica!
Answer: Pelo que vejo a arquitetura ideal para este processo (assumindo que faz tudo parte do cadastro) é ter apenas uma Activity e 5 fragmentos. Desta maneira consegues gerir os layouts, a escalabilidade e a informação(que pode ficar toda na activity) melhor.

Sobre Activities em Android/Java


PyOpenGL glutInit NullFunctionError

Question: I am running Anaconda Python 2.7 on a Win7 x64 machine and used
pip install PyOpenGL PyOpenGL_accelerate

at the Anaconda command line to install PyOpenGL.
I have some code (not my own I must confess) that makes use of glutInit
import sys
import math
import numpy

import OpenGL
from OpenGL.GL import *
from OpenGL.GLUT import *

import Image

import linkage

# ... a whole load of definitions etc ...

glutInit(sys.argv)
glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGB)
glutInitWindowSize(600, 600)
glutCreateWindow('linkage')
init()
initWindow()
glutIdleFunc(idle)
glutMainLoop()

I run by entering the following at the command line:
python main.py peaucellier.txt

But then get the following error (line 371 is the glutInt(sys.argv) line above)
File "C:/Users/Owner/Documents/Python Scripts/linkage/main.py", line 371, in <module>
glutInit(sys.argv)

File "C:\Anaconda\lib\site-packages\OpenGL\GLUT\special.py", line 333, in glutInit
_base_glutInit( ctypes.byref(count), holder )

File "C:\Anaconda\lib\site-packages\OpenGL\platform\baseplatform.py", line 407, in __call__
self.__name__, self.__name__,

NullFunctionError: Attempt to call an undefined function glutInit, check for bool(glutInit) before calling

I have looked at similar errors posted in this forum but none of the proposed fixes are working which is why I'm asking, what's wrong here?
Is the installation at fault? Are the imports correct?
EDIT: After trying many many fixes for the official release I am now using an unofficial release that works perfectly from Unofficial Windows Binaries for Python Extension Packages
Answer: According to the link below the problem was with the glut installation rather than pip install. It seems glut files are not part of PyOpenGL or PyOpenGL_accelerate package. You have to download them seperately.
https://stackoverflow.com/a/39181193/7030177
Windows user can use the link below to download glut as mentioned in the given link.
ftp://ftp.sgi.com/opengl/glut/glut3.html.old#windows
Linux Users can just install glut using the following command:
sudo apt-get install freeglut3-dev

Hope this helps :)
Comment: The FTP link is no longer hosted.
Comment: Under GNU/Linux installing freeglut3 is sufficient.
Comment: On my windows PyOpenGL work fine with copy of freeglut.dll with name freeglut32.vc14.
Comment: 'sudo apt-get install freeglut3-dev' saved my day!
Comment: As @Alexey noted, just rename freeglut.dll to freeglut64.vc14 (if you have a 32-bit interpreter, rename to freeglut32.vc14). The original freeglut.dll must be of the correct bit size. Then placed them to your python file. The numerical ending of the file extension probably [depends](https://wiki.python.org/moin/WindowsCompilers) on the used interpreter version.
Comment: Well, after python update to version 3.8.6, solution above didn't work. So I just installed an unofficial whl package. One thing this package differs from official is DLLS folder at /Lib/site-package/OpenGL that contains freeglut64.vc15.dll. I tested this in new venv by install official package and creating the folder and coping freeglut.dll renamed to freeglut64.vc14.dll (I builded freeglut with VS2019).
Answer: After looking around for a solution to a similar problem I ran across this google group that answers the question: https://groups.google.com/forum/#!topic/glumpy-users/aC1NjEHXtEE
There is a problem with OpenGL.GLUT when downloaded as pip from the official source. Uninstall OpenGL using pip, then download OpenGL from http://www.lfd.uci.edu/~gohlke/pythonlibs/
Comment: Worked for me on Win 7, python 2.7 anaconda, freeglut solution proposed by others like Mamuka Arabuli or Gnat don't, so try it first.
Comment: Worked for Win10 Python 3.8. Copying `freeglut.dll` did not work.
Answer: For people on Linux with this error after installing via easy_install PyOpenGL or pip install PyOpenGL.
-> Install the distribution package as: sudo apt-get install python-opengl - this works for me.
Answer: If installing PyOpenGL from easy_install, pip or conda, make sure that you have already installed a GLUT implementation, such as FreeGLUT (prebuilt Windows binaries).
For FreeGLUT, copy the distributed files to a location on your hard drive and then add the path to the bin directory (which contains the GLUT DLLs) to your PATH environment variable. Then PyOpenGL should work as expected.
Answer: It is mainly because you're running 64-bit windows put pip is installing 32-bit version of PyOpenGL.
To fix this, follow these steps:

Uninstall existing PyOpenGL, Run pip uninstall PyOpenGL PyOpenGL_accelerate

Download the 64-bit builds of PyOpenGL and PyOpenGL accelerate from here: https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyopengl

How to choose which one to download? Well, first you need to check your python version. Run python --version to determine.
Then according to your version download the whl files for PyOpenGL and PyOpenGL accelerate. For example, if you have Python 3.8, download these 2 files:

PyOpenGL‑3.1.5‑cp38‑cp38‑win_amd64.whl
PyOpenGL_accelerate‑3.1.5‑cp38‑cp38‑win_amd64.whl
Similarly, if you run Python 3.9, download these instead:
PyOpenGL‑3.1.5‑cp39‑cp39‑win_amd64.whl
PyOpenGL_accelerate‑3.1.5‑cp39‑cp39‑win_amd64.whl
Note: Must download amd64 ones, after all, you're running 64-bit windows.

Now go to the folder where you downloaded the files and run powershell/cmd with administrator there.

Use pip to force install those files. For example:

pip install PyOpenGL-3.1.5-cp38-cp38-win_amd64.whl --force-reinstall
pip install PyOpenGL_accelerate-3.1.5-cp38-cp38-win_amd64.whl --force-reinstall
Note: Install PyOpenGL first and then PyOpenGL_accelerate

If the installation succeeds, you may be able now to run.

Some facts to make sure:
*All platforms must be of the same bit version.
*System type, python, OpenGL needs to be of the same bit version. In my case it was x64 bit
*It is necessary to restart your desktop if you reinstall any one of them (Python, OpenGL)
*It is recommended to keep your pip version at 20.3, I downgraded it from 21.1.3
Comment: Best answer, the only one that works for me! Thanks.
Comment: Agreed. best answer in several posts here on stackoverflow.Thanks
Answer: I got the same error and a solved installing required files from here.
Download these files:

PyOpenGL-3.1.1-cp27-cp27m-win32.whl   (download if your computer 32 bits  )
PyOpenGL-3.1.1-cp27-cp27m-win_amd64.whl (download if your computer 64 bits  )
PyOpenGL_accelerate-3.1.1-cp27-cp27m-win32.whl (download if your computer 32 bits  )
PyOpenGL_accelerate-3.1.1-cp27-cp27m-win_amd64.whl (download if your computer 64 bits  )

install these .whl files for 64 bits:
pip install PyOpenGL-3.1.1-cp27-cp27m-win_amd64.whl
pip install PyOpenGL_accelerate-3.1.1-cp27-cp27m-win_amd64.whl

install these .whl files for 32 bits:
pip install PyOpenGL-3.1.1-cp27-cp27m-win32.whl
pip install PyOpenGL_accelerate-3.1.1-cp27-cp27m-win32.whl

Comment: ergul, you will notice that this is the same link as in the opening post.
Comment: @DrBwts you are right. This question asked by you 2 years ago. I just write a solution with step by step for people who don't know english very well.
Answer: for python 2.7, PyopenGL needs vc++ 9 compiler, download and install it.
then:
python -m pip install --upgrade pip

pip install image

pip install numpy

pip install PyOpenGL PyOpenGL_accelerate

I downloaded freeglut
unzipped it and added bin directory to the path
when calling: glutCreateWindow("sometitle")
changed to glutCreateWindow(b'sometitle')
and got it run on windows 7
Answer: My case is different, Python 3.6 and windows 10. However exactly same error message. Tried all above solutions, no success.
Downloaded WHL file right to my computer and version of python from HERE
Then pip installs filename.Whl, no more issue!
The answer was from a Chinese website: Answer Link
Answer: Yes, this happened to me on Windows 10 running python 2.713 anaconda 4 64 bit. I had used conda to install pyopengl but received the same error as above.  So I downloaded freeglut from transmissionzero and just copied the freeglut.dll (64 bit for me) to the same directory as my source file (it just needs to be in the dll searchpath) and all was good.
Answer: I know it is a little late. I also encountered this problem with python 2.7 (32 bits) in windows. I tried the method mentioned by user2723240 but still failed.  Finally, I solved this problem by copying glue32.dll to System32 in C drive and copy glue32.dll into my source file directory. It works well now.
Comment: Yes I tried that but it it didn't work on my set up. Only the unofficial releases linked to in the OP work for me.
Answer: On linux, the pyopengl module attempts to use ctypes module to load the glut library as simply 'glut'. According to ctypes documentation the loadLibrary routine must be given the complete filename. Therefore, I made a symbolic link to libglut.so and named it 'glut' and everything just worked.
Answer: The following command should work for Anaconda users:
conda install -c conda-forge freeglut
https://anaconda.org/conda-forge/freeglut
Answer: On windows, although PyOpenGL says it installs freeglut by default, it does not.
To patch it, you must download or compile freeglut (other answers here contain the appropriate links) and place it in a new site-packages/OpenGL/DLLS folder inside to your existing OpenGL site-packages installation.
Once there, the freeglut.dll needs to have the bits and the MSVC version appended to the filename. OpenGL/platform/win32.py has the details on exactly how it's detected.
To make it clearer the filename needs to be the one printed from the following script:
import sys
import platform

if sys.hexversion < 0x2070000:
    vc = 'vc7'
elif sys.hexversion >= 0x3050000:
    vc = 'vc14'
elif sys.hexversion >= 0x3030000:
    vc = 'vc10'
else:
    vc = 'vc9'

size = platform.architecture()[0].strip('bits')

print(f'freeglut{size}.{vc}.dll')

Answer: Step 1
Install python in your system windows 10/11 preferred. for python 3.8.0 : https://www.python.org/ftp/python/3.8.0/python-3.8.0-amd64.exe
If you have already installed then check for your python version
Open terminal and type "python --version"
it will display your python version. for example I have installed python 3.8.0.
Step 2
Next open terminal and run the below command
python -m pip install --upgrade pip==20.3
sometimes you have higher version of pip installed but its okay to downgrade back to version 20.3
Step 3
now for installing OpenGL go to this site : https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyopengl
and download
PyOpenGL‑3.1.6‑cp38‑cp38‑win_amd64.whl (for 64bit windows)  or
PyOpenGL‑3.1.6‑cp38‑cp38‑win32.whl (for 32 bit)
and
PyOpenGL_accelerate‑3.1.6‑cp38‑cp38‑win_amd64.whl (for windows 64bit) or
PyOpenGL_accelerate‑3.1.6‑cp38‑cp38‑win32.whl  (for windows 32bit)
Note : I have in installed python 3.8.0. so I downloaded PyOpenGL having cp38 word in it. If you have installed python 3.9 or other version download the above mentioned file having name cp39,cp10 etc.
after downloading both files according to your python version. put it a folder.
Step 4
then open terminal from that folder. Windows 10 lets you launch Command Prompt in a folder through the File Explorer's address bar. Type "cmd" in the address bar and then hit Enter
after opening terminal enter the below command
pip install PyOpenGL-3.1.6-cp38-cp38-win_amd64.whl --force-reinstall
then after installing it run the below command
pip install PyOpenGL_accelerate-3.1.6-cp38-cp38-win_amd64.whl --force-reinstall
Note : Don't forget to change the file name ( e.g. : PyOpenGL-3.1.6-cp38-cp38-win_amd64.whl) to the file name that you have downloaded.

PyOpenGL glutInit NullFunctionError


Differentiability of $f$ in $\mathbb{R^m}$

Question: Is true that if $A\subset \mathbb{R^m},$ $f:A\longrightarrow \mathbb{R}$ and $D_jf$ (partial derivatives) exist in and are bounded in  a neighborhood of $a\in A$ then $f$ is differentiable?
I think this is true but I don't see how to use the fact that there exist $M>0$ such that $|D_jf|<M$ for each j. Also, I know if I can show that $D_j f$ is continuous at $a,$ the result follows from that.
Thanks for any hint!
Comment: Not sure this is true. With the given hypothesis, that $f$ is *continuous*  can be proved, but *differentiable*, I am not sure.
Comment: астон вілла олоф мэллбэрг  Oh, I see... And how would I prove that f is continuous?
Comment: The answer below gives a counterexample. The hint would be to use the mean value theorem (for one dimension, using the partial derivatives), and the chain of expressions that is used, to show that if $D_jf$ are continuous then $f$ is differentiable (i.e. where you split  a difference component by component). If you are unaware, you may request an answer.
Comment: indeed, you need the partials to be continuously differentiable to get total differentiable. Ask about partial differentiable to continuity in another question. I'll need to give that a thought. but my hunch is that's also a no.
Answer: This counter example disproves the statement. (Note: Total derivative exist is equivalent as all directional derivatives exist.)


Clearing DATE field in Google Admin SDK API

Question: Any Google workspace DEV's here?
I have some fields for my users I am trying to clear via the API.
using
Method: users.update
https://developers.google.com/admin-sdk/directory/reference/rest/v1/users/update
If I pass a null value in the form of ""  it to try and clear some fields user attributes. It works for Boolean values and Strings (that I've tested so far)
But not for DATE fields.
Here is the JSON i Am sending
{
    "customSchemas":  {
                          "includeInGlobalAddressList":  "true",
                          "OffBoarding":  {
                                                 "abooleanvalue1":  "",
                                                 "astringvalue1":  "",
                                             },
                          "General":  {
                                             "aDateValue":  ""
                                         }
                      }
}

returns
{
  "error": {
    "code": 400,
    "message": "Invalid Input",
    "errors": [
      {
        "message": "Invalid Input",
        "domain": "global",
        "reason": "invalid"
      }
    ]
  }
}

if i use the same format to set a value , it updates the value successfully
{
    "customSchemas":  {
                          "includeInGlobalAddressList":  "true",
                          "OffBoarding":  {
                                                 "abooleanvalue1":  "",
                                                 "astringvalue1":  "",
                                             },
                          "General":  {
                                             "aDateValue":  "2020-01-01"
                                         }
                      }
}

will work fine.
I tried to test it out with GAM . Same thing
gam update user firstname.lastname@example.com OffBoarding.astringvalue1 ""
will work but if I do the same on a date field.
gam update user email@example.com General.aDateValue ""
ERROR: 400: Invalid Input - invalid
My google searching thus far has not turned up anything relevant, either that or I need more coffee. Closest I could find was this thread
Unable to clear Google user property completely
But that was attributed to an actual issue, and i've tried sending
[]
[""]
null
as they suggested there , so far no luck.
Answer: The way to reset a user property of type date is setting it to null :
{
    "customSchemas":  {
                          "includeInGlobalAddressList":  "true",
                          "OffBoarding":  {
                                                 "abooleanvalue1":  "",
                                                 "astringvalue1":  "",
                                             },
                          "General":  {
                                             "aDateValue":  null
                                         }
                      }
}

Comment: Thanks, this is correct.

 I also got some help with this last night as well from a redditor.  I omitted the fact that I was using Powershell as my code language and I was incorrectly setting the NULL value when I tried it.  As I have convert my objects to json format using converto-json .

I tried  value = "null"  or value = null which did not work when I had to use convert-tojson  the correct approach is to set value = $null and then convert to JSON which provided null without quotes.  This provided the desired results.


Como visualizar arquivos antes de executar o download?

Question: Quero que um PDF(gerado no meu servidor) seja mandado para o meu cliente e aberto em uma nova aba antes de ser baixado. Já consegui fazer com que ele seja baixado diretamente quando vem do servidor para o cliente, porém, agora necessito que ele seja exibido ao invés de ser baixado.
Criei um servidor Express na versão 4.15.0 e o meu cliente foi feito em VueJS utilizando o Quasar Framework. Segue alguns códigos para ajudar no entendimento da pergunta:
Servidor:
pdfMake = printer.createPdfKitDocument(docDefinition);
let stream = pdfMake.pipe(fs.createWriteStream('../pdfs/Tabela.pdf'));
pdfMake.end();

stream.on('finish', function() { //Método síncrono que só efetua o download do arquivo
                                 // depois que o PDF está criado
    if (fs.existsSync('C:/Projetos/Relatorios/pdfs/Tabela.pdf')) {
        let file = 'C:/Projetos/Relatorios/pdfs/Tabela.pdf';
        res.send(file); //Este método está certo?? Se não, qual devo usar??
    }
})

Cliente:
axios({
      method: 'post',
      url: '/server/gerarpdf',
      responseType: 'arraybuffer',
      data: this.pessoas
    })
    .then(function (response) {
      let blob = new Blob([response.data], {type: 'application/pdf'})
      let link = document.createElement('a')
      link.href = window.URL.createObjectURL(blob)
      //Comentei o método abaixo pois ele efetuava o download, qual método devo utilizar para que o PDF seja visualizado ao invés de baixado??
      // link.download = 'TabelaTeste.pdf'
      link.click()
    })

Answer: Faça seu link abrir numa nova guia:
let link = document.createElement('a')
link.target = '_blank'
let url = window.URL.createObjectURL(blob);
link.href = url.replace(/([\w]{8})-([\w]{4}-){3}([\w]{12})/g, 'meuarquivo.pdf');

Comment: `let options = {
    root: '../pdfs/',
    dotfiles: 'deny'
   };
   let fileName = 'Tabela.pdf';
   res.sendFile(fileName, options, function (err) {
    if (err){
     console.log(err)
    }else{
     console.log(fileName + ' foi enviado!')
    }`

E o servidor estando assim está correto??
Comment: Pois ele está abrindo o arquivo, mas o nome está "
4098840a-9687-4fad-aa36-7e6f16f5a018"
Comment: Acredito que ele não vai obedecer o nome enviado pelo servidor, experimente descomentar a linha de código `link.download` @LeonardoEbert
Comment: Após descomentar a linha `link.download` o arquivo foi somente baixado, sem abrir em nova guia
Comment: De um `console.log(window.URL.createObjectURL(blob))` para ver o formato da URL. Poderemos renomear por ela @LeonardoEbert
Comment: Foi isso que apareceu no console: `blob:http://localhost:8080/960619d0-a0fa-4a6e-ba0e-6c0380669f1f`
Comment: Editado @LeonardoEbert
Comment: Testei e não funcionou, não acontece nada quando clico no botão...
Comment: Verifiquei a URL no navegador e ela fica assim: "blob:http://localhost:8080/2050102b-7041-4cfa-9ebf-0c05af158005"


RNN on microcontroller based systems

Question: I'm currently developing a RNN with Python and Keras/TensorFlow for time series prediction. My final objective is to port the (trained) RNN to an embedded system, which should collect the input time series from sensors and run them through the RNN and output a time series (prediction) in real time, or at least in approximately real time.
So, my questions are: (1) is it possible to port a trained RNN (Python based Keras/TensorFlow model) into an embedded system? And (2) if so, which embedded platforms would you recommend to perform such a task?
If you could share references which relate to the questions, it would also help me a lot.
Thank you.
Obs.: the RNN is composed of 5 layers with 32, 16, 8, 4 and 2 LSTM units each. The inputs of the network are 2 time series, with sizes ranging from 10000 to 200000 samples; in the PC I handle them using Python generators, training and running the network with batches of 128 samples.
I think that reducing the size of the network would not cause to many issues (regarding the precision of the output series).
Comment: Check this paper
https://arxiv.org/pdf/1908.07062.pdf - Recurrent Neural Networks: An
Embedded Computing Perspective
Answer: This would be my approach to it:
First, estimate the memory needed for the LSTM: How can calculate number of weights in LSTM
I get that calculation to be 8552 params for all your layers. Now consider that each parameter will need to be stored as a floating point value. If we assume 32-bit resolution of these parameters is ok, you will need 4 bytes per parameter, so your lower memory bound will be:
lstm_parameter_memory_size = parameters * 4
lstm_parameter_memory_size = 34208 bytes
Of course you will need more memory than this, but this is (for the LSTM) the dominating factor. The exact timing response will require quite the analysis, so I suggest to use a tool to check Keras/TensorFlow execution or make a rough estimate on the number of instructions per LSTM unit.
A more pragmatic and less theoretical approach:
Buy something like an ESP-32, implement the LSTM in C and just try it. It is a powerful and inexpensive device: https://en.wikipedia.org/wiki/ESP32. This approach allows you to scale your hardware solution down or up also, since most platforms will run your C code with smaller adjustments.
Comment: I just edited the question in order to inform the size of the RNN. Hope this helps in getting more detailed answers.
Comment: It helps, but please also include the input and output vector sizes. Also, do you have any size constraints on your system? Battery constraints? Price? There are a wide range of embedded systems ranging from puny rudimental devices to almost full-fledged mini desktops...
Comment: I still have no constraints on the system settings (like size and battery) and price. One of the purposes of the question is to obtain guidance in selecting the system.
Comment: Do I understand correctly that your RNN reads 2 inputs at each timestep and outputs 1 prediction? (This is what I mean by input and output vectors)
Comment: Yes, that is correct.
Comment: Do you know of any references on implementing LSTMs or translating the Keras models to C? Thank you for the answer!
Comment: This seems to be a small LSTM implementation in C with few dependencies (I haven't tried it or looked at the code though): https://github.com/tmbdev/clstm . Provided that Keras let's you dump the weights into a file, you should be able to "move" your model to another lib by just reformatting that file to fit the style of whatever ML lib you choose.
Answer: Empirical results often indicate (e.g. [1]) that simpler gated RNN's (e.g. MGU or GRU) perform comparably to LSTM, and since in microcontroller application memory consumption is important, I would suggest to work with simpler gated RNN models instead of LSTM. [2] is my old implementation of GRU for microcontrollers (e.g. teensy 3.6).
[1] https://arxiv.org/pdf/1412.3555v1.pdf
[2] https://github.com/povidanius/gru_neurocontroller
Answer: Just to extend the possibilities stated by the accepted answer
1) Yes, it is possible to port RNNs to microcontrollers. An example of a library for doing so is CMSIS-NN. They even have a GRU example and more detailed procedures in its web page, such as how to convert a network.
Another possibility is TFMicro, but be aware that currently you will, I could assure, problems quantizing RNNs. However, if you do not quantize it, there shouldn't be any problem.
2) Depending on the easiness that you need I would choose one or another platform. For example, if you want an easy path you can choose a platform supported by TFLite for Microcontrollers. If you want to work on quantization patterns and so, I would, as stated by @Nenovrak, compute the model requirements in terms of size but also in terms of RAM, and then I would choose an appropriate microcontroller with an ARM CPU, juswt to use CMSIS on it.
Answer: In addition to the tools mentioned by @BCjuan, there is also.
https://github.com/majianjia/nnom
a platform independent inference engine for neural networks. It takes a Keras model as input.
X-CUBE-AI from ST Microelectronics. It is however proprietary and only supports their devices.
Answer: Haven't tried but would seem the CMSIS examples have been ported to ESP32
https://github.com/UT2UH/ML-KWS-for-ESP32
Forked from ARM's Keyword spotting for Microcontrollers using frankie "whyengineer" fork of ARM's CMSIS for ESP32
This repository consists of the tensorflow models and training scripts used in the paper: Hello Edge: Keyword spotting on Microcontrollers. The scripts are adapted from Tensorflow examples and some are repeated here for the sake of making these scripts self-contained.

RNN on microcontroller based systems


Facebook Like button: how it choose image to display

Question: I've put "Like" button to my web site.
In general it works fine, the only problem is when user add some text and publish it in the profile his post contains image. And the image chosen is not something meaningful, it is one of the menu items that doesn't really makes any sense.
Could you please advise how to tip to the facebook the better image? I didn't see any information about that in their documentation (http://developers.facebook.com/docs/reference/plugins/like/), probably I've overlooked that?
Thank you.
P.S. Pretty similar question: is there any way to suggest for user text he wants to share (that will appear once user click "Like" button)?
Answer: You can specify image by adding Open Graph  tags to head section each page containing the "Like" button.
You can specify an image URL in og:image tag, and Facebook will use this image in the user's profile entry.
The same goes with
og:title - this will be the title of the new entry on user's profile.
og:site_name (will be displayed as grey text under title) etc.
See http://developers.facebook.com/docs/reference/plugins/like/ and
http://developers.facebook.com/docs/opengraphprotocol/
for detailed description.
You can use the Open Graph tags for both versions of the "like" button - iframe and XFBML.
Once you add the tags to your pages you can use http://developers.facebook.com/tools/debug to check if they are OK.


Align labels in form next to input

Question: I have very basic and known scenario of form where I need to align labels next to inputs correctly. However I don't know how to do it.
My goal would be that labels are aligned next to inputs to the right side. Here is picture example of desired result.

I have made a fiddle for your convenience and to clarify what I have now - http://jsfiddle.net/WX58z/
Snippet:

    Simple label
    <input type="text" />

    Label with more text
    <input type="text" />

    Short
    <input type="text" />

Answer:
WARNING: OUTDATED ANSWER
Nowadays you should definitely avoid using fixed widths. You could use flexbox or CSS grid to come up with a responsive solution. See the other answers.

One possible solution:

Determine a reasonable fixed width for label elements and set it using width
Give them display: inline-block
Align text to the right

That is:

label {
  display: inline-block;
  width: 140px;
  text-align: right;
}

    Simple label
    <input type="text" />

    Label with more text
    <input type="text" />

    Short
    <input type="text" />

JSFiddle
Comment: How do I make this work if some of the labels are check-boxes or radio buttons? The labels for these elements end up with the same fixed width as the textbox labels which is not desired. Is there a way to do this without a fixed width on the label?
Comment: How to make this responsive? And how to cope with i18n? I mean that text labels have different length in different languages, thus I fear that that setting fixed width fill not work if the text is long.
Comment: this is marking fixed width, it should be dynamic, based on max label width.
Comment: @RebeccaMeritz You mean when the markup has the checkbox first, and the label afterwards? You could add a class to both, and style them separately. Perhaps you should [ask a new question](http://stackoverflow.com/questions/ask) about it.
Comment: @Azimuth Nowadays, you might want to use CSS grid instead.
Comment: I agree with the people here above, that using a fixed width is a bad solution when it comes down to scaling of the labels and the usage of dynamic width's based on content.
Comment: @Barrosy I totally agree, you could use flexbox or grid nowadays. That was not the case when this answer was written 8 yrs ago...
Comment: @bfavaretto Even so, I belive better solutions existed back then as well, but you might be right.
Comment: CSS flexbox is merely a candidate recommendation, while CSS grid is not even at that stage yet (draft CR). Unfortunately, the warning is misleading; this answer remains current.
Comment: Regardless of the formal status of flexbox and grid, I'd avoid fixed widths whenever possible today. That's the spirit of the warning. Also, both technologies are widely supported nowadays. @PhilippeCloutier
Answer: While the solutions here are workable, more recent technology has made for what I think is a better solution. CSS Grid Layout allows us to structure a more elegant solution.
The CSS below provides a 2-column "settings" structure, where the first column is expected to be a right-aligned label, followed by some content in the second column. More complicated content can be presented in the second column by wrapping it in a
.
[As a side-note: I use CSS to add the ':' that trails each label, as this is a stylistic element - my preference.]

/* CSS */

div.settings {
    display:grid;
    grid-template-columns: max-content max-content;
    grid-gap:5px;
}
div.settings label       { text-align:right; }
div.settings label:after { content: ":"; }

    Label #1
    <input type="text" />

    Long Label #2
    Display content

    Label #3
    <input type="text" />

Comment: Optimal Solution! Works fine now in Chrome 73.
Comment: Hey, can you add a fiddle please?
Comment: Awesome! If you replace the columns definition above with `grid-template-columns: max-content 1fr;`, the second column will use all remaining width. This to me is the holy grail of such layouts, where no column or content widths must be specified, and everything fits perfectly into the available space, automatically.
Comment: I'm sorry to vote that down since CSS grid remains a mere Candidate Recommendation draft; it's not so much "recent technology" as "future technology" which remains risky to adopt.
Comment: Yes, I've updated the answer to make use of snippets.
Comment: Which Chrome version and platform are you having problems with?
Answer: Answered a question such as this before, you can take a look at the results here:
Creating form to have fields and text next to each other - what is the semantic way to do it?
So to apply the same rules to your fiddle you can use display:inline-block to display your label and input groups side by side, like so:
CSS
input {
    margin-top: 5px;
    margin-bottom: 5px;
    display:inline-block;
    *display: inline;     /* for IE7*/
    zoom:1;              /* for IE7*/
    vertical-align:middle;
    margin-left:20px
}

label {
    display:inline-block;
    *display: inline;     /* for IE7*/
    zoom:1;              /* for IE7*/
    float: left;
    padding-top: 5px;
    text-align: right;
    width: 140px;
}

updated fiddle
Comment: This is a very nice solution, except for the fact that you must hard-code the width of the labels. If a new label is too long - the layout breaks. Seems like there should be a more robust solution?
Answer: I use something similar to this:

  Long Label
  <input type="text" name="foo" id="foo" />

Style:
.form-element label {
    display: inline-block;
    width: 150px;
}

Comment: The big problem with that approach is you're using a fixed width, which constantly needs reevaluation as labels change.
Answer: I know this is an old thread but an easier solution would be to embed an input within the label like so:

Label one: <input id="input1" type="text">
Comment: I was looking for a solution for this (include the input inside the label) but with aligned text
Comment: This doesn't respect the OP's requirement of alignment (unless all labels would have the same width).
Answer: You can also try using flex-box

<form>

            name:
            <input type="text" id="user_name">

            Password:
            <input type="password" id="user_pass">

</form>

Comment: That is pretty, but not at all what he asked for. See the picture in op
Comment: The CSS Flexible Box Layout Module is merely a W3C Candidate Recommendation - using it may not be future-proof.
Answer: You can do something like this:
HTML:

Something
<input type='text' class='input'/>

CSS:
.div{
      margin-bottom: 10px;
      display: grid;
      grid-template-columns: 1fr 4fr;
}

.input{
       width: 50%;
}

Hope this helps ! :)
Answer: Here is generic labels width for all form labels. Nothing fix width.
call setLabelWidth calculator with all the labels.
This function will load all labels on UI and find out maximum label width.
Apply return value of below function to all the labels.
     this.setLabelWidth = function (labels) {
            var d = labels.join('
'),
                dummyelm = jQuery("#lblWidthCalcHolder"),
                width;
            dummyelm.empty().html(d);
            width = Math.ceil(dummyelm[0].getBoundingClientRect().width);
            width = width > 0 ? width + 5: width;
            //this.resetLabels(); //to reset labels.
            var element = angular.element("#lblWidthCalcHolder")[0];
            element.style.visibility = "hidden";
            //Removing all the lables from the element as width is calculated and the element is hidden
            element.innerHTML = "";
            return {
                width: width,
                validWidth: width !== 0
            };

        };

Align labels in form next to input


mudar de cor depois que uma página foi visitada usando Bootstrap

Question: parece que fazer isso não surge efeito:
a:visited{
   color: #red;
}

Existe uma outra possibilidade de saber que página a pessoa já visitou?
Estou usando php
Answer: Utilizando cookies é possível verificar se uma página foi visitada.
Por exemplo:
setcookie("visitado", "1" /*, time() + 3600 */);

Onde o terceiro parâmetro que foi omitido, configura para o cookie expirar em uma hora, quando omitido o cookie só é válido até fechar o navegador.
Lembre-se que o cookie deve ser criado antes de qualquer saída, então é mais adequado criá-lo no início do código.
No seu arquivo de layout você faria algo como:
<a class="<?= key_exists("visitado", $_COOKIE) ? 'visited' : '' ?>">Página inicial

E no seu arquivo css:
.visitado {
  color: red;
}


Flex Mobile: Test Resolutions Greater than Screen Size

Question: Flash Builder has an Emulator for mobile devices of any resolutions.
My questions are the following:
1) When testing for devices with resolutions greater than my screen size, is it still reliable to use the FB Emulator?
2) What are other alternatives that can I use for debugging purposes with FB?
Comment: You can always use the various Android emulators (and Google's Android emulator, even though it is so slow that I would go with a 3rd party one) and on OS-X you can also use the Xcode/iPhone simulator to debug AIR apps...   Adobe's AIR Debug Launcher does a good job of resolution emulation. They all do a good job of device resolution emulation (in terms of accurate scaling to your actual screen size, but in the end, of course, physical device testing is the only true test for your app.
Comment: How are you handling scaling within your app?  i.e. are you just scaling everything bigger or are you resizing UI controls, font sizes, changing their individual position, showing additional content, etc... are you using flex mobile-based Skins to handle UI scaling, etc..   either way, the emulated device size should show you areas that you are not handling correctly when the device resolution changes. Are you following Adobe's Guidelines? http://help.adobe.com/en_US/flex/mobileapps/WS19f279b149e7481c682e5a9412cf5976c17-8000.html
Comment: how bout AIR Debug emulator? is it okay for big resolutions (greater than my screen)?
Comment: That 'emulator' works fine, all any of the emulators are doing is scaling up or down while maintaining the "true" aspect ratio of the original resolution. I'm not sure what your true concern of resolutions great then your screen size is, do you have a particular use-case that you are concerned about?
Comment: well like for example... i tried the emulator with 1920x1080 for LG G2 device and so far, I can see the same on the actual mobile.. My concern is for bigger resolutions such as S6 (2560x1440) and others.. Was working on optimizing my AIR App since clients noticed the app to be too small on their mobile, but I have no actual device that I can use. However my screen size is just 1920x1080, was just wondering if it will affect the scaling.
Comment: i used auto scaling by setting the applicationDPI.. but  I have custom areas where i made adjustments with scaleX and scaleY. I think we are following the guidelines.. was just hoping that there's a way that we can do this in responsive manner other than creating multiple views.
Answer: Alternative to Capabilities since on FB Simulator it will use the monitor screen size not the actual device resolution.
<code>var root:DisplayObject = SystemManager.getSWFRoot(this);
screenX  = root.stage.fullScreenWidth;
screenY  = root.stage.fullScreenHeight;
</code>


How do you solve this equations where the unknown is to the power of the unknown?

Question: How do you solve equations like: $$x^x=7$$
I've been thinking about this but couldn't find any answer. (I'm not looking for graphical solutions, only pure algebra)
Thanks!
Comment: I don't think in general there is a method other than approximation.
Comment: a solution by a numerical method is possible
Comment: Check out the Lambert W function.
Comment: Actually there is: Lambert's W. @fleablood
Answer: Letting $x=e^t$, you rewrite
$$e^{te^t}=7,$$ or $$te^t=\ln(7),$$
which is solved by means of the Lambert function:
$$x=e^{W((\ln(7))}=\frac{\ln(7)}{W(\ln(7))}.$$
There is no better analytical way, I am afraid.
Answer: You can try to use graphic way to find the number of the solution. If you apply the $log$ to both terms you get: $$xlogx=log7$$ that is $x=log(7)/log(x)$ and you can picture the function $y=x$ and $y=log(7)/log(x)$
Answer: If you are trying to solve $x^{x} = c$ for positive real $x$ and positive real $c$, then this is equivalent to proving that $x \log(x) = \log(c)$, so that $x\log(x) = d$ for positive real $x$ and some real number $d$. Now calculus tells you that $f(x) = x \log(x)$ has derivative $1 + \log(x)$. This derivative is strictly positive for $x > \frac{1}{e}$. Hence $f(x)$ is strictly increasing on $[\frac{1}{e}, \infty)$, and $f(x)$ takes each value in $[\frac{-1}{e},\infty)$ exactly once
on that interval ( making use of Rolle's theorem, for example). This is as far as general calculus theory will take you.
As others have said if you want to determine exactly where the values are attained you have to use numerical methods, or known values of Lambert's W-function.


How to remove an object from JSON array when checkbox is deselected in Angular 4?

Question: 0:
CategoryId: "31b7a227-9fda-4d14-8e1f-1dee5beeccb4"
Code: "GMA0300"
Description: "PA-5215: Renamed"
Enabled: true
Favorite: false
Id: "26cfdb68-ef69-4df0-b4dc-5b9c6501b0dd"
InstrumentType: null
Moniker: "1GMA0300"
Name: "Celiac Disease Panel (tTG IgG, tTG IgA, DGP IgG)"
Tests: Array(3)
  0:
   Code: "GMA0304"
   Id: "e2bb4607-c227-4483-a3e9-55c1bc5a6781"
   Name: "Deamidated Gliadin Peptide (DGP) IgG"
 __proto__: Object
  1: {Id: "2fcd610f-d453-4c4f-a8dc-1a5f50e88548", Code: "GMA0301", Name:
 "Tissue Transglutaminase (tTG) IgA"}
  2: {Id: "de41b236-4866-419a-a6f4-5f7c1440d30f", Code: "GMA0302", Name:
 "Tissue Transglutaminase (tTG) IgG"}
 length: 3
 __proto__: Array(0)
 TestsSelectable: false

hey this is an array selectedPanels object which has another array of objects
i have mapped this in panel and panel has checkbox and Tests which is an array is expandable rows and has also checkbox
when i check the panel checkbox it checks all the child checkboxes of Tests and shows the length of Tests say 3
but when i click on each test it should be minus from Tests length say 3 - 1 = 2 it should show 2 now
but when i use splice it removes the whole row when i deselect the the each test checkbox or the already implementation is when i click on each test it deselect the parent panel checkbox too
i dont know what to
what is want is when i deselect the each test
it should not remove the text but decrease the length of array
you can see from that image
image
here is my html file

    <input type="checkbox" class="custom-control-input" [name]="panel.Id + '-' + panel.Moniker" [ngModel]="checkAllTestsSelected(panel)"
      (ngModelChange)="onPanelCheckboxUpdate($event, panel)" [id]="panel.Id + '-' + panel.Moniker">

 </ng-template>
 <ng-template ngbPanelContent>

  {{test.Name}}

    <input type="checkbox" class="custom-control-input" [name]="test.Id + '-' + test.Code"
           [ngModel]="testSelectionSession.SelectedPanelIds.indexOf(panel.Id) > -1 || testSelectionSession.SelectedPanelIds.indexOf(test.AssociatedPanel?.Id) > -1"
           (ngModelChange)="onTestCheckboxUpdate($event, test, panel)" [id]="test.Id + '-' + test.Code">

ts file
checkAllTestsSelected(panel: TestOrderPanel) {
  // get all individual test panels
  let individualTestPanelIds = panel.Tests.reduce((acc, test) => {
   if (test.AssociatedPanel) {
    acc.push(test.AssociatedPanel.Id);
  }
  return acc;
}, []);

// check if all individual test panels are selected
let allIndividualTestsSelected = individualTestPanelIds.reduce(
  (acc: boolean, panelId: number) =>
    acc && this.panelIds.indexOf(panelId) > -1,
  individualTestPanelIds.length > 0 &&
  panel.Tests.length === individualTestPanelIds.length
);

// if selected, remove all individual test panels and add the panel group
if (panel.Tests.length > 0 && allIndividualTestsSelected) {
  this.panelIds = this.panelIds.filter(
    panelId => individualTestPanelIds.indexOf(panelId) === -1
  );
  this.selectedPanels = this.selectedPanels.filter(
    selectedPanel => individualTestPanelIds.indexOf(selectedPanel.Id) === -1
  );
  this.panelIds.push(panel.Id);
  this.selectedPanels.push(panel);
  this.updateSession();
 }
  return this.panelIds.indexOf(panel.Id) > -1;
  }

 onPanelCheckboxUpdate($event: boolean, panel: TestOrderPanel) {
   let testPanelIds = panel.Tests.reduce((acc, test) => {
    if (test.AssociatedPanel) {
    acc.push(test.AssociatedPanel.Id);
  }

  return acc;
}, []);
// Wipe any duplicates
this.panelIds = this.panelIds.filter(
  panelId => panel.Id !== panelId && testPanelIds.indexOf(panelId) === -1
);
this.selectedPanels = this.selectedPanels.filter(
  selectedPanel =>
    panel.Id !== selectedPanel.Id &&
    testPanelIds.indexOf(selectedPanel.Id) === -1
);

if ($event) {
  this.panelIds.push(panel.Id);
  this.selectedPanels.push(panel);
   }
   this.updateSession();
 }

 onTestCheckboxUpdate($event: boolean,
                   test: TestOrderPanelTest,
                   panel: TestOrderPanel) {

let testPanelIds = panel.Tests.reduce((acc, test) => {
  if (test.AssociatedPanel) {
    acc.push(test.AssociatedPanel.Id);
  }

  return acc;
}, []);
let associatedTestPanels = this.testSelectionSession.IndividualTestPanelsForAll.filter(
  testPanel => testPanelIds.indexOf(testPanel.Id) > -1
);

let clickedTestPanel = associatedTestPanels.find(
  testPanel => (test.AssociatedPanel ? test.AssociatedPanel.Id : -1) === testPanel.Id
);

if (clickedTestPanel) {
  // Wipe any duplicates
  this.panelIds = this.panelIds.filter(
    panelId => clickedTestPanel.Id !== panelId
  );
  this.selectedPanels = this.selectedPanels.filter(
    panel => clickedTestPanel.Id !== panel.Id
  );

  // Add individual panel if checkbox selected
  if ($event) {
    this.panelIds = this.panelIds.concat(clickedTestPanel.Id);
    console.log(this.panelIds)
    this.selectedPanels = this.selectedPanels.concat(clickedTestPanel);
    console.log(this.selectedPanels)
  }
  }
  this.updateSession();
 }

array is in this.selectedPanels
how to solve this issue
can anyone help?
Answer: If you add an index to the ngfor loop in your template ('let i = index' in the code below), you can pass this to your onTestCheckboxUpdate() function and splice the source array at this point:
HTML file:

        {{item}}
        <button (click)="removeItem(i)">Remove '{{item}}' from array</button>

TS file:
items = ['cat','dog','mouse','frog','horse','bird'];

removeItem(itemIndex:number){
    this.items.splice(itemIndex, 1);
}

Does this achieve what you're looking for? Example of the basic concept here.
Comment: this.panel.Tests.splice(arrayIndex,i) where is this i coming from?
Comment: Sorry I've updated the example code so it's clearer what's happening. The i from the  template (which is the index of each item) is passed to the removeItem function, which removes one item from the array at that index. Is the behaviour of the Stackblitz what you're expecting?
Comment: i have added my image you can get an idea from that
Comment: Ah sorry that was a mistake - should have been a 1, as in, remove one item starting at index  arrayIndex.
Comment: i have applied that but it removing the whole like when i uncheck the test it gets deleted
Comment: Are you looking for a counter, so if two checkboxes are selected, the number of available tests is reduced by two, but they're not removed from the array?
Comment: no no i what i simply want is when i uncheck the individual test the counter should reduced by one but what it is doing right now is reducing the counter but removing the whole row as well idk why is that
Comment: Are you using Angular material checkboxes?
Answer: You can use the following approach to get the number of items which are checked, or not checked. Updated to add 'checked' property to each item in data array, below and on Stackblitz.
TS File:
items = [
    {name: 'cat'},
    {name: 'dog'},
    {name: 'horse'},
    {name: 'mouse'}
];

checkCount = this.items.length;

checkItem(itemIndex:number){
    if(this.items[itemIndex]['checked'] === undefined){
        this.items[itemIndex]['checked'] = false;
    } else {
        this.items[itemIndex]['checked'] = !this.items[itemIndex]['checked'];
    }
    this.checkCount = this.items.filter(item => item['checked'] === true || item['checked'] === undefined).length;
}

HTML File:

        {{item.name}}
        <input type="checkbox" checked (click)="checkItem(i)">

Check count: {{checkCount}}

Example here.
If you needed two-way binding, you could use a formControl to hold the 'checked' variable for each checkbox, rather than a plain boolean. You can see an example of this here.
Comment: but there is not checked flag coming from backend
Comment: This approach will still work with a slight adjustment - you just need to check for 'item[itemIndex]['checked'] === undefined' at the beginning of the checkItem function. If it is undefined, you add it as a property to the item object and, set it to false. if it isn't undefined, you reverse the value as per the example. Then in the array filter function, you check for 'checked === undefined || checked === true'. I'm away from my machine right now, but will update my answer later.
Comment: yeah sure please update it so i can have a better understanding thanks btw :)
Comment: Have updated my answer - let me know how you get on!
Comment: i was busy these 2 days i will implement it and let you know
thanks tho :)
Comment: I'd like to help but you've posted a lot of code so it's difficult to debug. If you make a Stackblitz with a sample of the panel.Tests JSON  and as simple logic as possible, I'll have a look.


Como pegar a variavel de ambiente do arquivo .env utilizando Typescript?

Question: Estou utilizando a biblioteca dotenv para pegar a chave de API do Google Maps que está no arquivo .env, eu tentei dessa forma:
Imagem
Só que retornou esse erro :
Type 'string | undefined' is not assignable to type 'string'.
Type 'undefined' is not assignable to type 'string'.
dotenv: https://www.npmjs.com/package/dotenv
Comment: Isso é normal por causa da tipagem dessa API do env. Coloque uma `!` no final do `GOOGLE_API`  ou um `AS string` e veja se resolve.
Answer: Bem eu estou com essa mesma dúvida atualmente...
Mas resolvi colocar uma exclamação após o uso dessa várialvel de ambiente, para o typescript não se preocupar com isso. Por que sabemos que essa várialvel de ambiente não vai deixar de existir ou ser undefined em algum momento dévido ao fato que nós mesmos vamos ter que declara-lá como váriavel de ambiente em hardcode no momento de fazer o deploy ou até no de desenvolvimento.


Under what conditions is the argument integral zero?

Question: In my studies in complex analysis, I came across the usage of the argument principle to find the number of zeroes and poles of a meromorphic function within a given region. While trying to solve some examples, I stumbled on the following:
Let $f$ be a meromorphic function defined on a subset $D\subset \mathbb{C}$ and let $x$ and $y$ lie in the upper-half plane and satisfy $f(x)=f(y)$. Moreover, on the straight line connecting $x$ and $y$, the imaginary part of $f$ is constant. I would now like to conclude that the integral along this path
$$
\int_x^y \frac{f'}{f} dz = \int_x^y \frac{d}{dz} \log (f(z))
$$
is well-defined on a single branch of the logarithm, because the fact that the imaginary part of $f$ is constant on this path  and that therefore we must have
$$
\int_x^y \frac{d}{dz} \log (f(z)) = \log(f(x))-\log(f(y)) = 0.
$$
Am I correct in thinking so? I believe I am not fully grasping why this might work or not.
Answer: You are right (provided that the integral exists, i.e. $f$ has no zero in the segment $[x,y]$). If $\operatorname{Im} f(\zeta) \equiv c$ on the segment $[x,y]$, then the image of the segment under $f$ lies in a domain where a holomorphic branch of the logarithm is defined, so $(\log\circ\, f)$ is a well-defined (holomorphic, of course) function in a neighbourhood of $[x,y]$ and the fundamental theorem of calculus then says that
$$\int_x^y \frac{f'(\zeta)}{f(\zeta)}\,d\zeta = \log f(y) - \log f(x) = 0.$$
If $c\neq 0$, or $c = 0$ and $\operatorname{Re} f(\zeta) > 0$ for all $\zeta\in [x,y]$, then $f([x,y]) \subset \mathbb{C}\setminus (-\infty,0]$, where the principal branch of the logarithm is defined. If $c = 0$ and $\operatorname{Re} f(\zeta) < 0$ for all $\zeta\in [x,y]$, then we can take a branch of the logarithm defined on the left half-plane. If $c = 0$ and the real part of $f(\zeta)$ takes positive as well as negative values, then $f$ has a zero in the segment $[x,y]$, and the integral doesn't exist.
Note that it is important that we have a branch of the logarithm defined in a neighbourhood of $f([x,y])$ to be able to conclude that the integral is zero. If we only know that $f$ has a logarithm $g$ in a neighbourhood of $[x,y]$, i.e. $f(\zeta) = e^{g(\zeta)}$ for all $\zeta$ in some neighbourhood of $[x,y]$, then
$$\int_x^y \frac{f'(\zeta)}{f(\zeta)}\,d\zeta = \int_x^y g'(\zeta)\,d\zeta = g(y) - g(x),$$
and then we can only conclude that the value of the integral is a multiple of $2\pi i$, since $g$ need not attain the same value in $y$ as in $x$.
Comment: Great! Thanks for the added detail, that made me see exactly why this all works.
Comment: Of course, geometrically, one can see that the integral vanishes since a curve with constant imaginary part cannot wind around $0$. But to rigorously prove that geometrically evident fact, you need an argument like the one given.
Comment: Exactly. My intuition was based on this geometrical picture, but felt it would be better to have an argument like the one given above. Thanks for you help!


Blazor MatTable Page size change

Question: I am using pagesize for no of row in the page but that not wotking
declare without ""
<code><MatTable Items="project" FilterByColumnName="Name" PageSize="12">
</code>
Need to change the number of rows per page in the table
Comment: Incomplete and unclear. When do you nedd to change it? runtime?
Comment: It could be just `PageSize="@pageSize"`
Comment:   declare int pagsize = 10; but 5 rows only display per page
Comment: It is a known issue. it's reported on GitHub. Not much to do right now.
Answer: Note that it is now fixed with last version. Should set it to respect the Enum (5,10,25,50,*) or it will not be displayed in the pagesize selection selectlist although it will work and display the exact number of rows you set.

Blazor MatTable Page size change


Using swiftmailer and sending attachments

Question: I am trying to modify a script to send a email with an attachment. It works right now but all the fields are required and I was wondering what I am missing to make it so the fields are not required.
<?php
if (($_POST)) {

$success = $error = false;

$post = new stdClass;

foreach ($_POST as $key => $val)
    $post->$key = trim(strip_tags($_POST[$key]));

    $dir = dirname(__FILE__);

    ob_start();
    require_once($dir.'/html.php');
    $html_message = ob_get_contents();
    ob_end_clean();

    require_once($dir.'/swift/swift_required.php');

    $mailer = new Swift_Mailer(new Swift_MailTransport());

    $message = Swift_Message::newInstance()
                   ->setSubject('Imperial Order') // Message subject
                   ->setTo(array($post->email => $post->name, 'email@example.com' => 'Janet McCauley')) // Array of people to send to
                   ->setFrom(array('firstname.lastname@example.com' => 'Imperial Order'))
                   ->setBody($html_message, 'text/html') // Attach that HTML message from earlier
                   ->attach(Swift_Attachment::fromPath($_FILES['attachment']['tmp_name'])->setFilename($_FILES['attachment']['name']));

    // Send the email, and show user message
    if ($mailer->send($message))
        $success = true;
    else
        $error = true;
}
?>

I believe it has something to do with the foreach but if I try taking it out it breaks the whole code. If anyone can help that would be great. The reason I am taking out the validation is because i'm wanting to do it on the client side instead of server side.
Answer: you can remove the for each but then you'll have to request each posted field individually and process/validate them one at a time instead of in a loop as the loop is pulling all the post vars to local vars.
Also you don't need to require the swift mailer includes etc inside of the loop they can be moved outside of the loop as can the $mailer = new transport start line that can all go outside of the loop
EDIT WITH EXAMPLE
if (isset($_POST)) { //BAD BAD BAD way of checking there's better ways

$success = $error = false;

$input1 = $_POST['input1'];
$input2 = $_POST['input2'];
$input3 = $_POST['input3'];
$input4 = $_POST['input4'];

    $dir = dirname(__FILE__);
    // THIS BIT IS RETARDED BUT LEAVING IT IN FOR NOW
    ob_start();
    require_once($dir.'/html.php');
    $html_message = ob_get_contents();
    ob_end_clean();
    // END RETARDED BIT
    require_once($dir.'/swift/swift_required.php');
    $mailer = new Swift_Mailer(new Swift_MailTransport());
    if (isset($_FILES) && strlen($_FILES['attachment']['name']) > 0) { //here we're checking that there is attachments if there are then we're going to do the attach sw code
        $message = Swift_Message::newInstance()
                   ->setSubject('Imperial Order') // Message subject
                   ->setTo(array($input1 => $input2, 'email@example.com' => 'Janet McCauley')) // Array of people to send to
                   ->setFrom(array('firstname.lastname@example.com' => 'Imperial Order'))
                   ->setBody($html_message, 'text/html') // Attach that HTML message from earlier
                   ->attach(Swift_Attachment::fromPath($_FILES['attachment']['tmp_name'])->setFilename($_FILES['attachment']['name']));
    } else {
        //non attach sw code
        $message = Swift_Message::newInstance()
                   ->setSubject('Imperial Order') // Message subject
                   ->setTo(array($input1 => $input2, 'firstname.lastname@example.com' => 'Janet McCauley')) // Array of people to send to
                   ->setFrom(array('email@example.com' => 'Imperial Order'))
                   ->setBody($html_message, 'text/html') // Attach that HTML message from earlier
    }
    //there's better ways of doing the above but as an example this will suffice.
    // Send the email, and show user message
    if ($mailer->send($message)) {
        $success = true;
    } else {
        $error = true;
    }
}
?>

Comment: if I wanted to keep the loop to process them but not validate them how would I do that.
Comment: The problem is that `foreach ($_POST as $key => $val)` loops through all POST'd inputs.  So leaving one blank will create a blank value/entry in your array which is whats breaking your send.  You could kinda get around it by leaving it as is but putting an `if (strlen($post->email)>0 && strlen($post->name)>0) { //code here }` around your $message block and the if statement below it.  That way it'd only attempt to send the mail if there were actually values in the input fields.
Comment: Could you tell me how to process each field then? I'm not exactly sure how I would do that... The main problem I am having is they dont want the upload field to be required.
Comment: added code example now it'll only work if there's only a single input for name/email address if you have multiple then you'll need to construct a recipient array before hand and push that to the sw object but thats like 2 lines of code.
Comment: when I try that it breaks the code...at first I thought it was missing a semi colon at the end of the setBody on the else statement but that didn't change anything...
Comment: I did miss the ; at the end of the ->setBody which will have broke it but I rushed it so I probably missed something else else where a }{ or () or something . The concept is right though so you can use it as a basis to improve/fix upon
Comment: Okay... well I figured out what was causing it but now when it loads it instantly sends the email. Then after it loads I try filling it out and its not passing the variables through...
Comment: thats to do with the very first line! as i say in the code `if (isset($_POST)) { //BAD BAD BAD way of checking there's better ways` a better way is putting a hidden field in your form and checking that the value of the hidden field `isset()` and that it matches a fixed string so i use for example `` then my check is `if(isset($_POST['action']) && $_POST['action']=="dosomething") {`
Comment: Okay that makes sense but what would be causing the input to not pass through? I'm just doing echo in the html.php document.
Comment: not entirely sure all I can assume is your input vars aren't being passed through to your html template properly or you may need to adjust html.php to allow for non loops as it may be looking for $key $var where its now $input1 $input2 etc.


aws api gateway lambda authorizer cognito-idp client get_user error

Question: I am creating a lambda authoriser.
In which I want to check that the user exists in my cognito user pool and then check some other things that I cannot do with the normal cognito authorizer.
The following code snippet produces the error:

NotAuthorizedException: An error occurred (NotAuthorizedException)
when calling the GetUser operation: Invalid Access Token

cognito_client = boto3.client('cognito-idp')

def lambda_handler(event, context):
    print(event)

    response = cognito_client.get_user(
            AccessToken=event["authorizationToken"]
        )

I'm testing it by passing the id_token I get when I login to cognito just like I do to test the normal cognito autozizer.
What is wrong is not id_token the token that I have to pass to the lambda autozizer ?
Isn't event["authorizationToken"] the token I should pass to get_user ?
How can I get from event the token that I have to pass to get_user ?
Answer: Login user should add following scope "aws.cognito.signin.user.admin" during log-in to use this method. If u have access token you may decode token and get same user details values from that token.


Content Security Policy directive: "frame-ancestors" missing but there?

Question: I am working on a nodejs electron app, in my index.html I have a "Content-Security-Policy" that looks like this
<!DOCTYPE html>

<meta http-equiv="Content-Security-Policy"
      content="
      default-src     'self' https://*.mydomain.tld;
      script-src      'self' https://*.mydomain.tld;
      style-src       'self' https://*.mydomain.tld;
      img-src         'self' https://*.mydomain.tld;
      font-src        'self' https://*.mydomain.tld;
      connect-src     'self' https://*.mydomain.tld;
      media-src       'self' https://*.mydomain.tld;
      object-src      'self' https://*.mydomain.tld;
      child-src       'self' https://*.mydomain.tld;
      frame-ancestors 'self' https://*.mydomain.tld;
      frame-src       'self' https://*.mydomain.tld;
      worker-src      'self' https://*.mydomain.tld;
      form-action     'self' https://*.mydomain.tld;
      block-all-mixed-content;
      ">

When I run the app it works perfectly fine all assets are loaded just fine but in the console I get the following error

Content Security Policies delivered via a  element may not
  contain the frame-ancestors directive. index.html: 4

I been trying to get rid of the error and looking for what maybe causing it but can't find anything, all to me appears to be correct yet I still receive the error, I also thought that the error maybe caused by the server @https://*.mydomain.tld so I tried this
<!DOCTYPE html>

<meta http-equiv="Content-Security-Policy"
      content="
      default-src     'self';
      script-src      'self';
      style-src       'self';
      img-src         'self';
      font-src        'self';
      connect-src     'self';
      media-src       'self';
      object-src      'self';
      child-src       'self';
      frame-ancestors 'self';
      frame-src       'self';
      worker-src      'self';
      form-action     'self';
      block-all-mixed-content;
      ">

Which caused the exact same error, I could just ignore the error completely as the app does work correctly and the error does not seem to be causing any issues however if someone has any idea what maybe wrong I would really appreciate it.
Edit: When I removed the frame-ancestors leaving the tag looking like this
<!DOCTYPE html>

<meta http-equiv="Content-Security-Policy"
      content="
      default-src     'self' https://*.mydomain.tld;
      script-src      'self' https://*.mydomain.tld;
      style-src       'self' https://*.mydomain.tld;
      img-src         'self' https://*.mydomain.tld;
      font-src        'self' https://*.mydomain.tld;
      connect-src     'self' https://*.mydomain.tld;
      media-src       'self' https://*.mydomain.tld;
      object-src      'self' https://*.mydomain.tld;
      child-src       'self' https://*.mydomain.tld;
      frame-src       'self' https://*.mydomain.tld;
      worker-src      'self' https://*.mydomain.tld;
      form-action     'self' https://*.mydomain.tld;
      block-all-mixed-content;
      ">

The error went away, am I not supposed to add that?
Comment: Yeah, the error message explicitly says, *Content Security Policies delivered via a `` element may not contain the frame-ancestors directive*. The frame-ancestors directive has no effect in meta elements. See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors (*This directive is not supported in the `` element.*)  and https://w3c.github.io/webappsec-csp/#meta-element (*Note: The Content-Security-Policy-Report-Only header is not supported inside a meta element. Neither are the report-uri, frame-ancestors, and sandbox directives.*)
Comment: So if you specify frame-ancestors with meta anyway, it doesn't cause any failures — it just causes the browser to report the error message cited in the question. Per spec, it just gets removed from the policy. See https://html.spec.whatwg.org/multipage/semantics.html#attr-meta-http-equiv-content-security-policy (*4. Remove all occurrences of the report-uri, frame-ancestors, and sandbox directives from policy.*)
Answer: Because this directive is not supported in the meta element.
Look at https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/frame-ancestors.
Only on the "response" from the server.

Content Security Policy directive: “frame-ancestors” missing but there?


Why do T prior and likelihood make a bimodal posterior?

Question: In this post, the author shows that when a likelihood and prior are both T-distributed with $2$ degrees of freedom, the posterior is bimodal. The given reason is that

The two modes persist - the extra mass in the tails means each distribution finds the other's mode more plausible and so the average isn't the best "compromise".

The distributions are
$$y \sim T(\text{df} = 2, \mu = \mu_0)$$
$$\mu_0 \sim T(\text{df}=2, \mu = 10)$$
What exactly does it mean that each distribution finds the other's mode more plausible? Is this something peculiar about the T distribution or can this be generalized elsewhere?
Code to reproduce the results available here.
Comment: For a 2D problem, you can plot the log prior and log likelihood together to see why this happens.  Ben Bolker tweeted the plots [here](https://twitter.com/bolkerb/status/1701344639280693567).  You can see that for that example, the sum of the log prior and log likelihood results in a bimodal log posterior.
Comment: I'm a bit confused, where in the link does the poster show that the likelihood and prior are t, 2df distributed?
Comment: The simplest explanation is that the $t$ likelihood is the inverse of a polynomial. If the data contains enough outliers and a few observations, this likelihood will be multimodal.
Answer: The post shows a "Bayesian surprise" setting, where the data are surprisingly far from the center of the prior.  In this setting, the location and shape of the posterior is sensitive to the rate of decrease of the tails of the prior and likelihood.

for Normal data and prior, the posterior is Normal and is between the data mean and the prior mean
for $t$ data and prior, sufficiently far apart, the posterior is bimodal
for Laplace data and prior, the posterior is flat across a wide interval
and other things for other examples

I have an interactive version here, and Tony O'Hagan analysed the location problem completely in JASA in 1990


overriding ubercart - add to cart button

Question: I try to override add to cart button with hook form alter in custom module with this function but I got an error Fatal error: fatal flex scanner internal error end of buffer missed in. What can be the problem?
function uc_button_form_alter($form_id, &$form_state, $node) {
  if ($form_id == 'edit-submit-' . $node->nid) {
    $form['submit']['#attributes']=  array(
      'class' => 'node-add-to-cart',
      'xxx' => 'xxx',
    );
  }
};

Thank you
Answer: In D7, below is my solution for different product classes.
/* Overrides the Add to Cart form text*/
if ( !empty($form['nid']) ) {
  $node = $form['nid']['#value'];
}
else {
  $node = 0;
}
if (($form_id == 'uc_product_add_to_cart_form_'.$node) and ($form['node']['#value']->type =='uc_recurring_subscription')){
   $form['actions']['submit']['#value'] = t('Subscribe');
}

if (($form_id == 'uc_product_add_to_cart_form_'.$node) and ($form['node']['#value']->type =='credit')){
   $form['actions']['submit']['#value'] = t('Buy');
}

For regular product or just one product class, this should work.
/* Overrides the Add to Cart form text*/
if ( !empty($form['nid']) ) {
  $node = $form['nid']['#value'];
}
else {
  $node = 0;
}
if (($form_id == 'uc_product_add_to_cart_form_'.$node){
   $form['actions']['submit']['#value'] = t('Buy now');
}

Answer: Your function's arguments are wrong.
See hook_form_alter docs.
So basically you need to rewrite your function as follows.
First, grab the correct form ID.form_alter functions don't have a $node but in some forms, full node object form is in $form.
So use the following code. You will now see at least 2 message on your messages area with form ID and array explanation of $form.
function uc_button_form_alter(&$form, &$form_state, $form_id) {
  drupal_set_message($form_id);
  drupal_set_message('
'.print_r($form, 1).'
');
};

Now, check if the node ID you are looking for is available in the $form array. (in most cases, it's in $form['#node']).
Now you can change the function to the real code.
function uc_button_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['#node']->nid) && $form_id == 'edit-submit-' . $form['#node']->nid) {
    $form['submit']['#attributes']['class'] = 'node-add-to-cart';
    $form['submit']['#attributes']['xxx'] = 'xxx'; // we don't want  to clear existing values.
  }
};

However, even this implementation is not necessary. You can make use of default classes with tricky nesting if you only want to add a class to the button.
Update after 3rd comment:
Try this:
function uc_button_form_alter(&$form, &$form_state, $form_id) {
  if (isset($form['nid']['#value']) && $form_id == 'edit-submit-' . $form['nid']['#value']) {
    $form['submit']['#attributes']['class'] = 'node-add-to-cart';
    $form['submit']['#attributes']['xxx'] = 'xxx'; // we don't want  to clear existing values.
  }
};

Comment: Thank you for quick answer. I tried your code in custom module but it is not working. I use D6. I know that `function uc_product_add_to_cart_form` is the function I want to override. My aim is to add some additional code inside button's code to track clicks, since I am going to use ajax cart. I tried also a variation of a snippet I found here just to see if it works http://pastebin.com/btbuELMM `function xxx_uc_catalog_buy_it_now_form_alter(&$form, &$form_state) {
  $form['submit']['#value']=  t('Yes i want one');
}` none from above works
Comment: can you post a screenshot of the form array output ? We can't code blindly :)
Comment: see the update pls
Comment: No change. To override all buttons I use `function acquia_prosper_button($element)` put inside template.php. I tried to remove it in case it fights but the html code is not changed at all.


simple function $f(x)$ for which $x^{1/x} -1 \sim f(x)$ as $x \rightarrow \infty$.

Question: $f(x) \sim g(x)$ iff $\lim_{x \rightarrow \infty} \frac{f(x)}{g(x)} = 1$. Find a simple function $f(x)$ for which $x^{1/x} -1 \sim f(x)$ as $x \rightarrow \infty$.
I know that $\lim_{x \rightarrow \infty} x^{1/x} = 1$ so I was thinking of using a function that tends towards $0$. However, I didn't really get very far past that.
Comment: Do you know what is a simple function for which $e^x-1\sim f(x)$ as $x\to0$? Hint: these questions are kinda related.
Comment: What do you want to count as "simple"?  As functions go, $f(x) = x^{1/x}-1$ isn't so terrible.
Comment: You don't know a function similar to $0$ at infinity?
Comment: For starters, you need to define precisely what you mean by $\sim$.
Answer: $$x^{\frac{1}{x}}-1=e^{\frac{\log x}{x}}-1\underset{x\rightarrow +\infty}{\sim}\frac{\log x}{x}$$
because $\lim\limits_{x\rightarrow +\infty}\frac{\log x}{x}=0$ and $e^t-1\underset{t\rightarrow 0}{\sim}t$.


How many rows contain a specific value using php and mysqli

Question: I have a table "bookings" that looks like
bookings
    id      id_class    date                    day         name
    1       2           2016-03-10 16:00:00     monday      Fredrik
    2       5           2016-03-11 16:00:00     tuesday     Richard
    3       7           2016-03-11 18:00:00     tuesday     Sara
    4       4           2016-03-11 15:00:00     tuesday     Fredrik

Then I extract that table using php
<?php
    $result = $con->query("select * from bookings");
<?

What I want now is a php function that tells me how many rows that contain a specific entry such as "id_class=2" or how many rows contain (name=Fredrik) where the answer should be between 0 and a positive number. Is there a way for this?
Comment: If you only want the count run `"SELECT COUNT(*) FROM bookings WHERE id_class=2"`
Comment: Use a WHERE clause in your SQL query - http://www.mysqltutorial.org/mysql-where/ - and use COUNT - http://dev.mysql.com/doc/refman/5.7/en/counting-rows.html
Comment: Yeah, but what I want is to make just one query and then using php code to extract what I want without having to make more queries. Your suggestions imply one query per row count, right?
Comment: if you want to do it purely in PHP, it's going to be a lot slower, and a lot more PHP Code, and most people will wonder why you insist on doing it in PHP rather than letting the database do what it's designed too do.... but fetch all your records into a PHP array, use array_filter, and then count; or apply an if test with an incrementing counter as you fetch each row
Answer: Use where to get specific condition
SELECT COUNT(*) FROM bookings WHERE id_class=2

SELECT COUNT(*) FROM bookings WHERE name='Fredrik'


Create custom admin theme removes theme-primary-local-tasks from admin view

Question: I am creating an admin theme to manage certain content type. I was able to use Claro as base theme so everything is there. However, The primary-local-tasks items ( edit, view, delete..) are missing. Instead is rendering my Navbar into the admin view.. I am not sure how or what is going on. This is my first time creating an admin theme any guidance would b e appreciate it.
this is before

This is after:
Answer: When you install a theme Drupal tries to build a block layout automatically, but the result only works for front-end themes. For admin themes you need to provide a default block layout. See the default config of the base theme:
core/themes/claro/config/optional/
<code>block.block.claro_breadcrumbs.yml
block.block.claro_content.yml
block.block.claro_help.yml
block.block.claro_local_actions.yml
block.block.claro_messages.yml
block.block.claro_page_title.yml
block.block.claro_primary_local_tasks.yml
block.block.claro_secondary_local_tasks.yml
</code>
You can copy these files, adjust the file names and replace the theme name within the file. If you copy the files from an exported config then remove UUID and config hash.
If you want to install this only a few times you can also visit the block layout and move/create blocks until it looks the same as the layout of the installed base theme. After that you can always copy the result of the exported config to the themes folder to make further installations easier.
Comment: Sorry didnt realize your answer, I will give it a try and update here what i get. Thank you very much
Comment: I copied the files and changed the theme name to my cusomt_admin. I moved the files to cusom_admin/config/optional/..
I am not sure how to test if its actually working.. still having my main navbar in my admin theme instead of the task tabs
Comment: To test the default config files you have to uninstall and re-install the theme.
Comment: okey, unsintalling and re-installing got me somewhere, now the navbar is no more but the task tabs are also not showing.
Comment: I forgot to change the names of the id as well thats why it wasnt working. now its working. Thank you very much.


Angular Datatables Not Applying Correctly

Question: Here is my html code:

Here is my controller:
(function () {

var manageBackOrdersController = function ($scope, $http, $routeParams) {

    $http({
        url: '/Profiles/firstJson',
        method: "GET",
        params: {}
    }).success(function (data) {
        var JSON = data;
        $scope.data = JSON;

    });

}

manageBackOrdersController.$inject = ['$scope', '$http', '$routeParams'];

angular.module('customersApp')
  .controller('manageOrdersController', manageOrdersController);

angular.module('datatablesSampleApp', ['datatables'])
    .controller('withAjaxCtrl', function ($scope, DTOptionsBuilder, DTColumnBuilder) {
        $scope.dtOptions = DTOptionsBuilder.fromSource('scope.data')
           .withPaginationType('full_numbers');
        $scope.dtColumns = [
            DTColumnBuilder.newColumn('Customer').withTitle('Customer')
        ];
    });

}());

When I run my page I get an error saying "Error: [ng:areq] Argument 'withAjaxCtrl' is not a function, got undefined". My data is found stored in $scope.data.
Answer: Respectfully, Sameer's answer is incorrect. It took me two long arduoous days but I found the solution.
What you must keep in mind are 2 concerns:

Use DTOptionsBuilder.fromFnPromise, and
Have your promise inside your factory.

This is the correct solution:

'use strict';
 WithResponsiveCtrl.$inject = ['DTOptionsBuilder', 'DTColumnBuilder', 'simpleFactory'];
 angular.module('showcase.withResponsive', [])
.controller('WithResponsiveCtrl', WithResponsiveCtrl);

function WithResponsiveCtrl(DTOptionsBuilder, DTColumnBuilder, simpleFactory) {
var vm = this;
vm.dtOptions = DTOptionsBuilder.fromFnPromise(function() {
    return simpleFactory.getData(); }).withPaginationType('full_numbers')
    // Active Responsive plugin
    .withOption('responsive', true);
vm.dtColumns = [
    DTColumnBuilder.newColumn('id').withTitle('ID'),
    DTColumnBuilder.newColumn('firstName').withTitle('First name'),
    // .notVisible() does not work in this case. Use .withClass('none') instead
    DTColumnBuilder.newColumn('lastName').withTitle('Last name').withClass('none')
]; }

simpleFactory.$inject = ['$http', '$q', '$log'];
angular.module('showcase.withResponsive').factory('simpleFactory', simpleFactory);
function simpleFactory($http, $q, $log) {
return {
    getData: function () {
        var deferred = $q.defer();
        $http.get('api/data.json')
            .success(function (data) {
                deferred.resolve(data);
            }).error(function (msg, code) {
                deferred.reject(msg);
                $log.error(msg, code);
            });
        return deferred.promise;
    }
} };

Comment: thanks for the update @user1177440 , that answer was just given on the top of my head that time, thus mentioned 'try replacing', anyways I will remove my answer and upvote yours, keep up the good work
Comment: Oh I tried deleting it, it says I cant delete an accepted answer


how to make this div margin to zero and more nature

Question: I have a page here http://pastebin.com/Hva36KEn  ,and I'm new to css. How to make the #header div's margin zero and align it to page's top and make it more nature? Any help would be greatly appreciated!
Comment: Please put your code here, not on pastebin.
Comment: I wouldn't want all that code in the question.
Comment: It's looking fine for me in Firefox, which browser are you using?
Answer: Make sure the body and html elements' margin or padding equal zero on them. This may cause your #header to be pushed down.
A bit off-topic: You wrote that you're new to CSS and that's why I thought I would include this. Don't use inline CSS. This is a good place to read about different ways to apply CSS: http://www.w3schools.com/css/css_howto.asp
Comment: How do you figure out how to write `#header { margin: 0; padding: 0 }`, but you can't make the leap to doing the same thing for `body` or `html`?  All browsers have some form of default styling for most elements.  Just because you didn't define margin/padding doesn't mean it isn't there.
Comment: it doesnt have those elements.
Comment: Yeah it does. I see  and  in your code.
Comment: how to modify it, pal! more detail please I'm not clear it


How to Add Not NULL constrain for exisitng table column?

Question: I have table with data Now I'm trying to alter my table
I tried both ways but both show same error
<code>ALTER TABLE sample MODIFY latitude  NUMERIC(10, 7) NOT NULL DEFAULT 0;

ALTER TABLE sample CHANGE latitude latitude NUMERIC(10, 7) NOT NULL DEFAULT 0;
</code>

#1138 - Invalid use of NULL value

I think I have some null data for latitude column need Delete/modify those column first then only it will work or any other ways please suggest!
Comment: I don't think so. I think that's the only way to do it.  Default values only work on new records.
Comment: are there NULL values for latitude in the table, you need assign default value of 0 and then do alert
Comment: yes . Just i was updated to 0 @radar
Comment: @Tom it's working now but is there any way without update to 0
Answer: It looks like you still have null values in that column, first update them.

UPDATE sample SET latitude = 0 WHERE latitude IS NULL;

  and then

      ALTER TABLE sample MODIFY latitude  NUMERIC(10, 7) NOT NULL DEFAULT 0;


Firebase functions failing to deploy: Missing URI for HTTPS function in printTriggerUrls. This shouldn't happen

Question: I have an express app (API only) that is working locally cd functions && npm start but for whatever reason fails to deploy.
running firebase --debug deploy or firebase --debug deploy --only functions yield the same result which I don't understand.
Seeking advice for how to fix this or even how to dig into these firebase logs to better determine the problem
[info] Functions deploy had errors with the following functions:
    server(us-central1)
[debug] [2021-12-29T02:27:03.977Z] Missing URI for HTTPS function in printTriggerUrls. This shouldn't happen
[info] i  functions: cleaning up build files...

Answer: I also faced the same problem. The solution was removing this line:
logger.info("Hello logs!", {structuredData: true});

Example code:
export const helloWorld = region(regionName).https.onRequest((_, response) => {
    // logger.info("Hello logs!", {structuredData: true});
    response.send("Hello from Firebase!");
});


How to setup web.config to use SmtpClient

Question: I'm not even sure how to word the question, but here is what I am trying to do. I have a PHP website hosted on Azure with one CSHTML page found below that is a simple contact form. Once I try adding
    System.Web.Mail.SmtpClient client = new  System.Web.Mail.SmtpClient();

I get the most unhelpful runtime error of "An application error occurred on the server." and nothing else to help me. What do I need to include for this to work? I tried making a web.config file like :
<configuration>
<system.web>
<pages>
  <namespaces>
    <add namespace="System.Web" />
    <add namespace="System.Web.Mail" />
  </namespaces>
</pages>

and then I grabbed all my DLL files from another project and created a Bin folder in the wwwroot directory and put them in there. Any help would be greatly appreciated.
Here is the Contact form that works until I add the SmtpClient:
@using System.Web;
@using System.Web.Mail;
@{
<title>Contact Me</title>

var fName = HttpContext.Current.Request["fName"];
var lName = HttpContext.Current.Request["lName"];
var eMail = HttpContext.Current.Request["eMail"];
var qComment = HttpContext.Current.Request["qComment"];
var Submit = HttpContext.Current.Request["Submit"];
}

@if (HttpContext.Current.Request.HttpMethod.ToString() == "POST")
{

You are POST

 System.Web.Mail.SmtpClient client = new  System.Web.Mail.SmtpClient();
}

Have a question? Feel free to contact me:

<form method="post">

First Name:

<input type="text" name="fName" value="@fName" />

Last Name:

<input type="text" name="lName" value="@lName" />

E-mail:

<input type="email" name="eMail" value="@eMail" />

Question/Comment:

<textarea name="qComment" rows="10" cols="20">@qComment</textarea>

<input type="submit" name="Submit" value="Submit" />

</form>

Comment: PHP webapp with cshtml page ! how does that happen
Comment: Here is for webmatrix: http://www.w3schools.com/aspnet/webpages_php.asp  . Anyway, I just said screw it and created a new website project in Visual Studio and added my entire website just to make that one darn page. If anyone is curios why I did this its because I have a student subscription to Azure and I am not able to use sendgrid :( and I wasn't having much luck figuring out how to modify php.ini in Azure.
Comment: in azure webapps you can add a .user.ini file to your root directory and give your webapp a restart, that .user.ini is considered your php.ini file.
Comment: Oh, I see. Thanks for the tip.
Answer: Instead of crossing two different languages I found Swiftmailer for php and I used that.


Computing gcd without modular arithmetic

Question: What will make the following specification complete?
$gcd(x,y) = gcd((x-y)/2,y)$ when $x,y$ are odd
$gcd(x,y) = gcd(x/2,y)$ when $x$ is even and $y$ is odd
$gcd(x,y) = gcd(x,y/2)$ when $x$ is odd and $y$ is even
Will the $gcd(x,y) = gcd(x/2,y/2)$ when $x$ and $y$ are both even? How do I know what value to "return" as the gcd of $x$ and $y$?
Comment: Consider $x=2^AC,y=2^BD$ where $C,D$ are odd and  integer $A,B\ge0$
Comment: Questions like "Will the $\gcd(x,y)=\gcd(x/2,y/2)$ when $x$ and $y$ are both even?"can be easily answered  by considering a couple of examples.
Answer: Of course $\gcd(x,y)=2\cdot\gcd(\frac x2,\frac y2)$ if $x,y$ are both even!Note that once you have extracted the maximum possible power of $2$ with this last rule, you can continue only with your other three rules until one of $x,y$ becomes $1$.
Comment: Can you elaborate a little? What conditions needs to hold for this equation to be true? When will it give us the gcd for any two numbers x and y?
Comment: What do you mean by "maximum possible power of 2?"


Graph and statistics multiple regression show different things

Question: I've run a multiple regression to find out if visual memory declines differenty for the autism group than for the controlgroup.
I did find a significant main effect of age, showing that with increasing age visual memory declines for both groups. However, memory declines the same for autism as for controls over age, so there was no significant interaction effect.
But when I graph my findings in a line graph to compare the two lines (autism vs. control), you can see that memory declines less for the autism group. This implies that autism is a sort of safeguard for visual memory decline.
Concluding: my p-values were not significant, showing a parallel development of memory over age, but my graph shows that autism protects for a significant memory decline compared to the control group.
My question is what can I conclude from these findings? Should I just stick with my non-significant p-values? Or should I also write down that the graph shows something else?
My hypothesis was that autism was a safeguard for visual memory decline. Can I conform or reject this hypothesis based on my inconsistent findings?
Answer: First of all, a graph represents the trends in your sample but not in your population. Also, I assume that the number of the controls is greater than the number of idividuals with ASD. Thus they have greater variance and there could be some influencial points that make the difference.
You should first find if there are any influential points in your regression model, using HAC in R or UniODA. This will actually show you if your graph is manipulated by a small group of points.
Even if this is not the case, the difference that you clearly noticed through the graph seems to be random, according to the model and thus you have no statistical significance.
Also, you should consider change your method by applying a different set of tests to the idividuals if you are convinced that there is a safeguard.
Please provide us with more information about the method and the tools used to conduct the analysis in order for the answer to be more specific.
Comment: Yes your graph seems manipulated and your statistics are backing this hypothesis up. Surely I am not 100% sure unless I see the data, but it seems legit. My advice: do not try to predict classes with low amount of data. Focus on the class you have the most.
Comment: Thank you for your comment! Now that you point it out I definitely believe that my graph is manipulated by a small group of points. My controlgroup (N = 129) is indeed bigger than my autism group (N = 76). I was interested in subgroups as well, namely a 65+ subgroup and 30-64 years old subgroup. My 65+ subgroup consists of only 27 people, with N = 5 for autism and N = 22 for my controlgroup. I am aware of the fact that this is a extremely small sample size for my subgroup. So based on that: I believe I can assume my statistics are telling me the truth but not my graph?
Comment: Also, in my graph you can see that autism and control show a parallel decline over time till age 65, after age 65 the lines are still parallel but the line for autism lays way above the line for controls. Is this because of that small sample size for the 65+ subgroup?
Comment: Well the problem lies in your sample size. If you want to analyze the difference between the two subgroups you should consider a non parametric method like a Mann Whitney test for the medians. Then you should choose a larger subgroup (eg 20-40 years old) in order to explain it with regression.
Comment: Is there a non parametric method for a multiple regression or MANOVA? I already did run the mann whitney, but my supervisor didn't agree with it, because he said it wasn't a replacement for the MANOVA (I used the MANOVA for groupcomparisons). Also, I can't choose a larger subgroup, I got this dataset from my supervisor and I'm already in the last phase of my thesis. The only thing I have to do is to write a discussion and conclusion. But what you're saying might be an idea for future research. Do you agree with that?
Comment: But concluding: my graph is not reliable because the small sample size in the subgroups? So I can't conclude that autism is a safeguard just because my graph says so. I need to stick with my statistics, concluding a parallel age-decline in visual memory for both groups. However because of the sample size problem, my statistics might me biased as well. So I would need to discuss this point in my thesis, is that correct?
Comment: Sorry for the late response. The Mann Whitney solution is just a test between two variables. Should you need a multivariable test consider using bootstraping or the friedman's test with the iman-davenport extension which is for nonparametric tests for N×N comparisons.
Comment: Thank you for help! This sure is usefull information and knowledge I can use for my thesis.