Como tornar o cmd mais lento

Question: Existe algum comando para que o cmd execute um programa que eu mande rodar a partir do compilador? Gostaria de Debugar o que fiz e, como frequentemente caio em loop infinito, quero saber se tem como fazer o cmd executar de forma mais lenta (muito mais lenta) para que de tempo de ver em que ponto o programa está travando.
Comment: Já experimentou utilizar uma `IDE` para debuggar de verdade?
Comment: Com que ferramentas é que escreves e compilas os programas? Para além dos IDEs também há "debuggers" à parte como o `gdb`. Normalmente, podes usar "breakpoints" para fazer o "debugger" parar numa linha do código, e depois avançar passo a passo.
Answer: A tua melhor opcao 'e usar um debugger.
Com um debugger podes correr o programa linha a linha, podes inspeccionar o valor de variaveis antes e depois de cada instrucao ou funcao, podes mudar o valor de variaveis dinamicamente, ..., ...
Cada compilador tem o seu debugger especifico. Muitos IDEs integram o debugger no ambiente de desenvolvimento de forma natural; se ao usas IDE o uso do debugger pode nao ser tao natural mas 'e perfeitamente razoavel.
Outra forma que tens 'e usar printfs dentro do programa para veres o que esta a acontecer a uma ou mais variaveis
for (i = 0; i < 10000; i++) {
    fprintf(stderr, "DEBUGGING: i = %d; j = %d; x = %f\n", i, j, x);
    /* resto do loop */
}

Answer: Você pode usar interruptores (Exemplo abaixo... Não funciona em todos os locais, pois a instrução pode variar entre plataformas) :
#include <stdio.h>
#include <stdlib.h>

int main (void) {

   const int teste = 3;
   __asm__ ("int3");
   int teste2 = 5;
   __asm__("int3");

  return 0;
}

gcc -g teste.c
gdb a.out
run
Program received signal SIGTRAP, Trace/breakpoint trap.
main () at teste.c:8
8      int teste2 = 5;

continue
Program received signal SIGTRAP, Trace/breakpoint trap.
main () at teste.c:13
13    return 0;

Para ver o conteúdo das variáveis, só digitar: info locals
(gdb) info locals
teste = 3
teste2 = 5

Como tornar o cmd mais lento


Python - Select elements from matrix within range

Question: I have a question regarding python and selecting elements within a range.
If I have a n x m matrix with n row and m columns, I have a defined range for each column (so I have m min and max values).
Now I want to select those rows, where all values are within the range.
Looking at the following example:
input = matrix([[1, 2], [3, 4],[5,6],[1,8]])
boundaries = matrix([[2,1],[8,5]])
#Note:
#col1min = 2
#col1max = 8
#col2min = 1
#col2max = 5
print(input)

desired_result = matrix([[3, 4]])
print(desired_result)

Here, 3 rows where discarded, because they contained values beyond the boundaries.
While I was able to get values within one range for a given array, I did not manage to solve this problem efficiently.
Thank you for your help.
Comment: explain your question in brief!
Answer: Your example data syntax is not correct matrix([[],..]) so it needs to be restructured like this:
matrix = [[1, 2], [3, 4],[5,6],[1,8]]
bounds = [[2,1],[8,5]]

I'm not sure exactly what you mean by "efficient", but this solution is readable, computationally efficient, and modular:
# Test columns in row against column bounds or first bounds
def row_in_bounds(row, bounds):
    for ci, colVal in enumerate(row):
        bi = ci if len(bounds[0]) >= ci + 1 else 0
        if not bounds[1][bi] >= colVal >= bounds[0][bi]:
            return False
    return True

# Use a list comprehension to apply test to n rows
print ([r for r in matrix if row_in_bounds(r,bounds)])
>>>[[3, 4]]

First we create a reusable test function for rows accepting a list of bounds lists, tuples are probably more appropriate, but I stuck with list as per your specification.
Then apply the test to your matrix of n rows with a list comprehension. If n exceeds the bounds column index or the bounds column index is falsey use the first set of bounds provided.
Keeping the row iterator out of the row parser function allows you to do things like get min/max from the filtered elements as required.  This way you will not need to define a new function for every manipulation of the data required.
Answer: I believe that there is more elegant solution, but i came to this:
def foo(data, boundaries):
    zipped_bounds = list(zip(*boundaries))
    output = []
    for item in data:
        for index, bound in enumerate(zipped_bounds):
            if not (bound[0] <= item[index] <= bound[1]):
                break
        else:
            output.append(item)
    return output

data = [[1, 2], [3, 4], [5, 6], [1, 8]]
boundaries = [[2, 1], [8, 5]]
foo(data, boundaries)

Output:
[[3, 4]]

And i know that there is not checking and raising exceptions if the sizes of arrays won't match each concrete size. I leave it OP to implement this.


FirebaseMessagingService is not working in background using one plus 3 android oreo 8.0

Question: Firebase onMessageReceived never called when app is not running and removed from recent apps list.
I'm working with Firebase and sending data payload notifications to my app from my server, i have tried to use JobScheduler to start MyFirebaseMessagingService every 1 minute in case the system is killing my service but this approach didn't work for me on One Plus 3.
I know that android add limitation on background services to optimize battery usage, but does this limitation affect on FCM service?
here is my message string:
{
"notification": {
    "title": "Hello",
    "body": "Notification",
    "badge": 1,
    "icon": "app_icon",
    "color": "#ffffff",
    "sound": "default",
    "clickAction": "home",
    "tag": "parent_ccid_6"
},
"message": {
    "priority": "high",
    "type": "daily_tips",
    "data": {
        "parent_ccid": "parent_ccid_6",
        "id": "2",
        "sound": "default"
    }
},

}
and here is my Service in manifest
 <service
        android:name=".util.FCM.MyFirebaseMessagingService"
        android:exported="false">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT" />
            <action android:name="android.intent.action.BOOT_COMPLETED" />
            <action android:name="com.google.android.c2dm.intent.RECEIVE" />
        </intent-filter>
    </service>

Answer: You must use Notification Channel for above Nougat
Sample
        int notifyID = 1;
        String CHANNEL_ID = "my_channel_01";
         // The id of the channel.
        CharSequence name = "channel ram";
         // The user-visible name of the channel.
        String groupId = "Building654651";
        CharSequence groupName = "BuilgingHub123";
        int importance = 0;
            importance = NotificationManager.IMPORTANCE_HIGH;
            NotificationChannel mChannel = new NotificationChannel(CHANNEL_ID, name, importance);
 Notification notification = new Notification.Builder(this)
                .setContentTitle(getString(R.string.app_name))
                .setContentText(messageBody)
                .setSmallIcon(R.drawable.ic_notifi).setColor(Color.parseColor("#FFA23B"))
                .setChannelId(CHANNEL_ID)
                .build();
  NotificationManager mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        mNotificationManager.createNotificationChannelGroup(new NotificationChannelGroup(groupId, groupName));
        mNotificationManager.createNotificationChannel(mChannel);
            mNotificationManager.notify(notifyID, notification);

Comment: Thank you M.Ram, I have already implement Channels for android > N, and it works fine when application in foreground or in recent apps list, but when close the app on onMessageReceived is never triggered.
Answer: When the application is in background onMessageReceived will never be called as per the android document.
Link:- https://firebase.google.com/docs/cloud-messaging/android/receive
When app is in background the notification is delivered to the device's system tray and default intent of your application (i.e Launcher Screen) will be called and you have to handle that notifcation on this screen.
Other solution is that you can remove the "notification" keyword from payload then you will able to receive the notification when your application is in background and onMessageReceived will get called.
Comment: Thank you Kishna, I have tried this solution using
https://fcm.googleapis.com/fcm/send
and set Post body as:
 `{
  "to" : "ewHHsQa3R6g:APA91bF....",
      "priority": "high",
      "android_channel_id":"DEFAULT_CHANNEL",

  "data": {
   "type": "daily_tips",
      "daily_tips_type": "interest",
   "parent_ccid": "parent_ccid_6",
   "ccid": "ccid_6",
   "id": "2",
         "cid":1,
   "sound": "default"
  }
 }`

but it didn't work too.
Comment: Can you post your server notification code and android code
Comment: I don't have access to server code but the message data will come as the posted question above, and it works fine with other devices even though they have android 8 and 8.1, except my one plus and Huawei.
and if i go to settings and select "Don't optimize" from Battery optimization settings it works fine in background
Answer: I didn't find any solution to solve this issue by code.
The only way to revive notification is to go to settings and select "Don't optimize" from Battery optimization settings, and it works fine in background, otherwise notification handler will not be triggered.
I faced this issue with all installed applications on One plus 3.
Answer: Try android:exported="true". in your android manifest file.
Comment: Could you please expand upon your answer with a little more detail. Adding context to your answers make them more valuable.
Comment: Note that there is already an accepted answer to this question. Please [edit] your answer to ensure that it improves upon other answers already present in this question.


What is the probability that the maximum number of shots fired successively from a type A gun is $2$?

Question: A gun salute always takes place at the funeral of a military leader who has died in a certain country.
(The $21$ gun salute where $21$ rounds are fired - is the most common for the most senior military leaders and the number of rounds progressively gets smaller as the rank gets lower.)
Lance, who was an air marshal has died and his funeral is there tomorrow. At his funeral, a $14$ gun salute will be held (a total of $14$ rounds will be fired in succession) comprising of $5$ rounds from a Type A gun, $3$ rounds from a Type B gun and the rest from a Type C gun. => $6$ right?
If the guns are fired randomly, what is the probability that the maximum number of shots fired successively from a type A gun is $2$?
Answer: $\frac{121968}{168168} = \frac{66}{91} =0.7253$
I was trying to take the approach of taking the total number of possible ways ($\frac{14!}{{5!}{3!}{6!}} = 168168$) and subtracting the ways where you take all the type A out and then place them back in but in between others in ways that there are more than 2 successive fires.
I got confused because I don't know how to account for the repeated type A after putting them back in in such a fashion.
I had:
$3$ A's in succession and $2$ A's in succession
$3$ A's in succession and $2$ A's not in succession
$4$ A's in succession and $1$ A
$5$ A's in succession
I tried to approach it like this:
I'm just going to show you what I did to attempt to get the numerator of the answer ($121968$) before dividing it by $168168$ (obviously to get the probability).
$168168 - \frac{{9!}{10\choose2}{3!}{2!}{2!}}{5!3!6!} - \frac{{9!}{10\choose3}{3!}{3!}}{5!3!6!} - \frac{{9!}{10\choose2}{4!}{2!}}{5!3!6!} - \frac{{9!}{10\choose1}{5!}}{5!3!6!}$
$= 168168 - 756 - 3024 - 1512 - 840 = 162036$
What am I doing wrong? How do they get $121968$
Answer: Your expression is mostly right. Take the case "3 A's in succession and 2 A's in succession". We have 2 subcases, either the AAA comes first or the AA comes first. These are equivalent.
Let X denote a B or a C (whether it's B or C, we decide at the end). We have 9 X's to place in 3 slots as shown:
<code> AAA AA
^   ^  ^
</code>
Except we must place an X in the middle slot. So we have 8 X's and 2 blocks of A's to arrange; one possible arrangement is <code>(X AAA(X) X X X AA X X X X)</code>. Total # of ways to do this is 10C2.
Finally we choose B's and C's among the X's. There are 9C3 ways to do this. So the total # of ways for this case is $2\binom{10}{2}\binom{9}{3}$. The other cases are similar.


Como obter o caminho atual de um script .sh?

Question: No sistemas baseados em Linux sempre que necessito uso o seguinte comando:
#!/bin/bash

BASEDIR=$(dirname "$0")

echo $BASEDIR

Todavia li em diferentes locais que $(dirname "$0") não é suportado pelos sistemas Mac OS X e sistemas baseados em BSD (aparentemente ambos baseados em Unix).
Via algumas alternativas, mas todas sempre tem uma critica, ou alguma menção falando que falha em algo.
O que eu preciso é saber se existe alguma maneira de pegar o diretório do script atual de maneira cross-platfom (unix-like)?
Outra coisa, eu gostaria de saber como obter tanto o caminho do diretório real quanto o caminho de um link simbólico.

Nota: Não precisa ser com bash
Comment: Ah, tá, kkkkk, Vacilei na resposta
Comment: o `pwd` não serve pro teu caso?
http://devblog.drall.com.br/obter-o-caminho-real-de-um-link-simbolico/
Comment: @PabloVargas obrigado, sabaria me dizer se isto é cross? Todavia assim que instalar o BSD e o linux irei testar também. Obrigado por enquanto.
Comment: Não sei lhe dizer, sempre usei esses comandos só no Linux
Comment: `pwd` é padrão POSIX, isso significa que é altamente compatível não apenas nos sistemas operacionais baseados em UNIX (Linux, Android, iOS, OpenBSD, macOS, HP-UX, Solaris, ...), como também no Windows 10 através do Bash ou nas versões anteriores instalando o SUA(oficial da MS)/Cygwin
Answer: Utilizando a linha de comando no Linux, é possível utilizando o comando shell pwd para obter o caminho(path) do diretório alvo.
No entanto, quando se executa este comando dentro de um diretório que é um link simbólico, este comando normalmente retornará o caminho para o link simbólico e não o diretório real apontado. Este comportamento está correto e é o esperado. No entanto, por vezes, precisamos obter o diretório real apontado. Para isto, basta:
$ pwd -P

(mostra o path do diretório real apontado pelo link simbólico quando dentro do diretório)
$ pwd

(mostra o path do link simbólico quando dentro do diretório)
Comment: +1, Um complemento legal seria colocar o BASEDIR=$(pwd) na resposta, pra usuários que não conhecem bem o shell saberem como capturar o valor (e mencionar sobre a necessidade ou não de aspas em volta do ="$(pwd)" )
Comment: Ótimo pablo, vou tentar instalar o freeBSD e o Debian em algumas maquinas virtuais e testar, obrigado por enquanto :D
Comment: @Bacco é que a minha resposta foi mais para apresentar o comando `pwd`, não sou muito conhecedor de bash, mas fique a vontade para por mais uma resposta com suas sugestões.
Answer: É estranho que o dirname não esteja disponível no BSD e no MacOS, dado que é um simples programa em C, cujo código está em diversos repositórios.
Por exemplo: aqui OpenSource Apple
e aqui OpenBSD. Basta compilar e usar.
De qualquer forma, talvez seja útil uma solução baseado no caminho relativo à posição de chamada, dado que permite localizar "sempre" o script:
Eis uma proposta para experimentar a ver se dá jeito:
script: onde_estou.sh
#!/bin/bash

DIR_RELATIVO="${0%/*}"

DIR_CHAMADA="${PWD}"

SCRIPT_PATH=$DIR_CHAMADA/$DIR_RELATIVO

echo "Desde a posição de chamada:"
echo "--> $DIR_RELATIVO"

echo "Posição de chamada:"
echo "-->$DIR_CHAMADA"

echo "Junção das duas:"
echo "--> $SCRIPT_PATH"

echo " Exemplo de aplicação"
echo "Listar o conteúdo do diretório onde está o script"
ls $SCRIPT_PATH

O script pode ser chamado de vários locais diferentes e dá sempre um caminho até lá. Infelizmente faz algumas curvas :).


