How to curry a C/C++ macro?

Question: I have a macro
DECLARE_SOMETHING(X, Y) {X, Y}

Which because of macro callbacks, I want to invoke in two steps as such
CURRIED_DECLARE_SOMETHING(X)(Y)

But how can I do that ?  I don't really mind if DECLARE_SOMETHING exists really, I just want to write something as simple as {X, Y} for the declaration but call it curried.
I tried stuff like this, but I don't know how to substitute the ??? with the value given to Y.
#define CURRY(BODY, Y) BODY(Y)
#define CURRIED_DECLARE_SOMETHING(X) CURRY( DECLARE_SOMETHING(X, Y), ??? )

Any help would be appreciated.
Thanks.
Comment: Functional programming with macros... this ought to be interesting.
Comment: I'm having issues with this as it's before my lunch and it has curry written everywhere
Comment: @YSC yeah, but Boost devs are raging dark arts gurus in permanent berserk mode.
Comment: Btw [What is the XY problem?](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem). If you ever find yourself in obscure macros like these, something in your design has gone terribly wrong.
Comment: @Quentin I concede on that point.
Comment: It depends on what/if anything the macro should return.
Comment: I'm not clear what your intent here is? Is it that you want to generate a function name based on the name Y and then call it with the parameter X?
Comment: I've starred the question, grabbed some popcorn. I really hope someone has an answer.
Comment: @Lundin Not necessarily. Boost is full of macros like OP needs. I guess their example with `{X, Y}` _made_ you think of an XY problem :D.
Comment: @YSC Boost does however serve a purpose as sandbox playground for all kinds of language features. Therefore it is supposed to be experimental, rather than canonical.
Comment: And here I was reading "I **fried** stuff like this". I should get my lunch
Answer: You can get close by ending the definition of CURRIED_DECLARE_SOMETHING with the name of another macro, which will then be invoked by the (Y):
#define DECLARE_SOMETHING(X, Y) {X, Y}
#define LPAREN (
#define RPAREN )
#define EXPAND(x) x
#define CURRIED_DECLARE_SOMETHING(X) DECLARE_SOMETHING LPAREN X, CURRIED_DECLARE_SOMETHING_2
#define CURRIED_DECLARE_SOMETHING_2(Y) Y RPAREN

Now, EXPAND(CURRIED_DECLARE_SOMETHING(X)(Y)) expands to {X, Y}.
You can extend this to add as many parameters as needed:
#define CURRIED_DECLARE_SOMETHING(X) DECLARE_SOMETHING LPAREN X, CURRIED_DECLARE_SOMETHING_2
#define CURRIED_DECLARE_SOMETHING_2(Y) Y, CURRIED_DECLARE_SOMETHING_3
#define CURRIED_DECLARE_SOMETHING_3(Z) Z RPAREN

I'm not seeing an easy way of avoiding that extra EXPAND though. You cannot just write DECLARE_SOMETHING(x, CURRIED_DECLARE_SOMETHING_2, because that way, the complete CURRIED_DECLARE_SOMETHING_2(Y) will be taken as the macro argument un-expanded, and as there is no closing ) prior to the expansion, the preprocessor will continue looking for a closing ).
Comment: This is amazing! How do you generalize from 2 parameters to n?
Comment: @YSC There's nothing preventing `CURRIED_DECLARE_SOMETHING_2`'s definition from also ending in a macro name. I've edited to include an example of that.
Comment: I intend to use the call _inside_ a macro, so the EXPAND is not a big deal for me.  That's a great solution !  Many thanks !
Comment: Macro pornography? Or suicidal thoughts? I strongly discourage anyone from using this king of macros. Error prone, difficult to debug and understand (lest say after couple of months).
Comment: It seems not working on clang 16, complaining `call to undeclared function 'DECLARE_SOMETHING'`

How to curry a C/C++ macro?


skew symmetric matrice

Question: Let $A$ be a matrice with real entries and $A^T=-A$ with eigenvalues $\pm i\lambda$ with $\lambda\in\mathbb R_{\gt0}$ with respective eigenspaces of dimension $1$ (i.e. $\dim \operatorname{Eig}_{i\lambda,A}=1$).
Let $u,v$ be real vectors of norm $1$ s.t. $u\bot v$ and $A^2u=-\lambda^2u$ and $A^2v=-\lambda^2v$.
Q1: Is it true that now $Au=-\lambda v$ and $Av=\lambda u$ holds? (Up to permutation of $u$ and $v$.)
Q2: Is it possible to express a possible pair of $u$ and $v$ in terms of the (complex) eigenvectors of $A$?
I came to this question while trying to prove this: https://en.wikipedia.org/wiki/Skew-symmetric_matrix#Spectral_theory.
Edit: I just got the answer to the first part (Q1) after asking. $(Au)^Tu=-u^TAu$ so $u\bot Au$.
Answer: If $u$, $v$ are of norm one then it is true (up to a global sign).
Q1: A better approach is perhaps to take one of them, say $u=-\lambda^{-2} A^2u$ and define $v=\lambda^{-1} Au$.
Then the couple $u,v$ verify the wanted properties (almost by definition).
Q2:We then also have $A(u\pm i v) = \pm i \lambda (u \pm v)$.
Comment: Did you mean $A(u\pm iv)=\pm i\lambda(u\pm iv)$? This is really nice. Is there something fundamental behind this that I was missing?
Comment: Thanks¸ indeed the $\lambda$ was missing. I don't know if it is very fundamental, but restricting to the 2D subspace ${\rm Span\;}\{u,Au\}$ the map $A$ acts like a rotation by 90 degrees, whence the $i$, times a homothetie, whence the $\lambda$. The complex notation captures all of this in one go.

skew symmetric matrice


Criar um arquivo ".TXT" de configuração

Question: Meu problema é o seguinte, preciso fazer um arquivo configuravel para integrar ao meu projeto, segue o formato dele atualmente:
PRINTER = 127.0.0.12
PRINTER_PORT = 9100

Gostaria de formatar ele pra esse estilo:
[PRINTER]
PRINTER = 127.0.0.12
PRINTER_PORT = 9100

Atualmente estou utilizando o metódo de Dictionary pra obter os dados, tem alguma opção melhor? Já que se usar colchetes pra destaque no arquivo minha função não os lê.
Função:
var dic = File.ReadAllLines("config.txt")
          .Select(l => l.Split(new[] { '=' }))
          .ToDictionary(s => s[0].Trim(), s => s[1].Trim());
                VariaveisGlobais.DEFAULT_PRINTER = dic["PRINTER"];
                VariaveisGlobais.DEFAULT_PRINTER_PORT = dic["PRINTER_PORT"];

Answer: Se o formato é semelhante ao do .ini pode experimentar algo pronto, procurar no nuget, exemplo: https://www.nuget.org/packages/ini-parser/, para instalar:
PM> Install-Package ini-parser -Version 2.5.2

A vantagem dessa lib especifica é que ela não depende do WindowsAPI, o que é vantajoso para portar seu código para outros ambientes.
Exemplo de uso:
Adicione as classes:
using IniParser;
using IniParser.Model;

Para carregar o arquivo:
var parser = new FileIniDataParser();
IniData data = parser.ReadFile("Configuration.ini");

Para ler como string:
 string useFullScreenStr = data["UI"]["fullscreen"];

No exemplo se o valor for "true" você pode fazer o parse assim:
bool useFullScreen = bool.Parse(useFullScreenStr);

Comment: Nem sabia que tinha algo pronto pra um parser, realmente ajudou!

Criar um arquivo ".TXT" de configuração


Running and debugging tests in a Docker container

Question: I want to dockerize my entire node.js app and run everything inside a docker container, including tests.
It sounds easy if you're using PhantomJS and I actually tried that and it worked.
One thing I like though about running tests in Chrome - easy debugging. You could start Karma server, open devtools, set a breakpoint in a test file (using debugger statement) and run Karma - it will connect to the server run tests, and stop at the breakpoint, allowing you from there to do all sorts of things.
Now how do I do that in a docker container?