How to display currency in Indian numbering format

Question: I am trying to generate the numbers in Indian currency format
example the output value like 550500 should  display as 5,50,500.
Below is my script.
Live Demo
   $("#rTpe1").click(function(e){
      $("#rFor1").val(this.value * $("#PerHourRate1").val());
   });

Answer: You can retrieve 5,50,500 by using toLocaleString(). In order to use this, please modify 2 parts as follows.
1. HTML
From :
<input  name="" type="number" placeholder="" class="form-control input-md" value="0" id="rFor1" readonly>

To :
<input  name="" type="string" placeholder="" class="form-control input-md" value="0" id="rFor1" readonly>

2. Javascript
From :
$("#rTpe1").click(function(e){
  $("#rFor1").val(this.value * $("#PerHourRate1").val());
});

To :
$("#rTpe1").click(function(e){
  $("#rFor1").val((this.value * $("#PerHourRate1").val()).toLocaleString());
});

If toLocaleString() cannot be used, please use the following script for Javascript.
$("#rTpe1").click(function(e){
  var ar = (this.value * $("#PerHourRate1").val()).toString().split('.');
  $("#rFor1").val(ar[0].replace(/(\d)(?=(\d{3})+(?!\d))/g, '$1,') + (ar[1] ? "." + ar[1] : ""));
});

Answer: In order to generate numbers in Indian currency format,  you can use toLocaleString('en-IN'). You need to change the input type of rFor1 to text.
Also, if it helps you can use keyup event instead of click.
<input  name="" type="text" placeholder="" class="form-control input-md"value="0" id="rFor1" readonly>

$("#rTpe1").keyup(function(e){
   $("#rFor1").val((this.value * $("#PerHourRate1").val()).toLocaleString('en-IN'));
});

Comment: keyup?  How does that assist when other object values are used?  It might not even by a focus-able/key-able element.
Comment: Thanks Ritz
Do I need to use toLocaleString('en-IN') to genrate SUM
Example Now i am using ....$("#rFor3").val( Number($("#rFor1").val()) + Number($("#rFor2").val())
Comment: Any luck on this .....

$("#rTpe1").click(function(e){
   $("#rFor1").val((this.value * $("#PerHourRate1").val()).toLocaleString('en-IN'));
  $("#rFor3").val.toLocaleString('en-IN')( Number($("#rFor1").val().replace(/,/g , '')) + Number($("#rFor2").val().replace(/,/g , '')))
});


Issue with customizing kernel cmdline option in Ubuntu 20.04.3

Question: Im trying to add rootdelay=60 option in grub cmdline options by editing file /etc/default/grub as
GRUB_CMDLINE_LINUX_DEFAULT="rootdelay=300" and also ran
update-grub
update-initramfs -u
however i do not observe any delay after reboot and the root filesystem mounts right away
i can see that the rootdelay=300 is present in cat /proc/cmdline ,is there any thing missing here ?
Answer: rootdelay only waits until the rootfs device is available.
The kernel documentation is not very concise:
https://www.kernel.org/doc/html/v4.14/admin-guide/kernel-parameters.html
however, there is an answer on the Unix stackexchange that provides additional explanation:
https://unix.stackexchange.com/questions/67199/whats-the-point-of-rootwait-rootdelay


ScenicView Javafx java.lang.UnsatisfiedLinkError

Question: I am trying to run ScenicView as a standalong java application. I am running
java -jar ScenicView.jar

But I am getting the following output
java.lang.UnsatisfiedLinkError: no attach in java.library.path
at java.lang.ClassLoader.loadLibrary(Unknown Source)
at java.lang.Runtime.loadLibrary0(Unknown Source)
at java.lang.System.loadLibrary(Unknown Source)
at org.scenicview.model.attach.AttachHandlerFactory.patchAttachLibrary(AttachHandlerFactory.java:202)
at org.scenicview.model.attach.AttachHandlerFactory.initAttachAPI(AttachHandlerFactory.java:138)
at org.scenicview.ScenicView.start(ScenicView.java:167)
at com.sun.javafx.application.LauncherImpl.lambda$launchApplication1$161(LauncherImpl.java:863)
at com.sun.javafx.application.PlatformImpl.lambda$runAndWait$174(PlatformImpl.java:326)
at com.sun.javafx.application.PlatformImpl.lambda$null$172(PlatformImpl.java:295)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl.lambda$runLater$173(PlatformImpl.java:294)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:95)
at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
at com.sun.glass.ui.gtk.GtkApplication.lambda$null$48(GtkApplication.java:139)
at java.lang.Thread.run(Unknown Source)
Platform running
Launching ScenicView v8.7.0
Startup done
Creating server
Server done
Number of running Java applications found: 4
Exception in thread "org.scenicview.model.update.RemoteVMsUpdateStrategy" java.lang.UnsatisfiedLinkError: no attach in java.library.path
at java.lang.ClassLoader.loadLibrary(Unknown Source)
at java.lang.Runtime.loadLibrary0(Unknown Source)
at java.lang.System.loadLibrary(Unknown Source)
at sun.tools.attach.LinuxVirtualMachine.<clinit>(LinuxVirtualMachine.java:342)
at sun.tools.attach.LinuxAttachProvider.attachVirtualMachine(LinuxAttachProvider.java:78)
at com.sun.tools.attach.VirtualMachine.attach(VirtualMachine.java:250)
at org.fxconnector.remote.RemoteConnectorImpl.getRunningJavaFXApplications(RemoteConnectorImpl.java:368)
at org.fxconnector.remote.RemoteConnectorImpl.connect(RemoteConnectorImpl.java:251)
at org.scenicview.model.update.RemoteVMsUpdateStrategy.getActiveApps(RemoteVMsUpdateStrategy.java:57)
at org.scenicview.model.update.RemoteVMsUpdateStrategy.work(RemoteVMsUpdateStrategy.java:77)
at org.fxconnector.helper.WorkerThread.run(WorkerThread.java:43)

ScenicView opens but never finds my JavaFX program running.
Comment: What does happen when you launch ScenicView without any other Java programs running ? (it seems with your stacktrace there are 4 ones running `Number of running Java applications found: 4` ).
Comment: What java version? what ScenicView version? On their site they have versions for java 8 and java 9.
Comment: Im Running java 8, and I have the java 8 Scenic View Version.

When I run with no java process (Ensured by killing everything returned by ps aux | grep java) it has the same two errors except it is only 1 Java application found. Which I have to assume is Scenic View itself.
Comment: Are you using the JDK's distribution of the `java` executable? I just tried launching Scenic View with the public JRE's distribution (`...\jre1.8.0_172\bin\java`) and got an `UnsatisfiedLinkError`. However, if I use the JDK's distribution (`...\jdk1.8.0_172\bin\java`) Scenic View launches successfully. Scenic View must require libraries that are only shipped with the JDK.
Comment: My man. Yea i manually ran the jdk java and it launched no issue. Ok Ill post that as the answer and close it out.

Thank you.
Answer: Using the JRE version of java it caused errors. Switching to the JDK version and it worked as expected.


Are blocks a OK way to model a theme?

Question: I am trying to build a new theme. Are blocks a OK way to model a theme? Some sites seem to recommend them, others say that they should be avoided.
Comment: The main content section is a block...I'd say yes, that's pretty much expected
Answer: Blocks are an important part in Drupal, but you don't model a theme with them.
Blocks are implemented from modules, using hook_block_info() and hook_block_view() (together other hooks); what themes implement are regions where those blocks are rendered. A theme cannot decide not to implement regions, since there are some regions Drupal requires from themes.
Eventually, a theme can alter how a block is rendered, but themes are not modelled around blocks.
Comment: I agree. There is a trade-off: the more block-aware your theme the less versatile it becomes. Blocks should be used to populate themes.

Are blocks a OK way to model a theme?


Does MassTransit support detached Entity Framework graphs?

Question: The system I'm developing uses MassTransit to communicate between modules.  I've generated numerous messages and it was working great.  But I'm running into an issue with messages that contain Entity Framework 6 generated types.  Flat model objects publish fine, but when I try to send a detached object graph it fails.
I only get this generic error:
<code>[Error] - Send Fault: rabbitmq://127.0.0.1:5672/...
[Debug] - The model usage threw an exception
[Debug] - The connection usage threw an exception
[Debug] - The connection threw an exception
</code>
Are EF6 objects supported with MassTransit/RabbitMQ?  I've not been able to find documentation either way.
Not sure where to go from here...
Answer: It's probably not what you want to hear, but messages shouldn't contain your persistence types - even if it works, it's short term gain/long term loss. Conceptually messages represent delta/change in state, while persistence reflects applied change - final state, possibly at certain point in time. If you work against this, sooner or later you'll have a big problem, like having to reconcile multiple/concurrent updates on a whole record/hierarchy.
Comment: In general, I agree.  But in this case I have a couple of cases where potentially all of the persisted data needs to be passed along.


Can you construct a simple bipartite graph G, that has $\kappa (G) < \lambda(G) < \delta(G)$?

Question: Is it possible to construct a simple bipartite graph G, that has $\kappa (G) < \lambda(G) < \delta(G)$ ?
Where $\kappa (G) $ is vertex connectivity, $\lambda (G)$ is edge connectivity.
I can find examples where $ \kappa (G) \le \lambda (G) \le \delta(G)$ holds, like $K_1,_2$
But I am struggling to find a example where the strict inequality holds but it doesn't feel impossible
Answer: HINT: Let $G_1$ and $G_2$ be disjoint copies of $K_{3,3}$. Let $v$ be a new vertex not in $G_1$ or $G_2$. Connect $v$ to two vertices of $G_1$ and to two vertices of $G_2$ to form $G$.
Comment: @K.Hal: Make sure that both vertices in $G_1$ to which you connect it are in the same part of $G_1$, and both vertices of $G_2$ to which you connect it are in the same part of $G_2$. Those parts of $G_1$ and $G_2$ will be one part of $G$.
Comment: excuse me sir, i know this question is asked 3 months ago. but would you mind proving that this method always works? for example, if $\kappa(G)=3$,$\kappa'(G)=4$ and $\delta(G)=5$ ...


Modelo, relacionamento com DataAnnotations

Question: Se tenho uma entidade Clientes
public class Cliente
{
    public int ClienteId { get; set; }
    public string Email { get; set; }
    public string Nome { get; set; }
}

Se eu crio uma entidade Boleto
        public class Boleto
        {
            public int BoletoId { get; set; }
            public string Email { get; set; }
            public int IDC { get; set; }
public virtual Cliente Cliente { get; set; }
       }

Se eu trocar o IDC por ClienteId, ele entende que essa é a relação com o Cliente, porém como fazer com DataAnnotation para que ali seja a relação com o Cliente?
no caso 1-to-1
OBS: Sei que devo padronizar os nomes, para não virar uma salada de nomes, mas em um local queria utilizar outro nome e ai aconteceu o problema.
Answer: Basta especificar qual a chave do relacionamento seguindo o exemplo abaixo;
public class Boleto
{
    public int BoletoId { get; set; }
    public string Email { get; set; }
    public int IDC { get; set; }
    [ForeignKey("IDC")]
    public virtual Cliente Cliente { get; set; }
}

Comment: especifico no public virtual cliente cliente? show..entendi..obrigado
Answer: Apenas lembrando que você pode indicar o mapeamento na própria FireingnKey, desta forma:
public class Boleto
{
    public int BoletoId { get; set; }
    public string Email { get; set; }
    [ForeignKey("Cliente")]
    public int IDC { get; set; }

    public virtual Cliente Cliente { get; set; }
}

Ou usar Fluent API.


C# convert System.Func to System/Func

Question: I've googled but couldn't find satisfactory answers. I'm basically trying to get this code to work:
public List<WordEntry> WordDataBase = new List<WordEntry>();
public List<CharacterEntry> CharacterDataBase = new List<CharacterEntry>();

public List<Entry> SelectWhere<T>(System.Func<T, bool> predicate) where T : Entry
{
    if (typeof(T) == typeof(WordEntry))
        return WordDataBase.Where(predicate);
    else if (typeof(T) == typeof(CharacterEntry))
        return CharacterDataBase.Where(predicate);
    else
        return null;
}

In this sample, both WordEntry and CharacterEntry are derived from Entry. I get the compiler errors:
Error   CS1503  Argument 2: cannot convert from 'System.Func<T, bool>' to 'System.Func<WordEntry, int, bool>'

and
Error   CS1503  Argument 2: cannot convert from 'System.Func<T, bool>' to 'System.Func<CharacterEntry, int, bool>'

Hopefully you can help me with this. Thanks in advance
Comment: I think that this is slightly pointless as a method. If you have 2 types, then have two methods.
Comment: If you're doing type checking on a generic type then you've almost always made a poor design choice.
Comment: I would say it has something to do with type variance - the compiler won't allow implicit cast to a parent type.
Comment: Okay thanks for answering everybody. But I see a lot of people replying to the specific function I wrote. However, this function is just a basic version of what I'm trying to achieve. In the final version I want to setup a much more complex and dynamic system based on the casting of the func. So everybody can ignore the function with the if/else statement and only utilizing two types. Thank you
Answer: Basically, you just need to cast - the language rules don't allow the compiler to take the if statement into account when it thinks about the types involved. Note that you also need to call ToList<Entry>(), specifying the type argument to avoid getting a List<WordEntry> or List<CharacterEntry>:
public List<Entry> SelectWhere<T>(Func<T, bool> predicate) where T : Entry
{
    if (typeof(T) == typeof(WordEntry))
        return WordDataBase
            .Where((Func<WordEntry, bool>) predicate)
            .ToList<Entry>();
    else if (typeof(T) == typeof(CharacterEntry))
        return CharacterDataBase
            .Where((Func<CharacterEntry, bool>) predicate)
            .ToList<Entry>();
    else
        return null;
}

I'd suggest that rather than making this generic though, you might want to just have two different methods instead. It doesn't feel like it's really a generic method, given that it only works with two very specific types.
Comment: Thank you for answering. However I tried casting the func before. But the part:
    (Func)predicate
Gives the error:
    Error CS0030 Cannot convert type 'System.Func' to 'System.Func'
Comment: @user1370286: Ah, you may need a cast to `object` first. Will add that in.
Comment: @user1370286: Actually, no, my code compiles fine for me. It really should be fine - will create a gist to show...
Comment: @user1370286: https://gist.github.com/jskeet/1c63090d847a97cc757352807cfc0a50 compiles with no errors.
Answer: Your method SelectWhere does different things based on the type of argument - so why not just use overload methods
public List<WordEntry> SelectWhere(Func<WordEntry, bool> predicate)
{
    return WordDataBase.Where(predicate);
}

public List<CharacterEntry> SelectWhere(Func<CharacterEntry, bool> predicate)
{
    return CharacterDataBase.Where(predicate);
}

Then you can use those method without casting and "horrible" if...else statements
Func<WordEntry, bool> isValid = word => word.SomeProperty > 0;
var filteredWords = SelectWhere(isValid); // WordDataBase will be used

Func<CharacterEntry, bool> IsValid = character => character.SomeProperty != null;
var filteredCharacters = SelectWhere(IsValid); //CharacterDataBase will be used

Answer: From the errors you have shown i think your predicate has wrong declaration.
The where clause on both of your Database objects expects Func<T, int, bool>, note the second argument which is int, so changing your extension method like this should be progress in the right direction
public List<Entry> SelectWhere<T>(Func<T, int, bool> predicate) where T : Entry

NOTE: You have declared generic method in which your code depends on the generic type, this makes to code somehow not so generic, check @Fabio answer i think he has point for creating the separate extension methods.

C# convert System.Func to System/Func


Emptying Trash with Dovecot IMAP

Question: On a Debian Squeeze system I run an IMAP server using Dovecot with messages being stored in the Maildir format.  The server is accessed by various clients, including Thunderbird, Evolution and RoundCube.
When a user deletes a message it is moved to the Trash folder.  (I am unsure if all clients also mark the messages as deleted when moving them.) However, beyond that no action is taken.  Hence I am forced to periodically remind all users to explicitly empty their Trash every few months.
Does Dovecot provide an easy means of automatically deleting Trashed messages older than n days?  I've seen mention to an expunge cron-job but it seems to delete all messages older than a certain number of days as opposed to just those in Trash.
Answer: The Plugin that @hostemaster mentioned is not really needed if you don't deal with thousand of users.
Just create an easy script like this:
<code>#!/bin/bash
#
DOVEADM="/usr/local/dovecot/bin/doveadm";

$DOVEADM expunge -A mailbox Trash savedbefore 90d
$DOVEADM expunge -A mailbox Junk  savedbefore 60d
</code>
And run it daily as an cronjob.
This will remove all messages from Trash that are older than 90 days, or from Junk if older than 60 days.
Comment: Is that verbatim? "mailbox" isn't a placeholder or anything? And that will go through every user's folders?
Comment: @DevOpsSauce https://doc.dovecot.org/3.0/man/doveadm-expunge.1/
Answer: Expire plugin delete mails from specified mailboxes after a designated number of days.
http://wiki2.dovecot.org/Plugins/Expire
Comment: That plugin just optimizes the existing process when you have thousands of users. It does not itself expunge old messages.

Emptying Trash with Dovecot IMAP


Call the hardware back button programmatically?

Question: I know that one can overwrite the Back Button functionality in Android, but I was wondering if there was a method or anything I could call that would functionally do the same thing as pressing the hardware button.
Answer: You can send the back button press to the system like this
this.dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));

Or you can override the back button press and call
finish();

on your Activity. That basically does the same thing as the generic back button.
Comment: This did not work for me. But found this workaround that others might find useful too:

dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_DOWN, KeyEvent.KEYCODE_BACK));
dispatchKeyEvent(new KeyEvent(KeyEvent.ACTION_UP, KeyEvent.KEYCODE_BACK));

http://stackoverflow.com/a/14891899/555856
Comment: Try using KeyEvent.ACTION_DOWN and KeyEvent.KEYCODE_BACK :)
Comment: Doesn't work in my code...tells me to change it to ACTION_DOWN, and KEYCODE_BACK don't exist, what would I need to import for them to be found?
Comment: Thanks @jimmithy I updated the solution. Hopefully that was the correct answer you were looking for :)
Comment: This isn't entirely correct. You are literally dispatching a key event when the button is pressed down and then up. Did you try removing just the ACTION_DOWN event and see if it still works?
Answer: Just call this.onBackPressed(); in Activity.
Comment: This one is the best answer, as simply calling finish doesn't trigger onBackPressed like the real back button does.  If the activity is doing extra stuff there it'll be missed.
Comment: This is a great answer.
Comment: But like if there is any dialog over activity then it will close activity, and real button doesn't do that.
Comment: @NehaK In that case, you can override onBackPressed() If the dialog is showing then dismiss it first.
Answer: If you want just "press" hardware button,
create service extended from AccessibilityService:
class ExampleAccessService:AccessibilityService() {
    override fun onInterrupt() {
    }

    override fun onAccessibilityEvent(event: AccessibilityEvent?) {
    }

    fun doAction(){
        performGlobalAction(GLOBAL_ACTION_RECENTS)
//        performGlobalAction(GLOBAL_ACTION_BACK)
//        performGlobalAction(GLOBAL_ACTION_HOME)
//        performGlobalAction(GLOBAL_ACTION_NOTIFICATIONS)
//        performGlobalAction(GLOBAL_ACTION_POWER_DIALOG)
//        performGlobalAction(GLOBAL_ACTION_QUICK_SETTINGS)
//        performGlobalAction(GLOBAL_ACTION_TOGGLE_SPLIT_SCREEN)
    }
}

Call doAction() where you want action
Add to Manifest:
<application
...
    <service
        android:name=".ExampleAccessService"
        android:permission="android.permission.BIND_ACCESSIBILITY_SERVICE"
        android:label="Name of servise" // it will be viewed in Settings->Accessibility->Services
        android:enabled="true"
        android:exported="false" >
        <intent-filter>
            <action android:name="android.accessibilityservice.AccessibilityService"/>
        </intent-filter>
        <meta-data
            android:name="android.accessibilityservice"
            android:resource="@xml/accessibility_service_config"/>
    </service>
...
</application>

accessibility_service_config.xml:
<?xml version="1.0" encoding="utf-8"?>
<accessibility-service xmlns:android="http://schemas.android.com/apk/res/android"
    android:accessibilityEventTypes="typeAllMask"
    android:accessibilityFeedbackType="feedbackAllMask"
    android:accessibilityFlags="flagDefault"
    android:canRetrieveWindowContent="false"
    android:description="your description"
    android:notificationTimeout="100"
    android:packageNames="your app package, ex: ex: com.example.android"
    android:settingsActivity="your settings activity ex: com.example.android.MainActivity" />

for more info look at https://developer.android.com/guide/topics/ui/accessibility/service


Why is my website often put in maintenance mode by itself?

Question: My website in maintenance mode by itself. But other sites is work well, only this site has this problem. Some people encountered this kind of situation? Thank for help..
Answer: Usually, a Drupal site enters in maintenance mode by itself because is having problems to access to its database or when is set on that mode through the option located at "admin/config/development/maintenance".
If you are not able to log in on the site, that could indicate Db problems.
Check...:

at "admin/config/development/maintenance" is checked the option "Put site into maintenance mode". Or with drush: drush vget maintenance_mode
the settings.php if the Drupal database parameters are ok.
the status of the Drupal database, (if the user:password are correct, if the database server is online).
the error logs (MySQL, PHP, Drupal).
Comment: D-flat problems? Sorry, music geek joke. ;P
Answer: The problem is with the Backup and Migrate module. For some reason, sometimes something fails with the backup every once in a while.  The problem is the site is put into maintenance mode, then the issue happens and then the site is not taken out of maintenance mode.
Solution: Go to the profile section in Backup and Migrate module.  Click into your profile and in the 'Advance Settings' section "uncheck" the put site into maintenance mode option.  Done.