Should I start Karma server (with Chrome) on a hosting machine and tell somehow Karma-runner inside the container to connect to it, to run the tests? (How do I do that anyway?)
Is it possible to run Chrome in a docker container (it does sound like a silly question, but when I tried docker search desktop bunch of things come up, so I assume it is possible (?)
Maybe it's possible to debug tests in PhantomJS (although I doubt it would be as convenient as with Chrome devtools)

Would you please share your experience of running and debugging Karma tests in a docker container?
upd: I just realized it's possible to run Karma server in the container and still debug tests just by navigating to Karma page (e.g. localhost:9876) from the host computer.
However, I still have a problem - I am planning to set and start using Protractor as well. Now those tests definitely need running in a real browser (PhantomJS has way too many quirks). Can anyone tell me how to run Protractor test from inside a docker container?
Answer: I'm not aware of Protractor and it's workflow, but if you need a browser inside a container, did you see this article? I'll take the liberty for quoting this:
$ docker run -it \
    --net host \ # may as well YOLO
    --cpuset 0 \ # control the cpu
    --memory 512mb \ # max memory it can use
    -v /tmp/.X11-unix:/tmp/.X11-unix \ # mount the X11 socket
    -e DISPLAY=unix$DISPLAY \ # pass the display
    -v $HOME/Downloads:/root/Downloads \ # optional, but nice
    -v $HOME/.config/google-chrome/:/data \ # if you want to save state
    -v /dev/snd:/dev/snd --privileged \ # so we have sound
    --name chrome \
    jess/chrome

Comment: To run on mac this link is essential https://github.com/docker/docker/issues/8710
Answer: To dockerize your protractor test cases use either of this images from Dockerhub caltha/protractor (or) webnicer/protractor-headless.
Then run this command "docker run -it {imageid} protractor.conf.js". See the instructions in those repositories


Visual Studio Code ES7/JS Intellisense

Question: I'm trying to use Visual Studio Code to edit files in a react starter kit project.  The React project uses Babel for trans-piling, and so it has only .js files instead of .ts files.  I would like VS Code to provide proper intellisense for these files...including new async/await Javascript keywords.
So far I can only get intellisense to work properly if I rename the extension of files from .js to .ts, but I don't want to convert the whole project just to suit my personal tool choices.
Is there a way to make VS Code treat .js files as if they were .ts files...simply for the sake of ES7 intellisense?  I spotted a thread of discussion about this, but I'm not sure what options are available today.  I also tried adding a tsconfig.json file that looks like this:
{
  "compilerOptions": {
    "target": "es6"  //An "es7" option is not yet legal
  },
  "filesGlob": [
    "./**/*.js",
    "!./node_modules/**/*.js"
  ]
}

I hoped this would trick Typescript into acknowledging .js files, but no luck.
Ultimately I would just like to have ES7 intellisense in VS Code. If there is an entirely different way to achieve this, that would also be welcome.  For that matter, if there is an alternative to VS Code that provides the equivalent of intellisense for ES7 Javascript, I'm interested to know about that too.
Comment: https://github.com/Microsoft/nodejstools/wiki/ES6-IntelliSense-Preview-in-NTVS-1.1
Comment: @epascarello: Cool! Is there a way to activate this for `Visual Studio Code`?  Or is it only an option for `Visual Studio`?  Also, in the context of `Visual Studio`, it looks like I need to create a `.njsproj` or `.jsproj` file before I can get started...
Answer:
Visual Studio Code

VSCode doesn't support filesGlob. Its an atom-ts only thing at the moment.
To use .js files you need enable allowJs

Solution
tsconfig.json:
{
  "compilerOptions": {
    "target": "ES6",
    "allowJs": true,
  },
  exclude: ["node_modules"]
}

Note: Target es6 gives you all the latest features (including any es7 ones) http://json.schemastore.org/tsconfig

Visual Studio Code ES7/JS Intellisense


java.lang.OutOfMemoryError when running bazel build

Question: I have been trying to install the ONOS controller on my Ubuntu VM on my MAC computer following the steps in this link: Download ONOS code & Build ONOS.
However, the building process is not successful after executing the following command:
~/onos$ bazel build onos

The above command outputs the following:
Starting local Bazel server and connecting to it...
INFO: Analysed target //:onos (759 packages loaded, 12923 targets configured).
INFO: Found 1 target...
.
.
.
enconfig-native; [2,128 / 2,367] //models/openconfig:onos-models-openconfig-native; ERROR: /home/mohamedzidan/onos/models/openconfig/BUILD:11:1: Building models/openconfig/libonos-models-openconfig-native-class.jar (2 source jars) failed (Exit 1)
[2,128 / 2,367] //models/openconfig:onos-models-openconfig-native; An exception has occurred in the compiler (10.0.1). Please file a bug against the Java compiler via the Java bug reporting page (http://bugreport.java.com) after checking the Bug Database (http://bugs.java.com) for duplicates. Include your program and the following diagnostic in your report. Thank you.
java.lang.OutOfMemoryError: Java heap space
at jdk.compiler/com.sun.tools.javac.util.ArrayUtils.ensureCapacity(ArrayUtils.java:60)
at jdk.compiler/com.sun.tools.javac.util.SharedNameTable.fromUtf(SharedNameTable.java:132)
at jdk.compiler/com.sun.tools.javac.util.Names.fromUtf(Names.java:392)
at jdk.compiler/com.sun.tools.javac.util.ByteBuffer.toName(ByteBuffer.java:159)
at jdk.compiler/com.sun.tools.javac.jvm.ClassWriter$CWSignatureGenerator.toName(ClassWriter.java:320)
at jdk.compiler/com.sun.tools.javac.jvm.ClassWriter$CWSignatureGenerator.access$300(ClassWriter.java:266)
at jdk.compiler/com.sun.tools.javac.jvm.ClassWriter.typeSig(ClassWriter.java:335)
at jdk.compiler/com.sun.tools.javac.jvm.ClassWriter.writeMethod(ClassWriter.java:1153)
at jdk.compiler/com.sun.tools.javac.jvm.ClassWriter.writeMethods(ClassWriter.java:1653)
at jdk.compiler/com.sun.tools.javac.jvm.ClassWriter.writeClassFile(ClassWriter.java:1761)
at jdk.compiler/com.sun.tools.javac.jvm.ClassWriter.writeClass(ClassWriter.java:1679)
at jdk.compiler/com.sun.tools.javac.main.JavaCompiler.genCode(JavaCompiler.java:743)
at jdk.compiler/com.sun.tools.javac.main.JavaCompiler.generate(JavaCompiler.java:1641)
at jdk.compiler/com.sun.tools.javac.main.JavaCompiler.generate(JavaCompiler.java:1609)
at jdk.compiler/com.sun.tools.javac.main.JavaCompiler.compile(JavaCompiler.java:959)
at jdk.compiler/com.sun.tools.javac.api.JavacTaskImpl.lambda$doCall$0(JavacTaskImpl.java:100)
at jdk.compiler/com.sun.tools.javac.api.JavacTaskImpl$$Lambda$97/1225568095.call(Unknown Source)
at jdk.compiler/com.sun.tools.javac.api.JavacTaskImpl.handleExceptions(JavacTaskImpl.java:142)
at jdk.compiler/com.sun.tools.javac.api.JavacTaskImpl.doCall(JavacTaskImpl.java:96)
at jdk.compiler/com.sun.tools.javac.api.JavacTaskImpl.call(JavacTaskImpl.java:90)
at com.google.devtools.build.buildjar.javac.BlazeJavacMain.compile(BlazeJavacMain.java:113)
at com.google.devtools.build.buildjar.SimpleJavaLibraryBuilder$$Lambda$70/778731861.invokeJavac(Unknown Source)
at com.google.devtools.build.buildjar.ReducedClasspathJavaLibraryBuilder.compileSources(ReducedClasspathJavaLibraryBuilder.java:57)
at com.google.devtools.build.buildjar.SimpleJavaLibraryBuilder.compileJavaLibrary(SimpleJavaLibraryBuilder.java:116)
at com.google.devtools.build.buildjar.SimpleJavaLibraryBuilder.run(SimpleJavaLibraryBuilder.java:123)
at com.google.devtools.build.buildjar.BazelJavaBuilder.processRequest(BazelJavaBuilder.java:105)
at com.google.devtools.build.buildjar.BazelJavaBuilder.runPersistentWorker(BazelJavaBuilder.java:67)
at com.google.devtools.build.buildjar.BazelJavaBuilder.main(BazelJavaBuilder.java:45)
[2,128 / 2,367] //models/openconfig:onos-models-openconfig-native; Target //:onos failed to build
Use --verbose_failures to see the command lines of failed build steps.
INFO: Elapsed time: 1386.685s, Critical Path: 117.31s
INFO: 379 processes: 125 linux-sandbox, 254 worker.
**FAILED: Build did NOT complete successfully**

Comment: Please provide the entire output of the Bazel command.
Comment: https://drive.google.com/open?id=1MhU5fliF5CUwsh8HpczKBtkuQClOPyjO

just uploaded a screenshot of the output on my Google drive
Comment: any thoughts on why it is not successful, Jin
Comment: Please paste the entire output in your question.
Comment: just added the output in the question, Jin
Comment: Related: [Decrease bazel memory usage](https://stackoverflow.com/q/34382360/4561887)
Answer: Your output shows java.lang.OutOfMemoryError: Java heap space. You can increase the amount of memory available to javac with something like this:
BAZEL_JAVAC_OPTS="-J-Xms384m -J-Xmx512m"

If that still doesn't work, try progressively increasing sizes for -Xmx. This issue is discussed further at:
https://github.com/bazelbuild/bazel/issues/1308
Comment: Export it as an environment variable: `export BAZEL_JAVAC_OPTS="-J-Xms384m -J-Xmx512m"`. Then run Bazel again.
Comment: where should I insert the above line you?  Singh
Answer: Summary
If bazel runs out of memory while building, and you see this error:

java.lang.OutOfMemoryError: Java heap space

...then do this:

Increase your RAM or your virtual memory swap file size, to emulate having more RAM (details on how to do this are below).
From now on, build with this bazel command, for example, to give Bazel more heap space (RAM) while building. In this case I am giving it 32GB maximum RAM:
# Do this to give Bazel up to 32GB of RAM wile building
time bazel --host_jvm_args=-Xmx32g build //...

# ...instead of doing this
time bazel build //...

Details
If Bazel fails with any versions of the following error, it's because it ran out of heap space while trying to build.
Example error:

java.lang.OutOfMemoryError: Java heap space

I see that error in your output you pasted. Although very much not well-known, some monster-sized projects and mono-repos can require a heap of 16GB or more, so I recommend you just create a massive 32GB~64GB swap file (virtual memory) on your Linux build machine and let it run with it! Give it the whole thing to build!
CAUTION: if you have a standard HDD (spinning Hard Disk Drive), this may cause the build to run dozens or even hundreds of times slower than using physical RAM to build! This is because HDDs are HORRIBLY HORRIBLY HORRIBLY SLOW!
BUUUUT: If you have a 2.5" or 3.5" SSD (Solid State Drive), then it works ok, or 100x BETTER STILL IF YOU HAVE AN m.2 form-factor SSD! This is because an m.2 form-factor SSD is INCREDIBLY FAST, so you can get away with HUGE swap files being used in place of RAM all the time because these disks operate so fast!
If using a top-of-the-line internal m.2 form-factor SSD, I expect the following build with virtual memory to be only ~2x slower than using physical RAM only (of the same size) to build. If you have a super slow spinning HDD, however, the same build which takes 2 hrs using a swap file on the internal m.2 SSD might take up to multiple days or more using a swap file on a spinning HDD.
Your results may vary, of course, but favor a smaller JVM bazel heap (to use less of your virtual memory), the slower you expect your virtual memory (swap file) to be.

Increase your system's swap file (virtual memory) to at least 32~64 GB. To add or remove a swapfile, follow the detailed instructions here: https://linuxize.com/post/how-to-add-swap-space-on-ubuntu-18-04/. UPDATE: use my own instructions here instead: How do I increase the size of swapfile without removing it in the terminal?. My instructions avoid the pitfalls of fallocate by using dd instead, as I explain in my answer there.
In short, here is how to add a swapfile:
sudo dd if=/dev/zero of=/swapfile count=64 bs=1G # Create a 64 GiB file
sudo mkswap /swapfile           # turn this new file into swap space
sudo chmod 0600 /swapfile       # only let root read from/write to it,
                                # for security
sudo swapon /swapfile           # enable it
swapon --show                   # verify this new 64GB swap file is
                                # now active
sudo gedit /etc/fstab           # edit the /etc/fstab file to make these
                                # changes persistent (load them each boot)
# ADD this line to bottom (w/out the # comment symbol):
# /swapfile none swap sw 0 0
cat /proc/sys/vm/swappiness     # not required: verify your systems
    # "swappiness" value. Note: values now range 0 to 200 (they used to only
    #  go up to 100), and have a default value of 60. I highly recommend
    #  you follow my instructions here to set your swappiness to 0,
    #  however, to improve your system's performance:
    #  https://askubuntu.com/a/1445347/327339

To resize or delete your swapfile: if you ever need to resize your swap file you just made above, you can delete it like this:
sudo swapoff -v /swapfile # turn swap file off
sudo swapon --show  # verify the swap file is off
free -h             # you can also look at this as an
                    # indication the swap file is off
sudo rm /swapfile   # remove the swap file

Then, you can either follow the instructions above again to recreate it at a new size, or if you are permanently deleting it you'll need to edit your /etc/fstab file to remove the /swapfile none swap sw 0 0 line you previously added to the bottom of it.

Add --host_jvm_args=-Xmx32g to any bazel command, right after the word bazel. This sets the max Java Virtual Memory, or bazel build heap in this case, to 32GB, which goes into your swap file once your physical RAM is full. If you have a high-speed SSD drive, which will operate surprisingly well with swap, expect to wait a few hrs max for your build to complete, depending on the repo size. If you have an old spinning HDD, expect a repo that takes 2 hrs to buld with a swap file on an internal m.2 SSD to take maybe up to several days perhaps to build with a swap file on a slow spinning HDD--especially if it's an external instead of internal HDD.
Here is a sample full bazel command with this bazel startup option added, to build an entire repo:
time bazel --host_jvm_args=-Xmx32g build //...

...instead of this:
time bazel build //...

The time addition there just prints out a more readable printout of how long the build took is all (I like it). Just be sure to set your max Java Virtual Memory allotted to bazel for any bazel build command by putting --host_jvm_args=-Xmx32g (or similar) after the word bazel any time you need it.
Note that setting the max heap like we are doing here with -Xmx is NOT the same thing as setting the default heap like others might do with -Xms. Setting the max heap still starts with the default heap but lets it grow if needed. The other answer shows setting both via an environment variable.

Done!
References:

*****[my own answer] Ask Ubuntu: How do I increase the size of swapfile without removing it in the terminal?
https://linuxize.com/post/how-to-add-swap-space-on-ubuntu-18-04/
https://serverfault.com/questions/684771/best-way-to-disable-swap-in-linux/684792#684792
My answer: How do I configure swappiness?

See also:

https://github.com/bazelbuild/bazel/issues/1308


How do i calculate time like numbers

Question: Hello people i am doing an app on C# and now i am with a doubt.
I need to represent relative time, for example i have 02:30:00 i will need to say that is 2,5 hours.
How can i do that, and i need that have to  be with 2 decimals here is what i have done so far, but i gives me errors with timespan
private string Horas_Matutinas(string cedula, DateTime desde, DateTime hasta)
    {
        string respuesta = "";
        DateTime resto = Convert.ToDateTime("00:00:00");
        //Llamo la conexion SQL
        SqlConnection Wdcon_usuario = new SqlConnection(WDcon);
        SqlCommand usuario = new SqlCommand();
        SqlDataReader usuarioDR = null;
        TimeSpan tiempo = Convert.ToDateTime("00:00:00") - Convert.ToDateTime("00:00:00");
        //Instancio la conexion SQL
        usuario.Connection = Wdcon_usuario;

        //Registro el Query SQL
        usuario.CommandText = "SELECT * FROM matutino WHERE " +
        "(cedula = @ID) AND " +
        "(desde >= @DESDE) AND " +
        "(hasta <= @HASTA)";
        usuario.Parameters.AddWithValue("@ID", Convert.ToInt64(cedula));
        usuario.Parameters.AddWithValue("@DESDE", Convert.ToDateTime(desde));
        usuario.Parameters.AddWithValue("@HASTA", Convert.ToDateTime(hasta));

        //Abro la conexion
        Wdcon_usuario.Open();

        //Ejecuto la consulta
        usuarioDR = usuario.ExecuteReader();

        //Empiezo el ciclo
        while (usuarioDR.Read())
        {
            TimeSpan tiempX = (DateTime)usuarioDR["tiempotrbajado"] - resto;
            tiempo = tiempo + tiempX;
            Double tiemp = Convert.ToDouble(tiempo);
            respuesta = tiempo.ToString("0.00");

        }
        //Cierro la conexion
        Wdcon_usuario.Close();
        //Termino la sentencia SQL

        //int i = 0;
        int total = 8;
        int caracteres = respuesta.Length;
        int restantes = total - caracteres;

        //respuesta.PadLeft(restantes, "0");

        string s = new String('0', restantes) + respuesta;
        return s;
    }

Comment: What exception are you getting?
Answer: Try replacing this Line
Double tiemp = Convert.ToDouble(tiempo);

With this
Double tiemp = tiempo.TotalHours;

Timespan.TotalHours will return the timespan as whole and fractional hours which is what you appear to want
Comment: I used this, but now i get another error on line with "respuesta = tiempo.ToString("0.00");" this is the error "Input string was not in a correct format."
Comment: You'll need to check out these two pages on the different formating options avaible with the ToString Method (http://msdn.microsoft.com/en-us/library/dwhawy9k(VS.96).aspx) and (http://msdn.microsoft.com/en-us/library/0c899ak8(VS.96).aspx) Also try just ToString() (with no arguments) or ToString("F") (only two decimal places)
Comment: Also you are storing the total hours in the variable tiemp but you are trying to pull the string from tiempo. Try changing the line (respuesta = tiempo.ToString("0.00");) to (respuesta = tiemp.ToString("F");)
Answer: It looks like you need the difference between two times here, this example might help you out.
DateTime now = DateTime.Now;
DateTime later = DateTime.Now.AddHours(2.5);
double diff = (later - now).TotalHours;
var x = String.Format("{0:0.00}", diff);

Also, you can create resto and tiempo without using Convert.  Instead, you can use:
DateTime resto = DateTime.Now.Date;
TimeSpan tiempo = new TimeSpan();

Answer: The TimeSpan.TotalHours property looks like what you want. It returns the total time value of the TimeSpan expressed as whole and fractional hours. You can then round that value (it'll be a double) to however many decimal places you may need with Math.Round(), and format it for display using the overload of ToString() that takes a CultureInfo, or a specified format string.
Answer: You probably need to get the TimeSpan like this:
TimeSpan tiempX = (TimeSpan)((DateTime)usuarioDR["tiempotrbajado"] - resto);
Then format the result using one of the Standard TimeSpan Format Strings:
http://msdn.microsoft.com/en-us/library/ee372286.aspx
Answer: You could do it in SQL Server (I assume you are using SQL Server)... this is a ugly example but you could append the results or just convert them:

SELECT    SUBSTRING(CAST(CONVERT(TIME, GETDATE()) AS char(20)), 0, 3)
  AS horas,      CAST(SUBSTRING(CAST(CONVERT(TIME, GETDATE()) AS
  char(20)), 4, 2) AS float) / 60 * 100 AS minutos

Lots of functions, but thats the idea. Get the date (I use getDate(), you could use your column)... convert it to time (in my case 'cause I don't want the date for the example). Cast it to char so we can substring it to get hours or minutes, and in minutes y cast as float to divide and get the relation (30 = .5).
Just an idea.

How do i calculate time like numbers


Average time for a random walk on the edges of a cube

Question: In a interview i had something similar to this question Random walk on the edges of a cube.
But this time there is only a ant, it takes one minute to go through a single edge. The ant can use the same edge several times in a row.
The question was : on average, how long it would take for the ant to come back to the initial corner ?
Comment: All that matters is the first step, which takes one minute.  At that point the ant is on a different vertex and solving this problem thereby comes down to the expected time to reach the starting vertex from that one--and the answer is given in the referenced thread.
Comment: The referenced question already did the work: it tells you, from any position on the cube, the expected time to return to the original corner.  The ant takes one minute to advance to one of those positions, so *read off the answer and add one to it.*
Comment: "the ant takes one minute to advance to one of those positions" : is it an average time ? For example if the ant goes to the opposite corner it would take 3 minutes on top of the 10 found in the reference question
Answer: Here's a simple approach:
Imagine the ant performing its random walk on the cube for a long time (ignoring for a moment that you are interested in the time until the return to the origin point).
By symmetry the expected proportion of time the ant will be at each corner is $1/8.$ So on average the time between visits to the origin must therefore be 8 steps.
Since it's one minute per step, the expected time until the return to the origin is 8 minutes.
Comment: It's similar to a coin flip. If you flip a fair coin repeatedly, the long-term proportion of heads is 50 percent. So the expected time until I flip a head is 2 flips. For the cube problem, you could approach it more formally and set it up as a Markov chain and construct the transition matrix over the corners. You will find that the transition matrix is doubly stochastic, which implies the chain is at each corner an equal proportion of time.
Comment: Could you explain this please : "By symmetry the expected proportion of time the ant will be at each corner is  1/8" ? Is it just the fact that the ant walks at a constant speed and at some point it will visit the 8 corners ?


Ant design - is there a way to get styles that im actually using?

Question: installed recently ant design https://ant.design/
However, it doesn't use styled components, just old basic css modules. The .css file is like 10k of lines. There's a way to use only these u need, but first u have to install babel.
Unfortunately, Im not using babel in my project, just the typescript.
https://ant.design/docs/react/introduce - here is written that I need babel and babel-import-plugin. But as I said Im not using it and I dont want to use it in my project.
For those who dont want to enter external websites:
<code>Use modularized antd#
Use babel-plugin-import (Recommended)

// .babelrc or babel-loader option
{
  "plugins": [
    ["import", { "libraryName": "antd", "libraryDirectory": "es", "style": "css" }] // `style: true` for less
  ]
}
</code>
Question: Is there a way to use modularized css (import only these styles that u need) using typescript or just webpack or so? Without babel?
Thank you
Answer: I have been using Antd with react from past 1 year.
This is the problem when you will try to use the modularized antd otherwise this issue would not exist.
In modularized
import DatePicker from 'antd/lib/date-picker';  // for js
import 'antd/lib/date-picker/style/css';        // for cs
In non modularized
import 'antd/dist/antd.css'; //once in index.js file in src folder the
import {DataPicker,Button,Grid} from 'antd'; //whatever component you needed
Do you really wanted to user the modularized antd?
If you changed your mood here is my git repository for that https://github.com/shreyansRS/react-redux-antd
If you still wanted to use modularized, i think importing 'antd/lib/date-picker/style/css' in index.js should work.


How to send multiple images in formdata format in Angular 4

Question: I want to send multiple images in formdata format, so  far I  was sending single image in base65 format but here I have to send max 5 images as well in formdata format.
I am trying to solve this issue but I could not achieve  it .
My codes look like below .ts
    handleFiles= function (fileInput: Event) {

         if (fileInput.target['files'].length>1) {

            var files = Array.from(fileInput.target['files']);
    this.authService.sendMultipalImages(files).subscribe(data=>{
        console.log(data);

    })

            }else{
                var files = Array.from(fileInput.target['files']);

                this.convertImageToBase64(files, []);
            }

                }

            convertImageToBase64(list, resultArray) {

              if(list.length){
                let reader = new FileReader();
                reader.readAsBinaryString(list[0]);
                reader.onload = (evt: any) => {

                  const str = btoa(evt.target.result)
                  resultArray.push('data:image/jpeg;base64,' + str);
                  list.splice(0, 1);
                  console.log(list.length)
                  return this.convertImageToBase64(list, resultArray);
                };
              } else {

                console.log(resultArray.length);

                    this.attached_image = resultArray[0];

                }

this is my service .ts file
sendMultipalImages = function(mImage){

      let formData: FormData = new FormData();

       formData.append('image', mImage);

        return this.http.post(this.api_url + 'uploadmultiple', formData, this.getUploadMulitpleImages()).map(res => res.json())
      }

header looks like this

getUploadMulitpleImages() {

            let headers = new Headers();
            headers.append('Content-Type', 'multipart/form-data');
           headers.append('Accept', 'application/json');
           headers.set('Authorization', 'Bearer ' + this.webToken);
          let option = new RequestOptions({ headers: headers });
       return option;
         }

Please how can I send multiple images to server.
Your help would be highly appreciated.
Thanks in advance
Comment: People will let you know that your code is formatted horribly :) And I think you mean base64??
Comment: What error do you receive when using your current method?
Comment: Sorry for that but  I do not want send in base64 format because it will increase size, so I want to send in like formdata (chunk)
Comment: I am able to send single image but for the multiple images whatever part of code I have written is correct or not , I am not sure .
Answer: I found the Ans.
Just I removed these below thing from my header, did not make any changes in component file,
 headers.append('Content-Type', 'multipart/form-data');
  headers.set('Authorization', 'Bearer ' + this.webToken);// this is optional

Service.ts
sendMultipalImages = function(mImage){
       debugger;
       var formData: FormData = new FormData();
       for (const file of mImage) {
        formData.append(file.name, file)

      }
    return this.http.post(this.api_url + 'uploadmultiple', formData, this.getUploadMulitpleImages()).map(res => res.json())
      }


ASP Core scaffolding error - package restore failed on a clean new project

Question: I tried doing Identity scaffolding on my existing ASP Core app and I get this error:
There was an error running the selected code generator:
'Package restore failed. Rolling back package changes for 'WebApplication1'.'

take note that this is a clean new project, nothing was modified, I am using VS2022 and .NET 6, the project template I used had the Authentication Type set to "Individual Accounts"

is there any way around this to fix this bug?
Answer: I got this issue resolved by:
Going to Tools->NuGet Package Manager->Manage NuGet Packages for Solution...
I had updates for EntityFrameworkCore that needed installing.
Also had updates for RazorRunTimeCompilation.
Each are now on the current 6.0.10 version.
Answer: I decided to use dotnet rider's scaffolding feature instead, it works with no problems


php mysqli escape string error in sql syntax

Question: I am trying to escape fields posted from a form.  I can successfully insert into the SQL database by commenting out the code that escapes the string.
The error received is:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '\"test\",\"0123456789\",\"email@example.com\",\"1\",\"1\",\"fgsdfdfndfndfndfndfndfn\' at line 1

Here is the code I am using:
$Name= $_POST['fullname'];
$Phone = $_POST['phone'];
$email = $_POST['email'];
$inBuilding = $_POST['inbuilding'];
$floor = $_POST['floor'];
$inRoom = $_POST['inroom'];
$majorDescription = $_POST['majorcategory'];
$description = $_POST['desc'];

$query = "INSERT INTO `problem`.`reports` (`Name`, `PhoneNumber`, `EmailAddress`, `inBuilding`, `inRoom`, `Description`, `MajorDescription`) VALUES (";
$query .= '"' . $Name. '","' . $Phone . '","' . $email . '","' . $inBuilding . '","' . $inRoom . '","' . $description . '","' . $majorDescription . '");';

$query = mysqli_real_escape_string($connect, $query);

I have also tried:
$query = mysqli_escape_string($connect, $query);

with the same error.
According to other examples on stack overflow I changed the INSERT INTO code to the following:
$query = "INSERT INTO `problem`.`reports` (Name, PhoneNumber, EmailAddress, inBuilding, inRoom, Description, MajorDescription) VALUES ('$Name', '$Phone', '$email', '$inBuilding', '$inRoom', '$description', '$majorDescription')");

This code gave server 500 error.
MySQL is fully updated.
Any assistance appreciated!
MikeW's solution worked.  Also realized I was trying to escape the string before I had opened the database making mysqli_real_escape_string return null.  Connecting to the database first, ($connect= new connect("server","user","password");) solved this problem.  Hopefully this will help anyone else with the same problems.
Comment: You really should be using mysqli_escape_string() on the variable itself, not on the entire query string. Additionally, SQL likes if you use a single quote `'` to wrap values, not a double quote `"`.
Comment: You have a syntax error at the end of your 'revised' `$query`: there's a close parenthesis that does not belong.
Comment: gotcha, you mean on each variable?  I did try that too with the same error.
Comment: Right, yes on each variable. But, I think the problem may be the use of the double quote marks.
Comment: I tried with my revised $query without the extra close parenthesis (thanks to josh) and received the same error above.  No more 500 error though
Comment: Just a  thought: what version of PHP are you using? Is it possible you have magic quotes turned on?
Comment: I currently have 5.3.21
Answer: I'm not sure if MySQL works with double-quotes. You should use single-quotes. But the more glaring issue is that you need to call mysqli_real_escape_string() on every variable, not the entire query string.
To simplify the problem, say your query was as follows:
$query = "INSERT INTO tbl (Name) VALUES ('". $_POST['name'] ."')";
$query = mysqli_real_escape_string($connect, $query);

And then say I pass in a value, Michael O'Connor. What does your query become?
INSERT INTO tbl (Name) VALUES (\'Michael O\'Connor\')

Notice that not only did the ' in the actual name get escaped, but the quotes to surround that name also got escaped. If you called mysqli_real_escape_string() on the entire compiled query string, it has no way to distinguish a ' in the value vs. the ones that are supposed to surround the value.
Comment: @user2210274: No, I didn't mean to point the finger at any particular person. But more or less to the anonymous downvoter. Downvotes with no explanation kinda irritate me, especially when my answer is accurate.
Comment: I do agree.  I was downvoted as well, I think my post is relevant if not novice.
Comment: upvoted as you helped explain how string escaping works
Answer: You should be using single quotes, not double quotes. Also, mysqli_real_escape_string() should be called on each variable, not on the query as a whole. You should get something like this:
$Name= mysqli_real_escape_string($connect, $_POST['fullname']);
// more variables, similarly escaped.

$query = "INSERT INTO `problem`.`reports` (`Name`, `PhoneNumber`, `EmailAddress`, `inBuilding`, `inRoom`, `Description`, `MajorDescription`) VALUES (";
$query .= "'$Name','$Phone','$email','$inBuilding','$inRoom','$description','$majorDescription')";

However, for this sort of query you should consider using prepared statements.
Comment: @travesty3 In answer to your now deleted comment: it looks like the 'practically identical' answer has been extensively edited since I posted this. Your answer was two lines of text last time I looked.
Comment: Receiving a 500 error with the code you gave. Not sure why as I double checked and its virtually identical.
Comment: @user2210274 Then the problem may be somewhere else in your code. There should be a message in your server error log.
Comment: The error is because the closing paren at the end of the last line of code is unmatched. I deleted my comment because I didn't want to sound whiny on here, but it does bug me when people post an answer that has already been posted. Seems like a cheap way to steal rep. Yes, I edited my answer, but the original answer was the first three lines in my current answer, which is the only part of my answer that I was referring to as being nearly identical to yours. Yes, you added a (IMHO unvaluable) code sample and a suggestion to use prepared statements, but if it were me, I would've just commented.
Comment: @Travesty3 Thanks for the heads up on the syntax error - now fixed.


Volleyball - Is this reaching over the net?

Question: This is a follow-up question to the "In volleyball when is it considered reading over the net" question posted a few years ago.
Subject of this question, is the accompanying play starting at time index 54:07.
(Ok, so the Team Blue player failed the attack)
Am I wrong here? or did the Team Red & White blockers just barely jump the gun and reach over the net just before the third contact?
The bump(set) was not necessarily in the direction of the opponents court, but seemed parallel to the net.
(The Referees never made any calls to this effect, nor did they throughout the rest of the match despite some other possibly questionable blocking plays.
I assume by the referees not calling anything that everything was legal)
If it was not legal play, can someone explain to me from the rules where the referees or players may have made the mistake?
(I'm just curious because I've run into similar situations in my rec. league.)
Would someone with more experience/better perspective be able to shed some light on this?
Comment: Which ruleset are you interested in when looking for an answer, because the match in question clearly wasn't being played under FIVB rules?
Answer: If we would consider the play under standard (FIVB) rules, there is no issue here at all; the blocking players did not even touch the ball. The "reaching over the net" rule refers only to playing the ball beyond the net, not just literally "reaching over the net", without touching the ball nor interfering with opponent play.
You can reach beyond (or under) the net any time you want, unless you touch the ball there or interfere with the play in another way (e.g. by preventing the opponent from playing the ball).


'No converter registered for type Deedle.Frame' using F# R type provider and ggplot2

Question: I'm working on my first attempt to use R's GGPlot2 via the F# R type provider.
Here's my code:
let (++) (plot1:RDotNet.SymbolicExpression) (plot2:RDotNet.SymbolicExpression) =
    R.``+``(plot1, plot2)

let ChartGgPlot2 (prices : Prices) =
    try
        let fileName = makeFile ".png"
        let priceSeries = prices.Prices |> Seq.map (fun p -> p.Date, p.Close) |> series
        let dataFrame = Deedle.Frame.ofRecords priceSeries

        R.png(filename=fileName, height=200, width=300, bg="white") |> ignore
        R.ggplot(
            namedParams[
                "data", box dataFrame;
                "mapping", box (
                    R.aes__string(x="Date", y="Close"))])
        ++ R.geom__point() |> ignore
        R.dev_off() |> ignore
        fileName |> Choice.succeed
    with
    | e -> Choice.fail e.Message

p.Date is a System.DateTime and p.Close is a double.
At runtime I get this exception at the point of calling R.ggplot:

No converter registered for type Deedle.Frame`2[[System.DateTime,
  mscorlib, Version=184.108.40.206, Culture=neutral,
  PublicKeyToken=b77a5c561934e089],[System.String, mscorlib,
  Version=126.96.36.199, Culture=neutral, PublicKeyToken=b77a5c561934e089]] or
  any of its base types

I've tried the solution suggested suggested here (copying two DLLs): Deedle frame to R but that didn't make a difference.
I should also say that my usage of series and Frame.ofRecords is pretty much guesswork at this point.
Many thanks.
Edit:

It's a compiled .NET 4.6 project with RProvider (1.1.20) and Deedle.RPlugin (1.2.5) added via Nuget.
ggplot2 works correctly from RGui.
Comment: How are you referencing R provider & Deedle? Is this in a script file?
Comment: It's in a compiled project with the R provider and Deedle nuget-ed in.  Using plain old R.plot works fine.
Comment: thanks. can you also show what you are opening?
Comment: Convertors for Deedle are implemented in `Deedle.RPlugin` and R provider needs to discover the DLL. It uses "ProbingLocations" from app.config (https://github.com/BlueMountainCapital/FSharpRProvider/blob/master/src/RProvider/app.config) which has a default value pointing to "other nuget packages", which works in the scripting scenario, but I'm not sure about "compiled" scenario. Can you try modifying probing locations in `RProvider.Server.exe` config to point to the current directory? (Or directory with the Deedle.RPlugin files?)
Answer: Tomas's comment about config files and probing locations wasn't the answer - but it clued me in to what actually was the answer.
I needed to use Nuget to add references to Deedle.RPlugin, not only to the assembly that was doing the R calls to render a chart, but also to my 'main' assembly that references the charting assembly.
I don't know if this is an inherent limitation in the way the build system interacts with the type provider.  But for now I'm very happy to have a workaround.
(For teaching purposes it would be great to know if there could be a long term fix.)
Huge thanks to those that replied.
Answer: It's quite possible something is off with your FSLab and/or Rprovider install. This for example should work:
#load @"..\..\FSLAB\packages\FsLab\FsLab.fsx"
open System
open Deedle
open FSharp.Charting
open System
open RDotNet
open RProvider
open RProvider.graphics
open RProvider.stats
open RProvider.datasets
open RProvider.ggplot2

type DtPx = {
    Dt:System.DateTime
    Px:float
}

let rnd = System.Random()
let nextPx() = rnd.NextDouble() - 0.5
let nextDay i = DateTime.Today.AddDays(float i)

let data = List.init 100 (fun i -> {Dt=nextDay i;Px = nextPx()})
let df = Frame.ofRecords data

let mtc = R.mtcars.GetValue<Frame<string, string>>()
let (++) (plot1:RDotNet.SymbolicExpression) (plot2:RDotNet.SymbolicExpression) =
    R.``+``(plot1, plot2)

R.ggplot(
    namedParams[
        "data", box mtc;
        "mapping", box (
            R.aes__string(x="disp", y="drat"))])
++ R.geom__point()

R.ggplot(
            namedParams[
                "data", box df;
                "mapping", box (
                    R.aes__string(x="Dt", y="Px"))])
++ R.geom__point()

You can use this in an fsx file, but also in a compiled .exe to save the output to png. In that case you will have to reference DynamicInterop, RDotNet, Rprovider, etc as well.

References:

This is for an empty project nugetting Deedle and RProvider related packages.
Comment: Yes, as it happens I literally just tried that. I had to add a ggsave as R.png was writing a blank image.  But certainly didn't get the error.

Checking through the references now, thanks!
Comment: Thanks.  I'll try adding that code to the existing context to see if that works.
Comment: Same problem with the above code when merged into mine - i.e. "No converter registered..."
Comment: In that case I suspect maybe it's some sort of installation issue. Just in case I will show the actual references in a screenshot. Can you run this is fsx at least?
Comment: Hmm, interesting.  I am missing RProvider.Runtime.dll and RProvider.DesignTime.dll.  I've got a funny feeling I've had to add the equivalents manually, in other type provider based projects.  Trying that.
Comment: Correction - it was onlyl RProvider.DesignTime.dll reference that was missing.  Added that and checked that RunTime and DesignTime both had copy local set to true.  Same problem.
Comment: it's going to be difficult to troubleshoot. Maybe try starting a totally new solution. I tried it in a blank solution, nugetting RDotnet, Rprovider, Deedle, Deedle Rplugin, etc. and on my end it works. I will update the screenshot with a cleaner one.
Comment: Clean solution seems like the way to go.  This one has a chequered history.  I'll update here when tried.  Thanks!


How to keep my text justified with same space between under flex box

Question: I am trying to achieve the words to be shared with same whitespace around. But not getting the solution. any one help me? in my try you can find the unordered space between word(s).

.parent{
  display: flex;
  flex-direction: row;
  justify-content: space-around;
  width:80%;
  border:1px solid red;
}

.parent span{
  background: lightblue;
}

 one text
 small
 lengthy texter than one
 medium text two
 one

Answer: Please update your code like this:

.parent{
  display: flex;
  flex-direction: row;
  justify-content: space-evenly; /* important */
  width:80%;
  border:1px solid red;
}

.parent span{
  background: lightblue;
}

 one text
 small
 lengthy texter than one
 medium text two
 one

Comment: `space-evenly` currently works in Firefox and Chrome, but not Edge. (I didn't test in Safari.)


Peculiar android RuntimeException

Question: I just received the wierdest looking stack trace on my Developer Console. What puzzles me is where "MArcos" came from? This was the app: https://play.google.com/store/apps/details?id=genius.mohammad.accelerometer.mouse
Try recreating the exception if you want and explain to me what it is if you can. Thanks!
java.lang.RuntimeException: Unable to start activity ComponentInfo{genius.mohammad.accelerometer.mouse/genius.mohammad.accelerometermouse.MainActivity}: java.lang.NumberFormatException: unable to parse 'MArcos' as integer
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1651)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1667)
at android.app.ActivityThread.access$1500(ActivityThread.java:117)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:935)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:130)
at android.app.ActivityThread.main(ActivityThread.java:3687)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:507)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:867)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:625)
at dalvik.system.NativeStart.main(Native Method)
Caused by: java.lang.NumberFormatException: unable to parse 'MArcos' as integer
at java.lang.Integer.parse(Integer.java:383)
at java.lang.Integer.parseInt(Integer.java:372)
at java.lang.Integer.parseInt(Integer.java:332)
at genius.mohammad.accelerometermouse.MainActivity.updatePrefs(MainActivity.java:85)
at genius.mohammad.accelerometermouse.MainActivity.onCreate(MainActivity.java:51)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1615)

... 11 more
Comment: Are you using pro guard? If so that might explain why you aren't familiar with the variable `MArcos`
Answer: Caused by: java.lang.NumberFormatException: unable to parse 'MArcos' as integer

It seems in your code (MainActivity.java: line number 85) you are trying to parse String as Integer.
Comment: Oh wow i didnt even read to that point before posting this. Thanks ill take a look!

Peculiar android RuntimeException


JavaScript in iOS that responses to programmatic calls

Question: I'm using Processing with the HYPE framework to create some visualizations and want to put it in my iOS app. I've searched around a bit and it looks like the easiest solution would be to export Processing to JS and put that in a UIWebView.
The part I'm unsure about is that I need to be able to send input to the JS to adjust the visualization on a steady timer. My first thought is that I can set up key listeners in the JS, and then programmatically simulate a key press within the app. Is that possible? Are there other solutions?
Answer: Not a javascript expert but I know you can run JS in UIWebView. eg:
// Get
NSString *innerHTML = [self.myWebView stringByEvaluatingJavaScriptFromString:@"document.documentElement.innerHTML"];

// Set
[self.myWebView stringByEvaluatingJavaScriptFromString:@"document.documentElement.innerHTML"];

I hope this guides you in the right direction.
Source


Mapping csv columns to model?

Question: I'm creating a database of students and have the following code to read a csv file with headers and store each of the non-header lines as a student object.
class Student < ApplicationRecord
     def self.import(file)
          CSV.foreach(file.path, headers: true) do |row|
                Student.create! row.to_hash
          end
     end
end

My issue is that the csv files I need to import can be of different formats.  Some might have headers organized like:
Undegraduate Major | First Name | Last Name |  Class Year |  Undergraduate Minor
First_name  |  Last_name  | Major  | Minor
First_name | Last_name | Class_year
As you can see, not all of the fields might be present, and they definitely might not be in the same order.  How can I deal with this?
Comment: if the columns match the Student class attributes, why do you need all the columns and why do you need the columns in order?
Comment: The attribute of the student might have the name "major" but the column's name is "Undergraduate major", so it can't recognize the field "Undergraduate major" because it only knows the field "major"
Comment: you are right, sorry
Answer: You can do something like this to map the columns with attributes:
MAP = {
  "Undegraduate Major" => :major,
  "First Name" => :first_name,
  "Last Name" => :last_name,
  "Class Year" => :class_year,
  "Undergraduate Minor" => :minor,
  "Major" => :major,
  "Minor" => :minor,
  "Class_year" => :class_year
}

CSV.foreach(file.path, headers: true) do |row|
  data = {}

  row.to_hash.each do |k, v|
    key = MAP[k]
    data[key] = v
  end

  Student.create! data
end

Comment: Isn't this very slow, if you need to do 100K records ??
Comment: Hi! Thanks, I think this solution should work, but I'm running into the following error: "Unknown attribute " for Student".  It seems like it's reading " as an attribute, but the csv file has not " as an attribute.  Any idea what could be going on?
Comment: I think you are mapping a column to an attribute that does not exist in Student
Comment: Yeah, I just realized that, thanks!  Can you explain to me how this would behave if there was an attribute that exists in some csv files but not others.  Let's say some csv file include the attribute "minor" and some csv files have this column while others don't.  For the files that do not have this column, will the "minor" attribute just be set to null?
Comment: Yes, the attributes you don't have in te csv will be set to nil (or its default value). The order is not important. You only need to have a MAP const with all the possibilities.
Comment: If my answer solved your problem, please check it as the correct answer.

Mapping csv columns to model?


Number sequence as geometric sequence

Question: In a number sequence, I've figured the $n^{th}$ element can be written as $10^{2-n}$.
I'm now trying to come up with a formula that describes the sum of this sequence for a given $n$. I've been looking at the geometric sequence, but I'm not sure how connect it.
Comment: You could write this as $100\times \left(\frac  1{10}\right)^n$ if that helps
Answer: Hint: We have $10^{2-n}=10^2\cdot 10^{-n}=10^2\cdot(10^{-1})^n$ and $$\sum_{k=0}^n x^k=\frac{1-x^{n+1}}{1-x}.$$
Answer: If it is $10^{2-n}$ then, the initial term is $10$ and common ratio is $\frac 1{10}$, Now, can you get it?

Number sequence as geometric sequence


Using colors with MDX calculated measure

Question: I'm using this query in MDX for a calculated measure
topcount(nonempty([StatusPlanes].[Status].Status.members,[Measures].[Planes]),1)(0).member_caption

This will bring me this result
Dimension1     Measure
Center 1     'Status 1' ---> i want this text blue
Center 2     'Status 2' ---> i want this text in red
Center 3     'Status 3'
Center 4     'Status 2'

The thing I want to do is to add some color depending on the status... is this possible in mdx?
Thank you in advance
Adriana
Comment: PLEASE DO NOT USE ALL-CAPITALS.  IT'S LIKE SHOUTING.  Please edit your question to use mixed case, like you're speaking normally.
Answer: Can't you do this in your client? Are you trying to display this in SSRS, or in an application or something else?


How to disable htmlspecialchars in custom module form table?

Question: I'm making a table form
$form['table'] = [
  '#type' => 'tableselect',
  '#header' => $header,
  '#options' => $this->getOutput(),
  '#empty' => t('No vehicles found'),
];

In getOutput() I have 'vehicleName' =>  "vehicleId . "\">"  . $vehicle->vehicleName . "", for one of the fields. And it doesn't print out as normal html. It goes through htmlspecialchars() and I don't have clickable link at the end. How can I disable this?
Answer: You can use FormattableMarkup
Here's a simple example to get you started
use Drupal\Component\Render\FormattableMarkup; // place this at top of file

$options = [
  1 => ['foo' => 'Foo'],
  2 => ['foo' => 'Bar'],
  3 => ['foo' => new FormattableMarkup('I am a link', [])],
];

$header = [
  'foo' => t('Foo bar')
];

$form['table'] = [
  '#type' => 'tableselect',
  '#title' => t('Foo bar table'),
  '#header' => $header,
  '#options' => $options,
  '#empty' => t('No foos found.'),
];

So in your case $this->getOutput() may return something like (this is untested):
['vehicleName' =>  new FormattableMarkup(
  '@name',
  ['@id' => $vehicle->vehicleId, '@name' => $vehicle->vehicleName]
)]


Stage.addchild to bring object to front

Question: I have a sorting game with 10 elements to drag and drop in the correct order.
When i begin to drag an object i want it to appear in front of all the other objects. Since createjs does not have a zindex property I was told to readd the item to the stage with stage.adchild(sequenceNumbers);
How do I properly add this to the mousedown or pressmove function?
for (var a = 0; a < gameData.Terms.length; a++) {
  rect = new createjs.Shape();
  rect.graphics.beginFill("blue").drawRoundRect(0, 0, 350, 30, 8);
  rect.name = a;

  var name = new createjs.Text(gameData.Terms[a].Definition, "14pt arial bold", "white");
  name.id = gameData.Terms[a].Name;
  name.textAlign = "left";
  name.y = rect.y + 2;
  name.x = rect.x + 4;

  var sequenceNumbers = new createjs.Container();

  sequenceNumbers.landingSpot = landingSpots[a];
  landingSpots[a].sequenceNumber = sequenceNumbers;

  sequenceNumbers.addChild(rect, name);
  stage.addChild(sequenceNumbers);
  sequenceNumbers.x = 300;
  sequenceNumbers.y = xOffset;
  xOffset += 40;

  var startPositionX;
  var startPostitionY;
  sequenceNumbers.on('mousedown', function (e) {
    stage.adchild(sequenceNumbers);

    var posX = e.stageX;
    var posY = e.stageY;
    startPositionX = e.stageX;
    startPositionY = e.stageY;
    this.offset = { x: this.x - posX, y: this.y - posY };
  });

  sequenceNumbers.on("pressmove", function (evt) {
    evt.currentTarget.x = evt.stageX;
    evt.currentTarget.y = evt.stageY;
    var posX = evt.stageX;
    var posY = evt.stageY;
    this.x = posX + this.offset.x;
    this.y = posY + this.offset.y;

    stage.update();
  });

  sequenceNumbers.on("pressup", function (evt) {
    var stuffUnderMouse = landingSpotContainer.getObjectsUnderPoint(evt.rawX, evt.rawY, 0);
    var oldSpot = evt.currentTarget.landingSpot;
    var spotToMoveTo = null;
    for (var i = 0; i < stuffUnderMouse.length; ++i) {
      if (typeof stuffUnderMouse[i].landingSpot !== 'undefined' && stuffUnderMouse[i].landingSpot != oldSpot) {
        spotToMoveTo = stuffUnderMouse[i].landingSpot;
        break;
      }
    }
  }

Comment: I have been responding to http://stackoverflow.com/questions/33109223/adjusting-zindex-with-createjs/33109263#33109263 -- see my latest comment. Note that re-posting makes it difficult to help.
Answer: Just add the child again to its parent container:
evt.currentTarget.parent.addChild(evt.currentTarget);

should do the trick inside the mouse event function.
Notice the function is called addChild and not adchild.

Stage.addchild to bring object to front


How to listen to each individual voice of a piece of polyphonic music?

Question: When listening to a piece of polyphonic music, I can only hear the soprano part, but not the other voices, because the soprano part is making it difficult to hear the other voices. So, I can only transcribe the soprano, not the whole piece, and I'd like to know what kind of practice should I do to start listening to each individual voice of the music, so that I can transcribe all of it.
Comment: One tip: Try different playback devices to make sure you're getting the best chance. I've often listened to a familiar track on a different device than usual and heard parts I hadn't noticed before. Use the highest fidelity audio possible, not something highly compressed. You can of course then progress to experimenting with EQ to try to isolate individual parts, but even before doing that, experiment with what's making the audio in the first place.
Comment: @AndyBonner indeed, and different recordings.  This reminds me of taking the music GRE -- the listening questions included one asking us to identify the inversion of a chord, but we were sitting around a conference table in a seminar room and the tape was being played on a Panasonic Slimline cassette player with a single 8 cm speaker.  I, at least, couldn't hear the bass part, so I could only guess at the answer.
Comment: Do you sing/play an instrument? If you learn how to play the other parts, you'll gain some skill in isolating it.
I myself am a violinist and have had experience playing in both an all-strings group and an orchestra. Those experience helps with my listening a lot.
Answer: Start with two parts.  Find a piece for which you have both a recording and sheet music.  Listen to the recording while following the lower part.  Sing along if you can, sometimes, and sometimes just listen and follow in your mind.  If you play an instrument, play along once in a while.  It's best to experience the second part in as many different ways as you can.
If you play piano or any other instrument where you can learn to play both parts at the same time, definitely do that, too.  Better still: play one part and sing the other.  This takes practice!  But it's a great way of stretching your ear and your mind to hang on to multiple independent parts simultaneously.  Once you can sing one part while playing the other, switch.
Above all, don't do only one of these things; do as many of them as you can, and mix them as much as you can.  The point is to experience the music in as many ways as possible, to get to know the second part as an independent entity as thoroughly as possible.
Once you've done that, try it again with a different piece.  You should find that each time you do it, you reach your goal more quickly.
As you become comfortable with these exercises in two parts, begin moving to larger numbers.
If you experience this problem particularly with polyphony, try starting with more homophonic pieces and moving to more polyphonic ones.  A good link between the two is probably the late Renaissance, where many pieces are mostly homophonic in conception, but not strictly so, so you'll find different rhythms in one part just for a measure or two.
Pick up an exercise book on score reading.  These are largely about learning different clefs and transposition, but the good ones I've seen also address part independence.
Answer: I think this is quite common, Gabriel. We're used to listening for the tune, and in a great deal of music that's often the highest part and it's often the loudest. But with practice you can learn to focus on any part.
I'd suggest you get hold of both the sheet music and a recording of a 4-part choral piece and practice (or practise if you're British!) singing or playing each part in turn.
You could start with this 'air' by John Dowland:
What If I Never Speed (Sheet music here)
Maybe start by playing or singing the bass part along with the clip.
Then - this is what you're aiming for - don't play or sing anything: just listen to the piece, paying attention to the part you've been playing. If you can't hear it, try imagining it. Then see if you can hear it!
Then work your way through the tenor and alto parts, doing the same.
Finally, as you listen, see if you can switch your attention from one part to another.
Here's another piece to try. It's from three centuries later and is a little more dissonant, but it's slower and therefore maybe easier. It's by Charles Villiers Stanford.
The Blue Bird (with vocal score.)
Let us know how you get on.
Comment: Nice.  When I mentioned the late Renaissance I was thinking of some German pieces but also of Dowland's "Fine Knacks for Ladies" -- in particular the way the tenor here sings "still on sorrow" with eighth, eighth, half, quarter while the others have quarter notes.  There, the same rhythms appear on the words "money can not" and (if I remember correctly) it is the alto that takes the role given here to the tenor.
Comment: Good point! The difference in the rhythms may help to identify the individual parts. I remember singing that [Fine Knacks For Ladies](https://www.cpdl.org/wiki/images/e/ea/Dow-Fine_knacks.pdf) when I was a treble. But I could have sworn we sang the first four of the trebles' bars and the next four bars of the _altos'!_ It makes a better tune than that of the trebles alone! Perhaps Dowland did it deliberately: moving the tune around spatially.
Answer: Practice transcribing music where two musical lines are quite separate in both character and sound, e.g. the melody and the bass line in a pop song.   Progress to 2-part exercises using the same sound.  Then SATB hymn tunes.
I could waffle on.  But you get the idea.  Set up a structured scheme of study, starting with simple material, then progress.


Como fazer um XMLHTTPRequest para enviar valores para a propria página?

Question: O que eu tenho:
Eu criei vários botões atraves do PHP e para os distinguir usei a variável $botoes_criados.
Então eu tenho o valor da variável $botoes_criados em PHP que é passada para um botão da seguinte forma:
echo("
$botoes_criados
");

De seguida eu fiz um javascript para receber atraves da função pagination()   recebe a variável $botoes_criados através do parâmetro.
O que eu pretendo fazer:
Pretendo passar o valor dessa variável para o PHP de volta para assim saber que botão foi clicado.
O que eu tentei fazer:

No PHP tenho o seguinte código para tentar receber o valor da variável
Echo($_GET['b']);

Resumindo: Tudo o que eu quero é fazer um XMLHTTPrequest para a propria pagina para que possa recolher a informacão dessa variavel.
Caso não entenda a minha pergunta comente que eu edito.
Answer: Usar $botoes_criados para fazer a página recarregar como sugeriste na resposta não faz muito sentido.
Há uma resposta que pode ser útil ler. No teu caso tens duas opções a meu ver:

recarregar a página completamente
usar ajax para ir buscar novo conteúdo para não recarregar a página

Na tua resposta usas a primeira opção. Nesse caso, se vais recarregar a página nem precisas de JavaScript, podias fazer simplesmente
$botoes_criados

Se queres evitar carregar a página novamente, então ajax como referes na pergunta é a ferramenta a usar. E nesse caso envias os dados para o PHP, e ele deve retornar o novo conteúdo.
var request = new XMLHttpRequest();
request.open('GET', window.location.pathname + '?b=<?php echo $botoes_criados; ?>', true);
request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Successo!
    var data = request.responseText;
  } else {
    // Deu erro

  }
};
request.send();

No PHP precisas de usar o get como tens na pergunta, processar e decidir o que enviar de volta.
Answer: Resolvi o problema da seguinte forma


Is $f(x,y)=(xy)^{2/3}$ differentiable at $(0,0)$?

Question: I looked at the graph of $f(x,y)=(xy)^{2/3}$ at the origin, and no matter how far I zoom in it has four corners along $x=\pm y$, so it doesn't look like it is differentiable as $z=0$ doesn't look like a tangent plane.
I also found that its partial derivatives are not continuous at $(0,0)$, e.g.
$$
\lim_{(ky^2,y) \to (0,0)} \frac{\partial f}{\partial x} = \lim_{(ky^2,y) \to (0,0)} \frac{2}{3}x^{-\frac{1}{3}}y^{\frac{2}{3}} = \frac{2}{3}k^{-\frac{1}{3}}
$$
(although $\frac{\partial f}{\partial x}(0,0) = \frac{\partial f}{\partial y}(0,0) = 0$)
I also tried to prove/disprove its differentiability by definition, and for it to be differentiable I need
$$
\lim_{(x,y) \to (0,0)} \frac{f(x,y)-0}{\sqrt{x^2+y^2}} =0
$$
but then I got stuck. Am I even on the right track?
[UPDATE] I need to do the same thing for $f(x,y)=(xy)^{\frac{1}{3}}$... I think the answer is that $(xy)^{2/3}$ is differentiable but $(xy)^{1/3}$ is not, according to my professor but I'm not sure
Comment: I just wonder if $x<0$, $y>0$, how can we define $f(x,y)$ ?
Comment: Only use real roots
Comment: How does $\frac{\partial f}{\partial x}(0,0)=0$? Isn't that undefined?
Answer: Neither functions have continuous partials at $(0,0)$, but as you said $f(x,y)=(xy)^{\frac{2}{3}}$ is surprisingly differentiable at $(0,0)$ but $f(x,y)=(xy)^{\frac{1}{3}}$ is not.
For $f(x,y)=(xy)^{\frac{2}{3}}$, continuing with where you left off:
$$
\lim_{(x,y) \to (0,0)} \frac{f(x,y) - 0}{\sqrt{x^2+y^2}} = \lim_{(x,y) \to (0,0)} \frac{((xy)^2)^{\frac{1}{3}}}{\sqrt{x^2+y^2}} \le \lim_{(x,y) \to (0,0)} \frac{((x^2+y^2)^2)^{\frac{1}{3}}}{(x^2+y^2)^{\frac{1}{2}}} = \lim_{(x,y) \to (0,0)} (x^2+y^2)^\frac{1}{6}
$$
where we used the inequality $xy \le x^2 + y^2$. The last expression approaches $0$ no matter how $(x,y)$ approaches $(0,0)$ (in polar coordinates $r^{\frac{1}{3}} \to 0$ as $r \to 0$), so we conclude $f$ is indeed differentiable at $(0,0)$ by definition (no matter how crazy and unconvincing the graph looks).
For $f(x,y)=(xy)^{\frac{1}{3}}$, which also has $z=0$ as the candidate tangent plane, repeat the same procedure:
$$
\lim_{(x,y) \to (0,0)} \frac{f(x,y) - 0}{\sqrt{x^2+y^2}} = \lim_{(x,y) \to (0,0)} \frac{(xy)^{\frac{1}{3}}}{\sqrt{x^2+y^2}}
$$
here we have a smaller numerator and the same trick doesn't work as we get something like $\lim_{(x,y) \to (0,0)} (x^2+y^2)^{-\frac{1}{6}}$ which blows up as we approach the origin. In fact the limit does not exist:
$$
\lim_{(x,0) \to (0,0)} \frac{(xy)^{\frac{1}{3}}}{\sqrt{x^2+y^2}} = 0
$$
however
$$
\lim_{(x,x) \to (0^+,0^+)} \frac{(xy)^{\frac{1}{3}}}{\sqrt{x^2+y^2}} = \lim_{(x,x) \to (0^+,0^+)} \frac{1}{\sqrt{2}} x^{-\frac{1}{3}} = \infty \\
\lim_{(x,x) \to (0^-,0^-)} \frac{(xy)^{\frac{1}{3}}}{\sqrt{x^2+y^2}} = \lim_{(x,x) \to (0^-,0^-)} -\frac{1}{\sqrt{2}} x^{-\frac{1}{3}} = -\infty
$$
so we conclude $f(x,y)=(xy)^{\frac{1}{3}}$ is not differentiable at $(0,0)$, although its graph doesn't look much crazier than that of $(xy)^{\frac{2}{3}}$ .
The lessons are:

Continuous partials are not necessary (although sufficient) for differentiability;
Graphs can occasionally be counter-intuitive!
Answer: You have two options: 1) Go to polar coordinates (x=rcos$\alpha$ and y=rsin$\alpha$ where $r=\sqrt{x^2+y^2}$). And 2) This function converges to zero in $(0,0)$, so you need to find a sequence of $(u_k,v_k)$ such that $(u_k,v_k)$ $\to (0,0)$ but $f(u_k,v_k)\neq0$.


O uso e não uso da palavra function no TypeScript

Question: Por que quando declaro método em uma classe o compilador apita, informando que esta errado o uso da palavra function.
Em lições anteriores do meu aprendizado para criar uma função assinava primeiramente como function.
abstract class Empregado {
    abstract getFuncao():string;
}

class Professor extends Empregado {
    getFuncao():string {
        return "Professor";
    }
}

class Diretor extends Empregado {
    getFuncao():string {
        return "Diretor";
    }
}

Answer: A resposta já está na pergunta.
Porque você não declara funções dentro de uma classe, declara métodos, então não faria sentido usar function. Além do que dentro de uma classe o compilador tem mais controle do que está acontecendo (a sintaxe é menos ambígua) e pode determinar o início e fim do método, por exemplo não pode ter uma método dentro de outro, mas é possível ter uma função dentro de um método.
Comment: @Macario1983 Isso
Comment: Interessante! Como vc mencionou, eu respondi, mas foi uma curiosidade, ou seja, function é mais para `scripts` a nível procedural.


Add to an array in PHP

Question:
Possible Duplicate:
array_push() vs. $array[] = … Which is fastest?

Is it better to use [] or array_push() to add to an array in PHP?
I always use array_push(), but only because it seems proper.
<code>$array = array();

array_push($array, array('1', '2', '3'));

// or

$array[] = array('1', '2', '3');
</code>
Comment: http://stackoverflow.com/questions/1074059/array-push-vs-array-which-is-fastest
Comment: its better to use array_push() to add elements in an php array
Comment: See the second answer of the duplicate question. You question is not an *exact duplicate* but that answer is good for this one too.
Answer: I believe $array[] is more efficient.
Comment: Turns out thats because i've seen it here : http://stackoverflow.com/questions/2431629/php-array-push-vs-myarray - do I delete my answer as it's a dup?
Answer: When comparing alternative syntax constructs, there are multiple attributes to take into consideration:

"better"
faster
readability

Only one of them is valid.

Add to an array in PHP


Normal Linear Model: Prediction of original variable from log transformed variable?

Question: Suppose we have observations $(x_1,y_1),\dots, (x_n,y_n)$ which for some reason cannot be modelled reasonably using a Normal Linear Model. Assume we instead model the log transformed response variables as from a Normal Linear Model i.e. $\text{log}(Y_i) \sim N(\alpha +\beta x_i, \sigma^2)$. Say we have estimated $\alpha$ and $\beta$ as $\hat{\alpha}$ and $\hat{\beta}$ respectively. Then we can from a new observation $x_*$ predict $E[\text{log}(y_*)]$ as $\hat{\alpha} + \hat{\beta} x_{*}$.
But say we really were interested in $E[y_{*}]$ instead, can we predict this? It seems to me we cannot just take the exponential function on either side as this cannot be moved into the expected value. Can we say anything about the relationship between $x_*$ and $E[y_{*}]$?
Comment: We have several useful threads in this regard: see https://stats.stackexchange.com/search?tab=votes&q=Duan%20log.
Answer: You are right, you can't simply take the exponent. It seems that it is a log normal distribution.
If $Log(Y)$ is normally distributed with $\mu, \sigma^2$, then $Y$ is Log normally distributed with these parameters.
The expectation of a log normally distributed variable is:
$exp({\mu +\frac{\sigma^2}{2}})$
So you will have to learn $\sigma$ as well. You can do so, by model your output as distribution instead of a single number. i.e. in addition to the $\alpha + \beta x_i$, you need to output $\sigma_i$ as well and use likelihood as the loss function.
You can read about log normal distribution here


WYSIWYG-editor with "add custom html feature" and secure (validated) html output?

Question: I've been looking into some of the WYSIWYG editors (TinyMCE, FCKEditor, etc.) and they all seem to offer a lot of options.
However, one vital feature that seems to lack is a simple "add custom html" option which would allow the user to input any of these embed-snippets you find all around the web these days, for example a youtube video. This is different than a "edit html/source" feature as that requires actual knowledge of html and there is the risk of the user writing invalid code.
Another issue that I couldn't find much about is the output html. How would I make sure that this output causes no security invulnerabilities? Even when the user has the ability to add his own html?
So, basically, is there an open source WYSIWYG editor which covers these 2 features?
Answer: FCKEditor achieves this via plugins. e.g. http://sourceforge.net/projects/youtubepluginfo/
Comment: The YouTube embed was just an example, I'm looking for a feature which allows the user to embed any html snipper. This would work for youtube videos, vimeo, but also google gadgets, etc. Any service that offers embedding html snippets.
Comment: Ah right, I'm pretty sure this would be very easy to do as a plugin as well but then you'd have to worry about the security stuff as you say. I'm not really sure what your threat model is. If this is a public website then it will still be possible for people to inject arbitrary HTML into the request submitted to the server regardless of what functionality you expose in the WYSIWYG editor.
Comment: Yeah, the output will be checked server-side. I am amazed though that such html snippet feature doesn't exist by default. I think the problem lies in the visual positioning of the html result. Eg. if you embed a youtube video, how are you going to position it without knowledge of html?
Comment: @Tom I think the reason why "insert HTML snippet" doesn't exist is that it's a one-way street only: Once the HTML is injected, there's no way to select that injected snippet and edit it again. Plus, the danger of injecting invalid HTML is *huge*. If you force people to open the source code view and make their edits there, they are at least likely to know what they're doing.
Comment: This might help? http://sourceforge.net/tracker/index.php?func=detail&aid=1658125&group_id=75348&atid=737639
Comment: That plugin seems outdated as the project seems to have evoled in CKEditor. I'm going to see if there are any more suggestions and if not will give such plugin a try.
Answer: For the first part, you either have the "view source" view of the editor or, if that is too complex, I'm pretty sure such plugins already exist for all major editors. If they don't, building a "insert arbitrary HTML" plugin should be easy to implement by tweaking another simple plug-in like the youTube one linked to in Martin's answer.
The second part - sanitizing the incoming HTML - is impossible to achieve in the WYSIWYG editor itself, because it acts solely on the client side, and fills content into a form input that could be manipulated anyway, even though you turn off the "custom HTML" function in the editor.
Therefore, the sanitizing of the HTML needs to take place on server side. If you can use PHP, a tool that looks very good to me from the outside - I haven't worked with it but plan to in the near future - is HTML Purifier. It claims to produce reliable HTML with minimum hassle.


FB.Event.subscribe('auth.login', function(response) { }) issue

Question: FB.Event.subscribe('auth.login', function(response) {
FB.api('/me', function(response){
    //Some operation
});});

Above piece of JavaScript code runs when user logs-in through Facebook
or
when user is already logged-in the browser and you open the page containing the above JavaScript.
Is there any way to execute the operation only when user logs-in for first time and escape the operation when user is already logged-in in the browser?
Answer: Run FB.getLoginStatus to see if the user is already connected to your app and logged in.
https://developers.facebook.com/docs/reference/javascript/FB.getLoginStatus/
FB.getLoginStatus(function(response) {
  if (response.session) {
    // logged in and connected user, someone you know
  } else {
    // no user session available, someone you dont know
  }
});

Answer: Try subscribing to the event if and only if the user is not connected.
function listen_for_authorization (cb) {
  FB.getLoginStatus(function (res) {
    if (!res || res.status !== "connected") {
      FB.Event.subscribe('auth.login', cb);
    }
  }
}

We reproduced this in Safari/Mac, Firefox/Windows, Internet Explorer.
See http://developers.facebook.com/bugs/255767001140894


What is the ruling in badminton when the shuttlecock (birdie) rests on the top of the net?

Question: During badminton matches, in very rare circumstances, the shuttlecock (birdie) will fall to rest on the top of the net.  I'm not referring to when the shuttlecock gets stuck in the mesh of the net; I'm referring to when the shuttlecock literally lands - feathers down - on the top edge of the net, and continues to rest there without further movement.
This is exceptionally rare, but when it happens, it is usually the result of a lob play that is initiated close to the net and is performed with very low velocity and minimal spin.
Here is a link to video of a great example of this occurring:
https://www.viewpure.com/sXls9PPr54Q
What is the correct ruling when this happens, and why?
Answer: The shuttle stuck on top of the net is a fault during service and a let otherwise, according to the Laws of Badminton:

§13.2.1 It shall be a fault if in service the shuttle is caught on the net and remains suspended on its top.

§188.8.131.52 It shall be a let if after the service is returned, the shuttle is
caught on the net and remains suspended on its top.


Edit panel not showing up (Gear -> Edit Panel -> NOTHING??)

Question: If I go to a custom panel and click the gear, then click edit panel, the link changes as if a popup appeared, but nothing else shows up. I cleared my cache on my browser, computer, on the website, and even tried it on my coworker's computer but it still doesn't work. I also tried it on Chrome, Firefox, and Safari and still no success.  Any thoughts?
Comment: can you open console in the browser? maybe you have error in JavaScript
Comment: **Uncaught TypeError: Cannot read property 'msie' of undefined**

and

**Uncaught TypeError: Cannot read property 'close' of undefined**

those are the two js errors I'm getting
Comment: try to fix these errors and the your panel will work
Answer: You or one of the modules you installed is loading latest version of jQuery.  In the latest version of jQuery code like
<code>if (jQuery.browser.msie && parseInt(jQuery.browser.version, 10) < 8) {}
</code>
does not work.
This code is in one of the Drupal core files. You can find it in modules/overlay/overlay-parent.js file on line 932, 975 and 985.
I do not recommend editing this file, but you can test this change on your localhost to make sure it is the latest version of jQuery which is causing this issue.
Comment: So are you recommending that I update jQuery?
Comment: I am recommending to make sure your site is loading default version of jQuery not the updated or latest version. In older version of jQuery drupal code works.


Levels in a mixed effect model with interaction representation

Question: I am trying to understand how to stratify two different mixed effect models. For this, I am reading this guide for mixed effect models.
https://rpsychologist.com/r-guide-longitudinal-lme-lmer#conditional-growth-model-dropping-intercept-slope-covariance
In this article, they mentioned that in a Conditional three-level growth model of the form.
m1 <- lmer(y ~ time*tx +
             (time | subjects:therapist) +
             (1 | therapist) +
             (0 + tx | therapist) +
             (0 + time | therapist) +
             (0 + time:tx | therapist), data=df)

I want to apply a similar reasoning for my two models :
fit 1 <- lmer(lVolume ~ Country * Day + (1 | Rat.ID))

fit 2 <- lmer(lVolume ~ Country * Day + (1 + Day| Rat.ID))

In both models, I am interested in the prediction of exp(fitted) (I fit an exponential model, that is why I took lVolume).
For model fit1, if I am not wrong, what I am estimating is :
$$
\begin{aligned}
  \operatorname{lVolume}_{i}  &\sim N \left(\alpha_{j[i]} + \beta_{1}(\operatorname{Day}), \sigma^2 \right) \\
    \alpha_{j}  &\sim N \left(\gamma_{0}^{\alpha} + \gamma_{1}^{\alpha}(\operatorname{Country}_{\operatorname{England}}) + \gamma_{2}^{\alpha}(\operatorname{Day} \times \operatorname{Country}_{\operatorname{England}}), \sigma^2_{\alpha_{j}} \right)
    \text{, for Rat.ID j = 1,} \dots \text{,J}
\end{aligned}
$$
For model fit2, if I am not wrong, what I am estimating is :
$$
\begin{aligned}
  \operatorname{lVolume}_{i}  &\sim N \left(\alpha_{j[i]} + \beta_{1j[i]}(\operatorname{Day}), \sigma^2 \right) \\
\left(
  \begin{array}{c}
    \begin{aligned}
      &\alpha_{j} \\
      &\beta_{1j}
    \end{aligned}
  \end{array}
\right)
  &\sim N \left(
\left(
  \begin{array}{c}
    \begin{aligned}
      &\gamma_{0}^{\alpha} + \gamma_{1}^{\alpha}(\operatorname{Country}_{\operatorname{England}}) \\
      &\gamma^{\beta_{1}}_{0} + \gamma^{\beta_{1}}_{1}(\operatorname{Country}_{\operatorname{England}})
    \end{aligned}
  \end{array}
\right)
,
\left(
  \begin{array}{cc}
     \sigma^2_{\alpha_{j}} & \rho_{\alpha_{j}\beta_{1j}} \\
     \rho_{\beta_{1j}\alpha_{j}} & \sigma^2_{\beta_{1j}}
  \end{array}
\right)
 \right)
    \text{, for Rat.ID j = 1,} \dots \text{,J}
\end{aligned}
$$
So, I doubt how I can interpret my two models in terms of the organization chart from the guide and get the level equations similar to the guide lecture. I really don't understand the differences in (1 + Day | Rat.ID) and (1 | Rat.ID) because, to me, both models estimate the amount of variation in the rate of change of volume between rats. Is this correct?
I really appreciate any kind of thoughts and help/hints for this. Thanks.
Answer: Your situation is much simpler than the multi-level model that you first cite as an example. I'd recommend that you start by looking at this site's lmer cheat sheet, and its links, about mixed models. Only then should you look at more complex models.
As the notation in your question is a bit confusing, I'll limit myself to trying to clarify some conceptual issues.
Both your fit1 and fit2 include fixed effects of Country and Day and their interaction. The models only differ in the random effects. Your interpretation of those models seems to be incorrect in a few ways.
First, the coefficients not only for Day but also for Country and for their interaction should appear in the fixed-effect part of the model. You only show Day there explicitly in both attempts at interpreting the lmer models. Perhaps that's implied in the way that you wrote the random-effects parts of the model, but it's hard to say.* The random effects are usually presented as having means of 0, which is not how you wrote them for either of your models.
Second, there is no separate modeling of $\sigma_{a_j}^2$ for each Rat, as one might interpret the way you wrote the random effects for both models. In fit1 a single Gaussian distribution is fit to all of the individual Rat intercepts. (Perhaps that's what you intended, but the extra $j$ subscript is confusing.**) Those random intercepts just allow for variation among Rats about the fixed-effect intercept. To be clear, there is no modeling of Country or the Country:Day interaction within individual Rats (although it's hard to know if that's what you intended to convey). That model does NOT "estimate the amount of variation in the rate of change of volume between rats," just their hypothetical log-volumes at Day = 0 and your baseline value of Country.
In fit2 the (1 + Day| Rat.ID) term does also allow for differences among rats in the Day coefficient, which you can consider the slope with respect to time. Again, the extra $j$ subscripts in your random-effect variance terms is a bit confusing;** there is just one Gaussian distribution of slopes encompassing all Rats. The fit2 also models correlations between the individual intercepts and the slopes with respect to time in a way that is similar to what you write; see the cheat sheet linked above.
In response to comment and related question:
The equations you show are evidently from the extract_eq() function of the equatiomatic package. That can include fixed-effect terms in the mean values of expressions for random-effect terms, as explained for your fit1 in this answer. Furthermore, its choice of symbols used to describe a model can be more complicated than is needed for simple models like yours. That led to some of the confusion in my original interpretation (above) of those equations.
With respect to your fit2, recognize that all terms in mean values for expressions of random effects that don't involve your random effects of rats, indexed by $j$, are part of the fixed-effect portion of the model. I find it simplest to first assume that the coefficients involved in random effects are at their mean values, to obtain the full fixed-effect part of the model. Then evaluate the random-effect (co)variance terms as having zero means, adding to the fixed effects the random-effect terms for each rat $j$.
In your fit2, at the mean values of $\alpha_j$ and $\beta_{1_j}$ for the first term in the extract_eq() output, you would have for the distribution of fixed effects plus error variance $\sigma^2$:
$$lVolume \sim N\left(\gamma_{0}^{\alpha} + \gamma_{1}^{\alpha}(\operatorname{Country}_{\operatorname{England}}) + \left(\gamma^{\beta_{1}}_{0} + \gamma^{\beta_{1}}_{1}(\operatorname{Country}_{\operatorname{England}})\right)(\operatorname{Day}), \sigma^2 \right). $$
Multiplying out the terms in the mean value for this normal distribution, the overall fixed-effect intercept is thus $\gamma_{0}^{\alpha}$; $\gamma_{1}^{\alpha}$ is the fixed-effect coefficient for Country; $\gamma^{\beta_{1}}_{0}$ is the fixed-effect coefficient for Day; $\gamma^{\beta_{1}}_{1}$ is the fixed-effect coefficient for the Day by Country interaction.
Then you can simply think of the random-effect coefficients as distributed bivariate normal with means of 0 and the covariance structure indicated in your answer. Those add extra terms to what's predicted based just on fixed effects. The random intercept term is just added directly. The random slope is first multiplied by the corresponding Day value, then added.

*I now understand that this display is based on the extract_eq() function of the equatiomatic package. You can extract the fixed-effects portion of the model by substituting the mean values of the random effects into the corresponding portions of the model. Then the random effect coefficients have 0 means, to incorporate into terms that include the random effects.
**This is also from extract_eq(). It indexes the rat random effects with $j$ and calls the intercept $\alpha$. So $\sigma^2_{\alpha_j}$ is meant to represent the variance of the random intercept $\alpha_j$; $\sigma^2_{\beta_{1_j}}$ represents the random-effect variance of the $\beta_1$ coefficient.
Comment: @RosaMaria I think that my answer to [another of your questions](https://stats.stackexchange.com/q/568329/28500) explains that for `fit1`. I hadn't appreciated that your equations come from the `extract_eq()` function in the `equatiomatic` package. The terminology used by that function can be hard to understand, even in simple cases, as it can include things that are fundamentally fixed effects as part of its formulas for random effects. You seem to have several  related questions on this site; please see if you might be able to delete some of them now.
Comment: @RosaMaria fitting an `lmer` model assumes that each random effect comes from a normal distribution and that the residual variance is also normally distributed. The actual estimates of the individual random effects need not strictly follow a normal distribution, as the model must fit both the fixed and the random-effect terms together so there will be tradeoffs from ideal normality. The distribution of "predicted values" for the entire model depend on the distributions assumed for the fixed-effect predictors and the choice of values for the random effects.
Comment: Now I understood a little bit more what you ment, it took me a while sorry, which it is still a bit confusing is the mathematical interpretation, let's just say fit1. We have only the Passage*Day interaction. But how can I represent the model fit1 : fit 1 <- lmer(lVolume ~ Country * Day + (1 | Rat.ID))  in terms of expected values and variances if I can ask.
Comment: Hi sorry to bother you again, a technical question: the distribution of the predicted values by the lmer model follows a normal distribution approximately or almost a normal distribution or can it be non normal ? Thanks


ASP.NET MVC - Converting a complex control to be MVC-friendly

Question: I have an ASP.NET WebForms control (derived from Control, not WebControl, if it helps) that has a rather complicated Render() function. The control has no viewstate and only uses the Control approach so it can render output directly. I feel it's a fine candidate for working with the MVC approach.
I'd like to use it in an MVC application I'm using, however I don't know what's the best way to go about it.
At first I thought about converting it to a HTML Helper method, but my control renders a large amount of HTML so the Helper method (with it returning strings) isn't too attractive.
The alternative is a PartialView, but those are UserControl derivatives, which wouldn't be appropriate in this case.

I see other HTML Helper methods don't return HtmlString, but actually use HtmlHelper.ViewContext.Writer to write output directly, but according to this question ( HtmlHelper using ViewContext.Writer not rendering correctly ) he was getting strange results. I'd like to avoid that mishap.

EDIT:
I think I've solved it using the HtmlHelper.ViewContext.Writer approach, and I haven't experienced the same problem as the problem I quoted.
Here's the code I wrote:
public static class MiniViewHelper {

    public static void RenderMiniView<TModel>(this HtmlHelper html, MiniView<TModel> view, TModel model) {

        TextWriter wtr = html.ViewContext.Writer;
        HtmlTextWriter hwtr = wtr as HtmlTextWriter;
        if( hwtr == null ) hwtr = new HtmlTextWriter( wtr );

        view.Render( hwtr );
    }

}

public abstract class MiniView<TModel> {

    public TModel Model { get; set; }

    public abstract void Render(HtmlTextWriter wtr);

}

public class VeryComplicatedMiniView : MiniView<ComplicatedViewModel> {

    public override void Render(HtmlTextWriter wtr) {

        wtr.WriteLine("VeryComplicatedMiniView ");
    }

}

Used like so from my pages:
<% Html.RenderMiniView( new VeryComplicatedMiniView () { Propery1 = foo }, Model.RelevantMiniViewModel ); %>

Any thoughts?
Answer: The two approaches you have outlined in your question are correct. You could either try to write a custom HTML helper which will spit the same HTML as the control or use a partial.

I see other HTML Helper methods don't return HtmlString, but actually
  use HtmlHelper.ViewContext.Writer to write output directly

ViewContext.Writer should be fine. Returning an IHtmlString from the helper is also fine. Just make sure you are properly encoding it inside since IHtmlString will not be automatically HTML encoded in Razor and it supposes that the helper takes care of this. Using a TagBuilder to generate a DOM tree in a helper is a good approach.
Comment: Thanks. I've amended my question with the code I wrote to solve the problem. Can you please give me some feedback on it? Thanks!


A question on circle

Question: I was solving sample maths paper and came through this question:-
If a ball is dropped on ice having a diameter of $24cm$ and fill inside with depth of $8cm$, find the radius of the circle drawn over ice if the ball is pull outside ?
I was not able to understand the question. Please help.
Edit
My solution:-

$\text{Hypotenuse} = 12$
$\text{Height} = 4 cm$
So $(\text{Base})^2 = 12^2 - 4^2 = 128$
Is it correct ?
Answer: Hint
Draw a picture and use the Pythagorean theorem.
Answer The radius: $8\sqrt{2}$.
Comment: @Vivek, can you see a right angled triangle there? Hint: one its sides is the radius of the circle you are interested in.
Comment: Please provide more guidance. I have updated my answer.
Comment: Draw also the center of this circle and its orthogonal projection on the ice's surface and try to find a right triangle.
Comment: @VivekSadh This is a really good hint. If you are stuck, you're going to have to tell us where.
Comment: Thanks Sami and Jyrki for giving excellent hint :)
Comment: @VivekSadh You're welcome:)
Answer: My solution:-

Hypo = 12
Height = 4 cm
So Base^2 = 12^2 - 4^2 = 128
Thanks for the help :)
Comment: Yes, it is correct.

A question on circle