JQUERY - Load em formulário com editor

Question: É possível ao jogar um texto todo desalinhado e cheio de espaços a esquerda, em cima e em baixo. Deixar ele todo alinhado e sem espaços?
Por exemplo:

       texto
texto
texto texto
         texto

e sair assim, tudo sem espaços e alinhado a esquerda:

texto
texto
texto texto
texto

Isso já automático ao colar no editor (textarea).
Comment: Man vc consegue remover os espaços em branco com a função replace(' ', '') do javascript.. e pode adicionar classes CSS para formatar o conteúdo.. seria legal postar seu código, oque vc fez até agora para que possa te ajudar melhor.
Answer: Utilizando jQuery, pode ser assim:

$("textarea#txt1").on('input',function(){
  var txt = $(this).val();
  var txt_novo = txt.replace(/(^|[\n\r])([\t\s])+/g, "$1");
  $(this).val(txt_novo);
});

<textarea id="txt1" style="width:350px; height: 250px;"></textarea>
Comment: Era isso cara, que beleza. Valeuuuu
Comment: uma pergunta de leigo, já uso esse código no header do site
Comment: Não consigo fazer funcionar local. Não sei onde posto o código aqui, ainda não entendi o stackoverflow
Comment: to fazendo tudo igualzinho.
Comment: algumas coisas aconteceram. Só consegui colocando a função dentro do body, no header não vai. E uso fckeditor, ai complicou tudo. No textarea ta funcionando.
Comment: Legal! Você pode tentar colocar dentro de um $( document ).ready(function() {...}); no header pra ele bindar o input depois que a página carregou! Quanto ao editor, ai vc vai ter que verificar se ele não tem algum pré-processador de copiar e colar!
Comment: coloquei antes do fechmento do body, estranho, só funciona assim. O fckeditor vai ser foda, mas valeu.
Comment: Valeu @Rod! Se foi útil, marca a resposta ai como solução! Bons estudos!
Comment: como faz isso? rs

JQUERY - Load em formulário com editor


Why use static blocks over initializing instance variables directly?

Question: Why would I use a static block:
static {
   B = 10;
}

over:
Integer B = 10;

What is the advantages/disadvantages of one over the other?
Comment: This is less of an answer and more of a warning...  static initializers are run in the synthetic clinit() {class init} method, which is *implicitly synchronized*.  Thus, you must be careful with any code you call inside a static initializer, as multithreaded applications could incur deadlock from loading class files!

If you need to call out to other classes you don't control or understand, you may want to use a Provider abstraction to delay the initialization until after the class is loaded...
Answer: The static block allows you to write more complex initialization logic for the attribute, whereas the one-line initialization limits you to a single expression.
Be aware that initialization blocks exist for both instance and static attributes, for example this one initializes an instance attribute at instantiation time:
private int a;
{ a = 10; }

Whereas this one initializes a static attribute at class loading time:
private static int b;
static { b = 10; }

The initialization procedure is explained in detail in here, as part of the JVM specification.
Answer: You should only use a static initializer block, when it is necessary. For example, sometimes you need to do several steps to calculate the final value of the field. In this case you have two opportunities: write a method that calculates the value and declare your field as static final Integer B = calculateB(), or use an initializer block:
static final Integer B;
static {
  int temp = ...;
  ...
  B = temp;
}

In this case I prefer the static block, because a method might be confusing (other developers might try to call it, although it is only meant to be called once during initialization).
The same applies for instance fields as well, although normally one would avoid the unusual initialization block and simply write the initialization logic for fields into the constructor (which is of course not possible for static fields).
Answer: Static initialization happens when the class is loaded.
E.g. it would be a proper place to initialize member variables that could otherwise need synchronization due to access by multiple threads.
The second case would happen if you called the constructor explicitely.
The usage is different.
E.g. you would prefer the second case for lazy loading of something (if you put it in static initializers it will always load and perhaps you would not want that-prefer to lazy load it)
Comment: No, absolutely not. For example, calling a static method on the class will cause it to be loaded, but will not run any constructors.
Comment: Sorry im not sure I understand the difference? Surely loading a class is the same as calling its constructor?
Answer: First your Integer B appears to be a non static member variable and can not be accessed from a static block. So you either meant to write
//Initialize static field
static {
   B = 10;
}
static Integer B = 10;

or
//Initialize member field
{
   B = 10;
}
Integer B = 10;

In both cases you can use it to initialize B with a value that could cause an exception or do something more complex without writing a special method for init.
{
   try{
      B = thisWillThrowAFileNotFound();
   }catch(FileNotFoundException){
      B = 10;//Set default
   }

}

Answer: Actually, if you have
private static Integer B = 10;

The compiler will translate to, basically:
private static Integer B;
static {
    B = 10;
}

The thing with static blocks is that you can use the whole language and not just expressions to do initialisation. Imagine you need an array with a bunch of multiples of 7. You could do:
private static Integer[] array;
static {
    array = new Integer[1000];
    for (int i = 0; i < 1000; i++) {
        array[i] = 7 * i;
    }
}

Anyway, you could also do it this way:
private static Integer[] array = initArray();
private static Integer[] initArray() {
    Integer[] result = new Integer[1000];
    for (int i = 0; i < 1000; i++) {
        result[i] = 7 * i;
    }
    return result;
}


How can I efficiently compare contiguous and sequential rows using C# in Excel?

Question: I am developing a VSTO add-in for Excel in C# that needs to compare potentially large datasets (100 columns x ~10000 or more rows).  It is being done in Excel so an end user can view some pictorial representation of the provided data on a row-by-row basis.  This application must be done in Excel despite the potential pitfalls of using these large datasets.
Regardless, my question pertains to an efficient way to compare contiguous and sequential rows.  My goal is to compare one row to the row directly after it; if there is a change of any of the elements between row1 and row2, this counts as an "event" and row2 output into a separate sheet.  I'm sure you can see that for row-wise comparison of rows when the count is around 10000, this takes a long time (in practice, this is about 150ms-200ms per row for the current code).
Currently, I have used the SequenceEqual() method to compare two lists of strings as follows:
    private void FilterRawDataForEventReader(Excel.Application xlApp)
    {
        List<string> row1 = new List<string>();
        List<string> row2 = new List<string>();

        xlWsRaw = xlApp.Worksheets["Full Raw Data"];
        xlWsEventRaw = xlApp.Worksheets["Event Data"];
        Excel.Range xlRawRange = xlWsRaw.Range["A3"].Resize[xlWsRaw.UsedRange.Rows.Count-2, xlWsRaw.UsedRange.Columns.Count];
        var array = xlRawRange.Value;

        Excel.Range xlRange = (Excel.Range)xlWsEventRaw.Cells[xlWsEventRaw.UsedRange.Rows.Count, 1];
        int lastRow = xlRange.get_End(Excel.XlDirection.xlUp).Row;
        int newRow = lastRow + 2;

        for (int i = 1; i < xlWsRaw.UsedRange.Rows.Count - 2; i++)
        {
            row1.Clear();
            row2.Clear();

            for (int j = 1; j <= xlWsRaw.UsedRange.Columns.Count-1; j++)
            {
                row1.Add(array[i, j].ToString());
                row2.Add(array[i + 1, j].ToString());
            }
            if (!row1.SequenceEqual(row2))
            {
                row2.Add(array[i + 1, xlWsRaw.UsedRange.Columns.Count].ToString()); // Add timestamp to row2.
                for (int j = 0; j < row2.Count; j++)
                {
                    xlWsEventRaw.Cells[newRow, j + 1] = row2[j];
                }
                newRow++;
            }
        }
    }

During testing, I placed timers are various parts of this method to see how long certain operations take.  For 100 columns, the first loop which builds the string arrays for row1 and row2 takes around 100ms per iteration and the whole operation takes between 150ms-200ms when an "event" has been found.
My intuition is that building the two List<string> is the problem but I do not know how else to approach this kind of problem in my experience.  I should emphasize, the actual values of the data in the two List<string> don't matter; what matters is if the data are different at all.  In that way, I feel that I am approaching this problem incorrectly but don't know how to "re-approach" so to say.
I am wondering if, instead of building arrays of strings through iteration and comparing them with the SequenceEqual() method, anyone can suggest a faster way to compare contiguous and sequential rows?
Answer: In case this solution may be useful for someone else trying to use Excel in C# and do some comparisons:
This problem was largely an optimization exercise.  By eliminating the multiple loops and using Excel instead to generate the comparison lists:
    for (int i = 3; i < xlWsRaw.UsedRange.Rows.Count - 2; i++)
    {

        rng1 = (Excel.Range)xlWsRaw.Range[xlWsRaw.Cells[i, 1], xlWsRaw.Cells[i, xlWsRaw.UsedRange.Columns.Count - 1]];
        rng2 = (Excel.Range)xlWsRaw.Range[xlWsRaw.Cells[i+1, 1], xlWsRaw.Cells[i+1, xlWsRaw.UsedRange.Columns.Count - 1]];
        rng3 = (Excel.Range)xlWsEventRaw.Range[xlWsEventRaw.Cells[newRow, 1], xlWsEventRaw.Cells[newRow, xlWsRaw.UsedRange.Columns.Count - 1]];

        object[,] cellValues1 = (object[,])rng1.Value2;
        object[,] cellValues2 = (object[,])rng2.Value2;
        List<string> test1 = cellValues1.Cast<object>().ToList().ConvertAll(x => Convert.ToString(x));
        List<string> test2 = cellValues2.Cast<object>().ToList().ConvertAll(x => Convert.ToString(x));

        if (!test1.SequenceEqual(test2))
        {
            rng2.Copy(rng3);
            xlWsEventRaw.Cells[newRow, xlWsRaw.UsedRange.Columns.Count].Value = xlWsRaw.Cells[i + 1, xlWsRaw.UsedRange.Columns.Count].Value; // Outputs the timestamp of the event to the events worksheet.
            newRow++;
        }
    }

I believe this can be optimized further but in my case, the ranges contain multiple types including strings so I convert everything to List<string> for the purpose of comparison.  The SequenceEqual() method, however it works behind the scenes, is nearly instantaneous and reduces the time to compare 120 columns to around 3ms.


Laplace's method for integration

Question: I am trying to compute $$I(\lambda) = \int_{0}^1 \frac{x}{\sqrt{1+x^4}}e^{\lambda x}\mathrm{d}x $$ for large, real, positive $\lambda$. I'm attempting this with Laplace's method as suggested, however I fail to see how this would work considering $f(x) = x $ has no maximum on the interior of the interval $(0,1)$ and $f''(x) = 0$, which would be problematic in the formula for Laplace's method. Am I missing a small substitution trick here, or is the question poorly written?
Comment: The main contribution comes from $x \lesssim 1$. Change $x \mapsto 1 - x$.
Answer: $\newcommand{\bbx}[1]{\,\bbox[15px,border:1px groove navy]{\displaystyle{#1}}\,}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\on}[1]{\operatorname{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
\on{I}\pars{\lambda} & \equiv
\bbox[5px,#ffd]{\int_{0}^{1}
{x \over \root{1 + x^{4}}}\expo{\lambda x}\,\dd x}
\label{1}\tag{1}
\\[5mm] \stackrel{x\ \mapsto\ 1 - x}{=}\,\,\,&
\int_{0}^{1}
{1 - x \over \root{1 + \pars{1 - x}^{4}}}
\expo{\lambda\pars{1 - x}}\,\dd x
\\[5mm] = &\
\expo{\lambda}\int_{0}^{1}
\expo{-\lambda x}{1 - x \over
\root{1 + \pars{1 - x}^{4}}}\,\dd x
\\[5mm] \stackrel{\color{red}{\mrm{as}\ \lambda\ \to\ \infty}}{\sim}
\,\,\,&
\expo{\lambda}\int_{0}^{\infty}
\expo{-\lambda x}{1 - 0 \over
\root{1 + \pars{1 - 0}^{4}}}\,\dd x
\\[5mm] = &\
\bbx{{\root{2} \over 2}\,{\expo{\lambda} \over \lambda}}\label{2}\tag{2} \\ &
\end{align}
The $\ds{\color{darkblue}{blue}}$ one is the exact expression (\ref{1}) while the $\ds{\color{red}{red}}$ one is the asymptotic expression (\ref{2}):
Comment: I believe we can apply Watson's lemma here to get more terms. https://en.wikipedia.org/wiki/Watson%27s_lemma
Comment: @AlexandruIonut Yes. Of course. It can be improved. I just got the "leading term". Thanks.
Comment: Thanks! I split the final integral into 2 parts and used Watson's lemma on both and got the next term to be $-\frac{\sqrt{2}}{2}\frac{e^\lambda}{\lambda^{-3}}$

Laplace's method for integration


How do we calculate theta and phi in "persp(x,y,z ,theta =, phi =)"

Question: we have persp(x,y,z ,theta =, phi =) , now I want to know that if I want to imagine a 3d plot from a certain angle then where should I expect the theta and phi angle. Is it something that we calculate from x axis or Y axis? Or is it a different concept.
I want to understand it in simple language. I tried reading help using ?persp in R studio but could not understand.
Answer: Theta and phi just rotate the object. Imagine you're holding a book in your hands. Theta and phi control how the book is oriented towards your face.


Cannot Access Shared Folder From IIS

Question: From IIS I need to access a folder on another computer.  Both servers are Window 2008 SP2, and they live in a Virtual Private Cloud on Amazon EC2.  They reach one another by private IP -- they are in WORKGROUP, not a domain.
I can access the shared folder manually when logged in to the client as Administrator.  But IIS gets "access denied."  Here's what I have done:

Set File Sharing = ON
Set Password Protected Sharing = OFF
Set Public Folder Sharing = ON
Shared the folder
Added permission to the share: Everyone, Full Control
Added permission to the share: NETWORK SERVICE, Full Control
Verified that File & Printer Sharing is checked in Windows Firewall
Opened port 445 to inbound traffic from local sources

I tried adding <remote-machine-name>\NETWORK SERVICE to the share but it says it does not recognize the machine, which makes sense, I guess.
As I said, from the other computer I have no trouble accessing the shared folder from my user account, but IIS is shut out.  How does the file server even know the difference?  I would assume that with Everyone given full control and password protected sharing turned off, it would not matter what the client user account is.
In any case, how to solve?
UPDATE: To clarify, I am not trying to serve up files on the share directly through IIS.  Rather I am writing files to the share from my code (System.IO).
Answer: IIS's default operational mode is quite locked down.  IIS doesn't use <computername>\NETWORK SERVICE.  It uses <computername>\IUSR_<computername>, which is a member of the <computername>\Guests group.  If the web page you're trying to access on the IIS server instead is requesting authentication, it will instead attempt to use those credentials to authenticate.  If the files it's accessing are executable scripts, then instead it uses IWAM_<computername>.  I don't remember offhand the group membership of that.
What you want to do here isn't very easy to configure over a workgroup.  You'd have to set up an account on the remote machine with the same username and password that the IIS system is using.  You can use a script to hopefully determine the IIS user account's password, but I don't know if IIS changes that periodically or if the script doesn't function on newer versions.
Comment: Not sure if it matters, but I might clarify that I am not trying to access some file on the share through IIS as a URL.  I am using System.IO to write to files in the folder.  Basically it's a upload page that wants to save the stream to a share.
Comment: Ah, that does change things.  I avoid the NETWORK SERVICE account in lieu of creating a dedicated service account on both machines.  NETWORK SERVICE had so many random security issues and special case lock downs that I would only ever use it on legacy systems which demanded it.  Is as close to deprecated as possible.
Comment: I created a new account on the web server and set my App Pool to run under it.  Problem solved it seems.  I did not create a parallel account on the app server machine (where the share is).  But here's what I'm still unsure about.  I've not used Server 2008, so the account management is strange to me.  My only choices for this new account were "Administrator" and "Standard User" -- no ability to tailor permissions.  Is that okay to run a website under a "Standard User" account?  If not, how do I customize the account?

Cannot Access Shared Folder From IIS


Convolution of functions and measures

Question: I need some help with this exercise. I'm not sure how to deal with it:
Let $f(x)=e^{-x^2}$, $\mu$ the Lebesgue measure in $[0,1]$ and $\nu$ the Lebesgue measure in $[2,\infty)$.
I have to find the convolutions $f\ast f$, $\mu\ast f$ and $\mu\ast\nu$.
Using the definition I don't get much, so I was wondering if there is a best way to compute them.
Thanks for any help.
Comment: Using the definition, you get an integral that you simply need to compute. (Not trying to be unhelpful.)
Answer: By definition, we have
$$\begin{align*} (f \ast f)(x) &= \int_{\mathbb{R}} f(x-y) \cdot f(y) \, dy = \int_{\mathbb{R}} \exp \left(-(x-y)^2 - y^2 \right) \, dy \\ &= \sqrt{2\pi \sigma^2} e^{-x^2} \int_{\mathbb{R}} \exp(2xy) \cdot \underbrace{\frac{1}{\sqrt{2\pi \sigma^2}} \exp \left( - \frac{y^2}{2\sigma^2} \right)}_{=:p(y)} \, dy. \end{align*}$$
for $\sigma^2 := 1/4$. As $y \mapsto p(y)$ is the density of the normal distribution with mean $0$ and variance $\sigma^2=1/4$, the integral can be computed using the widely known formula for exponential moments of the normal distribution. Thus,
$$(f \ast f)(x) = \sqrt{\frac{\pi}{2}} e^{-x^2} \cdot e^{\frac{1}{2} x^2} = \sqrt{\frac{\pi}{2}}  \cdot e^{-\frac{1}{2} x^2}$$
Alternatively, a more probabilistic reasoning can be used; it is based on the fact that the convolution of two distributions $\mu$ and $\nu$ equals the distribution of the random variable $X+Y$ where $X \sim \mu$, $Y \sim \nu$ are independent random variables. As $f$ is basically the density of a Gaussian random variable, the calculation of the convolution is pretty easy using some known properties of the Gaussian distribution.

Similarly, we find by the definition of the convolution that the measure $(\mu \ast \nu)$ has the density
$$\begin{align*} h(x)  &= \int 1_{[0,1]}(y) \cdot 1_{[2,\infty)}(x-y) \, dy \\ &= \int_0^1 1_{(-\infty,x-2]}(y) \, dy =  \begin{cases} 0 & x \leq 2 \\ x-2 & x  \in [2,3] \\ 1 & x \geq 3 \end{cases} \end{align*}$$
Comment: Excellent answer, saz! Thanks a lot!

Convolution of functions and measures


What does SR mean for track?

Question: I know that there's a PR for personal record for track, I was looking as I SR and I have no clue what it means.
Comment: Could you provide an example where is it used? Is it possible that you mean *personal best* and *season's best*? These two are mentioned in the Wikipedia article: [Athletics abbreviations](https://en.wikipedia.org/wiki/Athletics_abbreviations).
Comment: Related: https://sports.stackexchange.com/q/14182/35
Answer: The usual notation is:
PB: Personal best
SB: Season's best
I assume that PR and SR are the same, but use 'Record' instead of 'Best'.
Note: I have also seen 'SR' used to mean 'Senior Record' (as opposed to 'JR' = 'Junior Record, so as Martin comments above, it does depend on context.
Generally though, I think this should be true.
Comment: In collegiate (e.g. NCAA) and high school results, 'SR' also shows up in results to denote that the athlete is in their fourth year of study, as in [Senior](https://en.wikipedia.org/wiki/Senior_\(education\)).
Answer: As Thevesh says, this really depends on context.
If you're seeing it in the published results or start lists of an event, it could me "Stadium Record", i.e. the best mark made at a particular facility. See What does HF stand for in context of track and field abbreviations (WR, MR, etc)? for examples of other such abbreviations; I didn't include "SR" in that list but perhaps I should have?
Answer: Without more context, it's difficult to say. As noted in other answers, it could mean "Stadium Record" or "Season Record". (Although "Season Record" is odd phrasing to me - "Season Best" is much more common.) If it is a collegiate or other level of scholastic competition it may mean "School Record".

What does SR mean for track?


Is this a $\sigma$-algebra (closed under countable union)?

Question: Could I say that this
$$
M=\{X\subseteq\Omega=[0,1):x\in X\iff y\in X\}
$$
is an $\sigma$-algebra? I don't see whether it is closed under countable union.
x,y are two singetons of $\Omega$
For example let x=0 y = 0,7 $X_{n}=[1/n, 0,5] n\geq 2$ if we make the infinite countable union of thesse we have $[0,0,5] \notin M$
Comment: What is the problem with proving closure under countable unions? Where exactly do you get stuck?
Comment: Your latest edit to the question added a mistake, by the way.
Comment: which mistake,please?
Comment: "For example let $x=0$ $y = 0,7$ $X_n=[1/n,0,5]$ $n\ge2$ if we make the infinite countable union of thesse we have $[0,0,5]\notin M$"
Comment: and why is this wrong?
Comment: Look carefully at what you wrote. You should be able to figure the mistake out on your own. Perhaps doing that will help you answer you own question correctly.
Comment: it is something about open and closed extremes of the interval? i tried to continue that way but i wasnt sure.Furthermore not finding a contra-example doesn´t mean that proposition is truth
Comment: @manu: if what you say is true, could you tell me which $X_n$ does $0$ belong to?
Comment: no one but is the limit
Comment: @manu: there's no limit in the definition of $\bigcup_nX_n$...
Answer: I assume that you mean that $x,y$ are two (fixed) elements of $[0,1)$ and that $M$ is the collection of all sets that either contain both $x$ and $y$ or contain neither $x$ nor $y$.
We will show that $M$ is a $\sigma$-algebra. It is immediate that $\Omega \in M$ as $\Omega$ contains both $x$ and $y$. Furthermore, if $A \in M$ then $A^c \in M$ since if $A$ contains both $x$ and $y$ then $A^c$ contains neither $x$ nor $y$ and if $A$ contains neither $x$ nor $y$ then $A^c$ contains both $x$ and $y$. So it remains to show that $M$ is closed under countable unions.
Suppose $A_1$, $A_2$, $\ldots \in M$. We will show that $A = \bigcup_{n \in \mathbb{N}} A_n \in M$. If $A$ does not contain $x$ or $y$ this is clear. Suppose $A$ contains $x$. Then there is a $n \in \mathbb{N}$ such that $x \in A_n$. Then we have $y \in A_n$, implying $y \in A$. Similarly, $y \in A$ implies $x \in A$. Hence, if $A$ contains $x$ or $y$ then $A$ contains both $x$ and $y$. It follows that $A \in M$, thus $M$ is closed under countable union.


linkar ultimo slide a próxima data

Question: Estou fazendo site e neste link http://atomica.com.br/clientes/usinavertente/site/nossa-historia.php depois que eu terminei o cliente está pedindo pra que quando chegar no ultimo slide de cada data ir pra próxima data, mas não consegui adaptar para o que já estava feito alguém tem alguma dica pra dar?
HTML

                -
                +

2003

2004

2006

2008

2010

2012

2014

2016

Captação de água industrial (Rio Grande)

Construções Civis

 Montagem

Montagem (vista aérea geral)

 Início da produção do Álcool e Açúcar

SCRIPT PARA ABA

SCRIPT PARA SLIDES

Comment: Por favor, se possível complemente a pergunta com os trechos de código pertinentes à essa parte do seu projeto,para podermos lhe dizer como fazer, é necessário saber como você está fazendo. Está usando alguma biblioteca em Jquery ?
Comment: lucas queiroz   Veja se está bom agora
Comment: Sim, nunca trabalhei com essa biblioteca, irei dar uma resposta se não funcionar me avise que vou tentando modificar
Comment: Lucas queiroz Eu tive que usar duas pq não estava conseguindo dar todas funções que eu precisaria, eu não sou mto bom de back-end sou mais front
Comment: Respondi, porém só pra complementar, Javascript é Front-End :) kkkkk
Comment: Lucas Queiros Pra mim criar um javascript do zero não é front-end, agora manipular biblioteca é outra coisa, no caso ai eu disse isso pq eu não achei como faz isso e não sei criar um do zero, tendeu?
Answer: Bom, dei uma rápida olhada na documentação da biblioteca que você está usando, e acredito que algo como o seguinte pode funcionar :
Pelo que vi essa biblioteca "unslider" está implementando o infinite independente do que você faça, desta forma é um pouco complicado determinar quando o fim foi atingido.
Uma saída é usar uma variável pra guardar de onde a chamada está vindo.
 var ultimoIndex = 0;

var unslider =  $('.my-slider').unslider();
        //infinite:true;   <--- Creio que aqui tenha um erro de sintax, o certo seria usar dentro do .unslider({infinite: true}) mas infinito não é mais o que você quer.
unslider.on('unslider.change', function(event, index, slide) {
    if((index - ultimoIndex) > 1){ significa que o slide pulou uma casa, ou seja deu uma volta completa, já que o passo normalmente é de 1
      if(index > ultimoIndex){  // Clicou próximo
        $('a.pager-next').click();
      }else{
         $('a.pager-prev').click();
       }
     }
       ultimoIndex = index;

});

Comment: Não está funcionando veja se está correto

   jQuery(document).ready(function($) { $('.my-slider').unslider();
  //infinite:true;
  var ultimoIndex = 0;

  var unslider =  $('.my-slider').unslider();

  unslider.on('unslider.change', function(event, index, slide) {
   if((index - ultimoIndex) > 1){ //significa que o slide pulou uma casa, ou seja deu uma volta completa, já que o passo normalmente é de 1
     if(index > ultimoIndex){  // Clicou próximo
    $('a.pager-next').click();
     }else{
     $('a.pager-prev').click();
      }
    }
      ultimoIndex = index;
 });
Comment: O que acontece ? tenta com o console aberto e me diga se tem algum erro, se possível coloque um console.log dentro dos if pra sabermos se está caindo na condição, se o evento está sendo chamado (peguei esse evento na documentação, não testei)

linkar ultimo slide a próxima data


Upper bound on $\|A^{-1}\|_{\infty}$ for $A$ with unit length columns.

Question: Consider a non-singular $A \in \mathbb{R}^{n\times n}$ with $\|\mathrm{col}_i(A)\| = 1$ ($i \in \{1,\ldots,n\}$), where $\mathrm{col}_i(A)$ is the $i$th column of $A$ and $\|\cdot\|$ is the Euclidean norm. Then, can we find an upper bound on $\|A^{-1}\|_{\infty}$?
Thanks!
PS: I find an upper bound $\|A^{-1}\|_{\infty} \leq \sqrt{n}$, but I am not sure if this bound is tight enough. The proof is as follows.
Let $B = A^{-1}$, and we have
$$\mathrm{row}_i(B) \mathrm{col}_j(A) = \begin{cases}1, & i = j,\\0, & i\neq j.\end{cases}$$
This means $\|\mathrm{row}_i(B)\| = 1$, which further implies $\|\mathrm{row}_i(B)\|_1 \leq \sqrt{n}$. Thus, $\|A^{-1}\|_{\infty} = \|B\|_{\infty} = \max_i \|\mathrm{row}_i(B)\|_1 \leq \sqrt{n}$.
Comment: "This means $\|\text{row}_i(B)\| = 1$" part is not correct.
Comment: @uranix Oh, I see where I am wrong. Thanks so much for your helpful comments.
Answer: Since $A$ can be arbitrarily close to a singular matrix, the norm of its inverse is not bounded above. E.g.
$$
\left\|\pmatrix{1&\cos t\\ 0&\sin t}^{-1}\right\|_\infty
=\left\|\pmatrix{1&-\frac{\cos t}{\sin t}\\ 0&\frac{1}{\sin t}}\right\|_\infty\ge\frac{1}{|\sin t|}\to\infty
$$
as $t\to0$.
Comment: Thanks very much for your answer. Since $\mathrm{col}_i(A)$ and $\mathrm{row}_j(B)$ are orthogonal for $i \neq j$, I intuitively assumed that they are parallel for $i = j$. But actually, $\|\mathrm{row}_j(B)\|$ can be arbitrarily large as their angle tends to $\pi/2$.


If for $\epsilon \gt 0 \space x \in (a-\epsilon,b+\epsilon)$, Prove that $x \in [a,b]$

Question: Assume that $a,b,x$ are real numbers such that $a<b$. We have :
$\forall \epsilon \gt 0 \space \space x\in (a-\epsilon,b+\epsilon)$
Prove that $x\in[a,b]$.
Note: I tried to assign values to $\epsilon$ and i noticed that the smaller $\epsilon$ is, i get closer to the desired result.  But it seems that i need to assign something related to limits  to $\epsilon$ . I don't know if i can do that. ( Something like $\lim_{n\to \infty}\frac{1}{n}$ )
Comment: Your attempt leads to a direct proof, actually. You would be done if you proved that $$\bigcap_{n=1}^\infty \left(a-1/n,b+1/n\right)=[a,b]$$ which can be done fairly routinely.
Comment: @NicholasStull Thank you :)
Answer: It's simpler than that, you don't need to use limits or anything. Suppose to the contrary that $x$ is not in $[a,b]$. Then either $x < a$ or $x > b$.
If $x < a$, let $\epsilon = a-x > 0$. Then by hypothesis $x$ must belong to
$$(a - \epsilon, b+\epsilon) = (x, b+\epsilon),$$
i.e. we must have $x > x$, a contradiction.
Similarly if $x > b$, let $\epsilon = x-b>0$, then $x \in (a-\epsilon,x)$, contradiction again.
Answer: Assume $x\not\in [a,b]$. Then either $x<a$ or $x>b$ and WLOG assume $x<a$. Then let $\epsilon_0=a-x$. Then with $\epsilon={1\over 2} \epsilon_0$ we see that $x\not\in (a-\epsilon, b+\epsilon)$, a contradiction.


Generate one-time-use custom links for emails and interact with them to accomplish tasks

Question: Is there a module that would auto-generate custom unique  one-time-use URLs that timeout after a set time, and can be used to accomplish tasks and progress workflows in Drupal 7?
Use Case 1
User must click link in email to verify their address is valid.
Use Case 2
As part of a workflow process users must confirm they wish to complete an action by clicking on the appropriate link in an email message and depending on the link chosen the node would progress to a different state in the workflow
Answer: You can copy function "user_pass_reset_url" and form "user_pass_reset" and customize it for your needs. With first you create custom link and with the second you can get "one-time-link" logic.
Answer: I was having some problems generating the one time login URL using the Drupal 7 documentation, This worked for me.
<code>$mail = 'firstname.lastname@example.com';
// Load the user.
$account= user_load_by_mail($mail);
$url = user_pass_reset_url($account);
print '$url';
</code>
Comment: What about the scenario when the user does not exist yet?
Comment: Good point...i was dynamically creating the user based on the email address associated with the node, then building an email address to send to them with this link included.


Translation from C# to Delphi

Question: I need help translating part of the C# code to Delphi.
I would very much appreciate any help or advice.
unsafe {
    fixed (byte* bpt = &buff[140]) {
        byte b1 = bpt[0];
        byte b2 = bpt[1];
        byte b3 = bpt[2];
        byte b4 = bpt[3];
    }
}

I tried several ways, defining a record with 4 byte vars, defining tbytearray, but nothing seems to be right.
Any thoughts on this?
Thanks.
UPDATE
Since it seems that I haven't defined my questions right, since this is my first question, here is the complete function on C#.
        private void ProcessCommAlarm_V40(ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
        {
            MyDebugInfo AlarmInfo = new MyDebugInfo(DebugInfo);

            byte[] buff = new byte[dwBufLen];
            System.Runtime.InteropServices.Marshal.Copy(pAlarmInfo, buff, 0, (int)dwBufLen);

            string sBuff = "";

            if (dwBufLen - 140 > 0 && (dwBufLen - 140) % 4 == 0)
            {
                int msgType = BitConverter.ToInt32(buff, 0);
                string sMsgType = "";
                bool bAcceptedMsg = false;
                int nTargetType = 0;

                switch (msgType)
                {
                    case 2:
                        sMsgType = "Video Loss"; bAcceptedMsg = true; nTargetType = 1; break;

                    case 3:
                        sMsgType = "Motion"; nTargetType = 1; break;
                }

                if (bAcceptedMsg)
                {
                    int nTotalElements = BitConverter.ToInt32(buff, 12);

                    if ((nTargetType == 1 && nTotalElements <= CHCNetSDK.MAX_CHANNUM_V30) || (nTargetType == 2 && nTotalElements <= CHCNetSDK.MAX_DISKNUM_V30))
                    {

                        int len = nTotalElements * 4;
                        byte[] channels = new byte[len];

                        unsafe
                        {
                            fixed (byte* bpt = &buff[140])
                            {
                                byte b1 = bpt[0];
                                byte b2 = bpt[1];
                                byte b3 = bpt[2];
                                byte b4 = bpt[3];

                                IntPtr dwDataAddress = new IntPtr(b1 + b2 * (1 << 8) + b3 * (1 << 16) + b4 * (1 << 24));
                                System.Runtime.InteropServices.Marshal.Copy(dwDataAddress, channels, 0, len);
                            }
                        }

                        for (int i = 0; i <= len - 4; i += 4)
                        {
                            sBuff += string.Format("Channel No: {0}", BitConverter.ToInt32(channels, i));
                            sBuff += Environment.NewLine;
                        }
                    }
                }
            }
        }

Now, this is what I have done so far, which includes the change given my @remy-lebeau.
procedure ProcessCommAlarm_V40(pAlarmer: LPNET_DVR_ALARMER; pAlarmInfo: PChar; dwBufLen: DWORD; dwUser: DWORD);
var
  buff: array of byte;
  msgType: Integer;
  sMsgType: String;
  bAcceptedMsg: Boolean;
  nTargetType: Integer;
  sBuff: String;
  nTotalElements: Integer;
  channels: array of byte;
  len: Integer;
  b1,b2,b3,b4:byte;
  bpt: pbyte;
  dwDataAddress: IntPtr;
  I: Integer;
begin
  sBuff := '';

  SetLength(buff, dwBufLen);
  CopyMemory(buff, pAlarmInfo, dwBufLen);

  if (dwBufLen - 140 > 0) and ((dwBufLen - 140) mod 4 = 0) then begin
    msgType := Integer(buff[0]);
    sMsgType := '';
    bAcceptedMsg := false;
    nTargetType := 0;

    case (msgType) of
      2:
        begin
          sMsgType := 'Video loss';
          bAcceptedMsg := true;
          nTargetType := 1;
        end;
    end;

    if (bAcceptedMsg) then
    begin
      nTotalElements := buff[12];
      if ((nTargetType = 1) and (nTotalElements <= MAX_CHANNUM_V30)) or ((nTargetType = 2) and (nTotalElements <= MAX_DISKNUM_V30)) then begin
        len := nTotalElements * 4;
        SetLength(channels,len);

        bpt := @buff[140];
        b1 := bpt[0];
        b2 := bpt[1];
        b3 := bpt[2];
        b4 := bpt[3];

        dwDataAddress := IntPtr(b1 + b2 * (1 shl 8) + b3 * (1 shl 16) + b4 * (1 shl 24));

        sBuff := sBuff + IntToStr(dwDataAddress);
        sBuff := sBuff + #10 + #13;

        CopyMemory(Channels, @dwDataAddress, len);

        I:=0;
        while (i <= len - 4) do begin
          sBuff := sBuff + 'Channel No: ' + IntToStr(channels[i]);
          sBuff := sBuff + #13 + #10;
          i:= i + 4;
        end;
      end;
    end
  end;
end;

Can someone please recheck the translation, because Delphi code is not reproducing the same results as C#.
UPDATE:
After reading the detailed explanation @Remy wrote down below, I was able to reproduce the same results on both applications in C# and in Delphi.
The code which now is working is below.
procedure ProcessCommAlarm_V40(pAlarmer: LPNET_DVR_ALARMER; pAlarmInfo: IntPtr; dwBufLen: DWORD; dwUser: IntPtr);
var
  buff: array of byte;
  channels: array of byte;
  msgType: Integer;
  sMsgType: String;
  bAcceptedMsg: Boolean;
  nTargetType: Integer;
  sBuff: String;
  nTotalElements: Integer;
  len: Integer;
  b1,b2,b3,b4:byte;
  bpt: pbyte;
  dwDataAddress: IntPtr;
  I: Integer;
  x:pbyte;
begin
  Form1.Memo1.Lines.Add(FormatDateTime('H:m:s',now));
  sBuff := '';

  SetLength(buff, dwBufLen);
  CopyMemory(buff, Pointer(pAlarmInfo), dwBufLen);

  if (dwBufLen - 140 > 0) and ((dwBufLen - 140) mod 4 = 0) then begin
    msgType := Integer(buff[0]);
    sMsgType := '';
    bAcceptedMsg := false;
    nTargetType := 0;

    case (msgType) of
      2:
        begin
          sMsgType := 'Video loss';
          bAcceptedMsg := true;
          nTargetType := 1;
        end;
    end;

    if (bAcceptedMsg) then
    begin
      nTotalElements := buff[12];
      if ((nTargetType = 1) and (nTotalElements <= MAX_CHANNUM_V30)) or ((nTargetType = 2) and (nTotalElements <= MAX_DISKNUM_V30)) then begin
        len := nTotalElements * 4;
        SetLength(channels,len);

        bpt := @buff[140];
        b1 := bpt[0];
        b2 := bpt[1];
        b3 := bpt[2];
        b4 := bpt[3];

        dwDataAddress := IntPtr(b1 + b2 * (1 shl 8) + b3 * (1 shl 16) + b4 * (1 shl 24));
        CopyMemory(Channels, Pointer(dwDataAddress), len);

        I:=0;
        while (i <= len - 4) do begin
          sBuff := sBuff + 'Channel No: ' + IntToStr(channels[i]);
          sBuff := sBuff + #13 + #10;
          i:= i + 4;
        end;
      end;
    end
  end;
end;

Comment: You should show what you have done and tell how you verify it is correct or not.
Comment: @fpiette, thanks for your comment, I apologize, this is my first post. I have updated the question.
Comment: This isn't a translation service.
Comment: Yes, thank you, I am aware of that, but I am stuck on this part of the code for 10 days now in project with over 20000 lines. So, I know it's not by the rules, I know I'm asking to much, but I really need help from someone who is more experienced than me in this field.
Comment: @Mark Have you tried debugging the code to see where its behavior deviates from your expectations?  This is a Q&A site, not a debugging service.  You should focus on *specific questions*.
Comment: Exactly. If you've got 20k lines of code, it's time to learn how to debug. You should find a different site if you want this kind of service. Our rules exist for a reason.
Answer: Given buff: array[0..MaxLimit] of Byte; where MaxLimit is >= 143;
In Delphi 2009 and later:
var
  bpt: PByte;
  b1, b2, b3, b4: Byte;
begin
  bpt := @buff[140];
  b1 := bpt[0];
  b2 := bpt[1];
  b3 := bpt[2];
  b4 := bpt[3];
end;

In Delphi 2007 and earlier:
var
  bpt: PChar;
  b1, b2, b3, b4: Byte;
begin
  bpt := PChar(@buff[140]);
  b1 := Byte(bpt[0]);
  b2 := Byte(bpt[1]);
  b3 := Byte(bpt[2]);
  b4 := Byte(bpt[3]);
end;

Alternatively:
var
  bpt: PByte;
  b1, b2, b3, b4: Byte;
begin
  bpt := @buff[140];
  b1 := bpt^; Inc(bpt);
  b2 := bpt^; Inc(bpt);
  b3 := bpt^; Inc(bpt);
  b4 := bpt^; Inc(bpt);
end;

UPDATE: That being said, I see a number of problems with your translation.

in the C# code, the dwUser parameter is declared as IntPtr, which is a pointer-sized integer.  Delphi also has IntPtr.  But in your Delphi code, you have declared the parameter as a DWORD instead.  That will work in a 32-bit build, but not in a 64-bit build.  If the parameter ever receives a value more than 32-bits, like a memory address, it will get truncated.  Use DWORD_PTR instead, if not IntPtr.

in the C# code, the pAlarmInfo parameter is declared as IntPtr.  But in your Delphi code, you have declared the parameter as a PChar instead.  Though that can work, an untyped Pointer would have been more appropriate, if not IntPtr.

in Delphi, using array of bytes is OK for the buff and channels variables, though TBytes or TArray<Byte> would be more preferred in modern Delphi versions.

using the Win32 CopyMemory() function is fine, but you should consider using Delphi's System.Move() instead.  In any case, your 1st call to CopyMemory() is correct (though, if pAlarmInfo is declared as IntPtr, you will have to type-cast it to Pointer).  However, your 2nd call is wrong.  The C# code is copying len bytes from the memory address held in dwDataAddress, whereas you are copying len bytes from the address of dwDataAddress itself.  You need to type-cast dwDataAddress to a pointer and copy from the pointed-to address instead.

your translation of the assignments of msgType and nTotalElements are wrong. The C# code is extracting a 4-byte integer from buff at indexes 0..3 and 12..15, respectively.  Your Delphi code is reading 1 byte at indexes 12 and 15 and scaling their values up to an Integer.  Not the same thing.

you completely omitted case 3 from the case msgType of statement.  Probably because it was not setting bAcceptedMsg = true.  I suspect that missing assignment might be a bug in the C# code.

#10 + #13 should be #13 + #10, or simply #13#10.  Or, you should use Delphi's System.sLineBreak constant instead.

your translation of reading the channel numbers is wrong. Like further above, the C# code is extracting a 4-byte integer from channels at index i..i+3, respectively.  Your Delphi code is reading 1 byte at index i and scaling its value up to an Integer.
Comment: thank you very much for you answer. I know I'm asking for much, but if you could recheck what I have done so far, that would be awesome. Thanks.
Comment: Dear @Remy, I'm speechless. I really can't thank you enough. I struggled so long with this and you fixed it like it was a breeze. I changed the types of the dwUser to IntPtr, pAlarmData to IntPtr, I changed both CopyMemory functions to cast Pointer as 1) CopyMemory(buff, Pointer(pAlarmInfo), dwBufLen); and 2) CopyMemory(Channels, Pointer(dwDataAddress), len); After this change both C# and Delphi app are reproducing the same output.

Translation from C# to Delphi


Display Users emails with views

Question: I want to display the users emails with views, but it doesn't show for the users, only the administrators can see them.
How can i display them to the users with views, and i have a warning: Email address for a given user. This field is normally not shown to users, so be cautious when using it.
Answer: I found a way to do it by using user_presave, i created a field_profile_email field using this answer : https://drupal.stackexchange.com/a/205308/65949

Display Users emails with views


Three sides of a trapezium are each equal to $k$ cm.Prove that the greatest possible area of the trapezium is $\frac{3\sqrt3 k^2}{4}$ sq cm.

Question: Three sides of a trapezium are each equal to $k$ cm.Prove that the greatest possible area of the trapezium is $\frac{3\sqrt3 k^2}{4}$ sq cm.
I let two non-parallel sides and one of the parallel sides as $k$(shorter one).I know that area of the trapezium is $\frac{1}{2}\times $sum of parallel sides $\times$ height.But in this question,neither height is given nor longest side is given.How should i formulate the equation of the area?
Comment: introduce an angle so that you can write down the fourth side in terms of the angle
Comment: How can you assume that $k$ is the length of non-parellel sides?
Comment: If it is a pure" trapezium, then you are right.
Comment: Can you tell how is this related to supremum-infimum.
Comment: @AdityaAgarwal,this question is asking the greatest possible area,so supremum problem.
Comment: Ohkk, I presume it is something multivariable.
Comment: I can just tell you that the triangle would be an isosceles. And if we let the other parallel side to be $k_1$, then, $h^2+\frac{(k_1-k)^2}{4}=k^2$
Comment: And the area would be $\frac12(k_1-k)h$. (If $k_1>k$)
Comment: This does not give me equation in one variable $k$,other two variables $k_1,h$,how to express them in terms of $k?$@AdityaAgarwal
Answer: You can parametrize the trapezium via its height $h$. Then the longer side is
$$ 2 \sqrt{k^2-h^2} + k $$ and its area is
$$ h (\sqrt{k^2-h^2} + k)\ .$$
The derivative for $h$ is
$$k - \frac{h^2}{\sqrt{-h^2 + k^2}} + \sqrt{-h^2 + k^2}\ ,$$
which is zero for $h=0$ or $h=\pm \frac{\sqrt{3}}{2}k$. $h=\frac{\sqrt{3}}{2}k$ gives the proposed optimum, which you can be sure about after also checking the border case $h=k$ (which gives an area of $k^2$).
Answer: Notice, let the unknown side be $x$ which is parallel to one of three equal sides each of length $k$ then the normal distance between the parallel sides can be determined as follows (using pytagorean theorem in a right triangle)
$$\sqrt{k^2-\left(\frac{x-k}{2}\right)^2}$$
the area of the trapezium is given as
$$A=\frac{1}{2}(x+k)\sqrt{k^2-\left(\frac{x-k}{2}\right)^2}\tag 1$$
differentiating (1) w.r.t. $x$, we get
$$\frac{dA}{dx}=\frac{1}{2}(x+k)\frac{-(x-k)}{4\sqrt{k^2-\left(\frac{x-k}{2}\right)^2}}+\frac{1}{2}\sqrt{k^2-\left(\frac{x-k}{2}\right)^2}$$
$$=\frac{1}{8}\frac{x^2-k^2+4k^2-4\left(\frac{x-k}{2}\right)^2}{\sqrt{k^2-\left(\frac{x-k}{2}\right)^2}}=\frac{1}{4}\frac{(-x^2+kx+2k^2)}{\sqrt{k^2-\left(\frac{x-k}{2}\right)^2}}$$
Again differentiating w.r.t. $x$, we get
$$\frac{d^2A}{dx^2}=\frac{x^3-3kx^2-7k^2x+5k^3}{16\left(k^2-\left(\frac{x-k}{2}\right)^2\right)^{3/2}}$$
Now, for maximum or minimum, setting $\frac{dA}{dx}=0$, we get
$$\frac{1}{4}\frac{(-x^2+kx+2k^2)}{\sqrt{k^2-\left(\frac{x-k}{2}\right)^2}}=0$$
$$x^2-kx-2k^2=0$$
$$x=\frac{-(-k)\pm\sqrt{(-k)^2-4(1)(-2k^2)}}{2(1)}=\frac{k\pm 3k}{2}$$
But, side $k>0$ hence, we accept $$x=\frac{k+3k}{2}=2k$$
It can be checked that $\frac{d^2A}{dx^2}=-\frac{13}{6\sqrt 3}<0$ at $x=2k$. Hence, the area is maximum at $x=2k$
Hence, substituting $x=2k$, the greatest possible area is $$A_{\text{max}}=\frac{1}{2}(2k+k)\sqrt{k^2-\left(\frac{2k-k}{2}\right)^2}$$
$$=\frac{3k}{2}\sqrt{k^2-\frac{k^2}{4}}=\frac{3k}{2}\sqrt{\frac{3k^2}{4}}$$
$$\color{red}{A_{\text{max}}=\frac{3\sqrt 3\ k^2}{4}\ \text{sq. cm.}}$$
Answer:
The diagram shows the sides $k$ and included angles $\theta$ and $\pi-2\theta $ of the trapezium. Then its area $A$ can be expressed in terms of $k$ and $\theta$ now.
$$
\begin{aligned}
A &=k^{2} \sin \theta+\frac{k^{2}}{2} \sin (\pi-2 \theta) \\
&=\frac{k^{2}}{2}(2 \sin \theta+\sin 2 \theta)
\end{aligned}
$$
$$
\begin{aligned}
&\quad \frac{d A}{d \theta}= k^{2}(\cos \theta+\cos 2 \theta)=0 \\\Leftrightarrow & \quad \cos \theta+\cos 2 \theta=0 \\
\Leftrightarrow & \quad  2 \cos ^{2} \theta+\cos \theta-1=0 \\
\Leftrightarrow &\quad (2 \cos \theta-1) (\cos \theta+1)=0\\
\Leftrightarrow &\quad \cos \theta=\frac{1}{2} \text { or }-1 \textrm{ (rejected) }
\end{aligned}
$$
Hence
$$
\begin{aligned}
A_{\max } &=\frac{k^{2}}{2}\left(2 \cdot \frac{\sqrt{3}}{2}+\frac{\sqrt{3}}{2}\right) =\frac{3 \sqrt{3}}{4} k^{2} \quad  cm^2
\end{aligned}
$$
Comment: How do you get to draw this trapezoid? Do you use any software? geogebra? Desmos?
Comment: Geogebra is very useful!
Answer:
Since we have an isosceles trapezium (non-parallel sides of equal length), we can "clip off" a triangular section and arrange the portions into a rectangle of dimensions $ \ k + x \ $ by $ \ h \ \ , $ with $ \ k \ $ being the hypotenuse of a right triangle with legs $ \ x \ $ and $ \ h \ = \ \sqrt{k^2 - x^2} \ \ . $  The area of the trapezium is then given by
$$ A \ \ = \ \ (k + x)·\sqrt{k^2 - x^2} \ \ = \ \ \sqrt{(k + x)^2·(k^2 - x^2)} \ \ = \ \ \sqrt{(k + x)^3·(k  - x )} \ \ . $$
Without the use of calculus, we can take $ \ x \ = \ r·k \ $ to express the area as $ \  \sqrt{(k + rk)^3·(k  - rk )}   $ $ = \ k^2·\sqrt{(1 + r )^3·(1  - r )} \ = \ k^2·\sqrt{2·(1 + r )^3 \ - \ (1  + r )^4} \ \ . $  Making the further substitution $ \ s \ = \ 1 + r \ \ , $ the area is then $ \ k^2·\sqrt{2 s^3  -  s^4} \ = \ k^2·\sqrt{ s^3 · (2  -  s)} \ \ . $  Applying the AM-GM inequality, we obtain
$$ \sqrt[4]{\left(\frac{s}{3} \right)^3·(2 - s )}
 \ \ \le \ \   \frac{\frac{s}{3} \ + \  \frac{s}{3} \ + \ \frac{s}{3} \ + \ (2 \ - \ s)}{4} \ \ = \ \ \frac{1}{2}  $$ $$ \Rightarrow \ \ A \ = \ k^2 \ · \ \sqrt{3^3} \ · \ \left[ \ \sqrt[4]{\left(\frac{s}{3} \right)^3·(2 - s )} \ \right]^2  \ \ \le \ \  k^2 \ · \ 3\sqrt{3} \ · \left( \frac{1}{2} \right)^2 \ \ ,  $$
with equality occurring for $ \ s \ = \ \frac32 \ \Rightarrow \ r \ = \ \frac12 \ \Rightarrow \ x \ = \ \frac{1}{2}·k \ \ . $
With the use of differentiation, we have
$$ \frac{dA}{dx} \ \ = \ \ \frac{3}{2}·(k + x)^{1/2}·(k - x)^{1/2} \  - \ \frac{1}{2}·(k + x)^{3/2}·(k - x)^{-1/2} \ \ = \ \ 0 $$
$$ \Rightarrow \ \ 3·(k - x) \ \ = \ \ k + x \ \ \Rightarrow \ \ x \ = \ \frac{k}{2} \ \ . $$
[We then have $ \frac{d^2A}{dx^2} \   = \   \frac{2x^2-2kx-k^2}{(k - x)^{3/2}·(k + x)^{ 1/2}} \ \ < \ \ 0 \ \   $ for $ \ x \ = \ \frac{k}{2} \ \ . \ ] $
So the maximum area of the trapezium is $ \ \sqrt{\left(\frac{3k}{2} \right)^3·\left(\frac{ k}{2} \right) } \ = \ \frac{3\sqrt3}{4}·k^2 \ \ . $
(The factor of $ \ \frac{ \sqrt3}{4}·k^2 \ $ is perhaps a bit of a tip-off that a $ \ 60º \ $ angle is involved (as seen in Lai's solution), as this is the area of an equilateral triangle of side $ \ k \ \ .   $  This actually suggests another approach:  as the equilateral triangle maximizes the area of an isosceles triangle, Lai's parallelogram can be subdivided into three equilateral triangles with the indicated maximal total area.
Yet another way -- which would need to be made rigorous -- is to surmount the isosceles trapezium with an isosceles triangle.  The area is maximized when the large "total" triangle is equilateral, which occurs for $ \ y \ = \ z \ = \ k \ \ $ in the diagram below.  This maximal area is $ \ \frac{\sqrt{3}}{4}·(2k)^2 \ \ , $ of which the maximal-area isosceles trapezium has $ \ \frac34 \ $ of that area.)


Survival analysis in R with left-truncated data

Question: I am doing a survival analysis in R with the survival package.
I think I am working with left-truncated data, but I'm not entirely sure how to handle it.
I have a cohort of patients diagnosed between 1990 and 2012. All the patients have a well-defined time of diagnosis (entry time). However, the outcome of interest (specific worsening of disease) has only been documented from the year 2000 and onwards. For patients diagnosed before 2000, it is therefore not known whether the outcome has occurred before that time - only after.
My first thought was that I needed to restrict the analysis to the time period from 2000, only including patients diagnosed after that point in time. After doing some reading, it appears to be unnecessary to exclude patients diagnosed before 2000. This seems to be left-truncation and that can be dealt with in coxph using Surv(time1, time2, event), where time1 is left-truncation time (time from diagnosis to the start of documentation of the outcome) and time 2 is the time-to-event (from time of diagnosis).
Here are two examples of patients in my dataset:
Patient #1: Diagnosed in 1999. Outcome observed in 2001. Left-truncation time: 1 year (to 2000). Time-to-event: 2 years.
Patient #2: Diagnosed in 2001. Outcome observed in 2005. Left-truncation time: 0 years. Time-to-event: 4 years.
For these patients, I suppose their survival times (in years) in the survival object would be (respectively):
Surv(time1 = c(1,0), time2 = c(2,4), event = c(1,1))

Is this an example of left-truncated data? If so, is this the correct way to handle it?
Answer: I'm assuming that time from diagnosis is your underlying time variable. For simplicity I also assume that the event can only occur once.
You can treat your data as being left-censored. This is different from being left-truncated, however.
For left-truncated data we only include in the study patients conditional on them not having experienced the event at the time of inclusion. This would in your case amount to throwing away the patients that have had the event before 2000. Thus, we are modelling survival conditional on survival until inclusion.
This is different from left-censoring. Left-censoring occurs when we only know the upper limit of the time of an event. This is exactly what you suggest yourself, if I understand you correctly. In this case, we include all individuals regardless of their survival times, but for some individuals we only know an upper bound of their survival time.
Chapter III of Statistical Models Based on Counting Processes by PK Andersen et al. provides a good explanation of the above along with some examples of both cases.
Answer: You are likely to run afoul of immortal time bias, which means that the cohort diagnosed pre-2000 is effectively immortal, until post-2000 when the outcome can occur. Per Rothman and Greenland, the correct approach is indeed to exclude (truncate) the pre-2000 years of observation from the analysis, or else risk biasing between cohort estimates toward the null hypothesis of no difference in hazard.
The survival command Surv does not seem to follow the syntax you use. What about creating a new variable where the value 0 corresponds to the Beginning of (Study) Time (e.g. year = 2000?), 1 corresponds to 1 unit of time in, etc?
You will want to read up on: Rothman, K. J. and Greenland, S. (1998). Modern Epidemiology, chapter Cohort Studies—Immortal Person Time. Lippincott-Raven, 2nd edition.
Comment: I see immortal time bias is important, for example, in drug trials where patients receiving the drug are guaranteed to live a given time by study design whereas the control group is not, resulting in an observed (false) positive effect of the drug.

However, in my case, the missingness in outcome data is equal for all patients, regardless of the exposure. Omitting all patients diagnosed pre-2000, will result in a severe lack of statistical power, as many of them will experience the outcome after 2000. I think there must be a way to control for possible bias without omitting these patients.
Comment: Ah I see, that was not clear. On the other hand: perhaps your data simply do not support the analysis you want to perform.


Using jQuery Tools

Question: I have looked online to see if it is possible to use jQuery Tools 1.2.7 with Drupal 7. I see that there is a defunct project that attempted to use it in Drupal 6 but nothing for Drupal 7. I tried downloading it and including it in the scripts line in the .info file for my module but still not executing. I suspect the issue might be that jQuery Tools expect jQuery 1.7.2 while Drupal 7 uses jQuery 1.5.
The specific feature that I am trying to use is the overlay function. I followed the online documentation but I don't see any overlay. All it does is reloading the same page over again. I was wondering if anyone has used the overlay module with Drupal 7 and has gotten it to work.
Answer: You're approaching this correctly in trying to add this in your own info file - not every jQuery library needs its own Drupal module and its often more overhead than its worth to try and set one up. If the jQuery tools module is what you need but its not compatible with the current version of Drupal 7, than use jQuery Update module to upgrade your version of jQuery.
If all you need is the overlay and you're not tied to the jQuery Tools implementation, you have a couple of customized Drupal options that should be easy to implement:

The built-in overlay functionality in Drupal 7.x core (see https://drupal.org/node/1087026 for guidance on how to implement)
Use one of the specialized overlay libraries - best one I've found is Colorbox, which has a Drupal module with easy to implement solutions (i.e. no hand-coding javascript)

Using jQuery Tools


Email Verification with React and Flask

Question: I have setup a Email Verification Function in my ReactJS app, with flask as backend. But for some reason its giving out Something went wrong. Error, with 500 - Internal Error at http://localhost:5000/send-verify-email.
PFA Relevant files. Let me know if I've missed any file or information.
Someone please tell me the issue -
Here's the Verify Button's eventHandler -
    const handleClick = ( user ) => {
        if(user.email) {
            // Dispatch send email link
            dispatch(sendEmailVerifyLink(user.email))
        }
    }

auth.js File
// Action generator for sending verify email link`enter code here`
export const sendEmailVerifyLink = (recipientEmail) => (dispatch) => {

  // Dispatch Start Process
  dispatch({
    type: EMAIL_VERIFY_SEND_LINK
  })

  // create data body object
  const data = {
    email: recipientEmail
  }

  // send request to server
  axios.post('/send-verify-email', data)
    .then((res) => {
      // Dispatch success action
      dispatch({
        type: EMAIL_VERIFY_SEND_LINK_SUCCESSFULLY
      })

      // set Alert
      dispatch(setAlert(res.data.message, 'success'))
    })
    .catch((err) => {

      // Create response from error object
      const res = err.response

      // Dispatch fail action
      dispatch({
        type: EMAIL_VERIFY_SEND_LINK_FAILED
      })

      if(res && (res.status === 404 || res.status === 422 || res.status === 500))
      {
        // Set ALert for the above status codes
        dispatch(setAlert(res.data.message))
        return
      }

      // Set error alert
      dispatch(setAlert('Something went wrong.'))
    })
}

auth.py File
@auth.route('/send-verify-email', methods=["POST"])
def send_verify_email():
    """
    Route to handle and send verify email message.
    """

    # Get Recipient email address
    try:
        req = request.get_json()
        recipientEmail = req["email"]

    except:
        response = {
            "success": False,
            "message": "Please Provide Recipient Email Address."
        }
        return make_response(jsonify(response)), 422

    # Check if user exists or not
    user = ( Admin.query.filter_by(email=recipientEmail).first() or
             Extractor.query.filter_by(email=recipientEmail).first() or
             Management.query.filter_by(email=recipientEmail).first() )

    # return if user not exist
    if(not user):
        response = {
            "success": False,
            "message": "User Not Found, Please a Registered Email ID."
        }
        return make_response(jsonify(response)), 404

    # Check if user is verified or not
    if(user.verified):
        response = {
            "success": False,
            "message": "User is already verified."
        }
        return make_response(jsonify(response)), 422

    # create access token
    token = user.encode_access_token()

    # Verify Email Link
    verify_link = f"http://localhost:3000/verify-email/{token}"

    # Send reset link meail message
    try:
        send_verify_link_mail(recipient=recipientEmail, verify_link=verify_link)
        response = {
            "success": True,
            "message": f"Email Verification link has been sent to {recipientEmail}."
        }
        return make_response(jsonify(response)), 201

    except Exception as e:
        response = {
            "success": False,
            "message": 'Something went wrong.',
        }
        return make_response(jsonify(response)), 500

Comment: Maybe you should return the error message instead of the string literal `"Something went wrong"`. Is it the `"f"` character outside the string in the try portion? `"message": f"Email Verification link has been sent to {recipientEmail}."`?
Answer: Maybe your problem is with CORS. For default, server don't receive front-end request, but you can easily fix that installing flask-cors (pip install flask-cors). So try write this in your code:
from flask_cors import CORS

app = Flask(__name__)
CORS(app)

source: https://flask-cors.readthedocs.io/en/latest/
Comment: Perhaps not since OP is getting a valid response back from their backend.
Comment: yepp! but I had a similiar error when I tried to send info from frontend to backend

Email Verification with React and Flask