+= and incremental growth give two different values in C

Question: I have a chunk of code that is measuring the length of a block of text.  I need the length of a gap of an unknown number of N inserted within the text (which consists of G, A, C, and T only) as well as the total length of the text block containing the gap(s).  I am working one character at a time via a fgetc() and I devised two different ways to calculate the values, but they are giving me vastly differing results.
Method A:
...
} else if (in != '\n') {
    scafLength++;
    if (in == 'N') {
//Read entire gap
        while ((in != 'G') && (in != 'A') && (in != 'C') && (in != 'T') && (in != '>')) {
            if (in != '\n'){
                gapLength++;
                scafLength++;
            }
            in = fgetc (inFile);
//If it's at the end of the file
            if (feof (inFile)) {
                break;
            }
        }
        ...
        Do stuff
        ...
//Reset for next gap and allow normal processing of next character after the gap
        gapLength = 0;
        fseek (inFile, -1, SEEK_CUR);
    }
}

Method B:
...
} else if (in != '\n') {
    scafLength++;
    if (in == 'N') {
//Read entire gap
        while ((in != 'G') && (in != 'A') && (in != 'C') && (in != 'T') && (in != '>')) {
            if (in != '\n'){
                gapLength++;
            }
            in = fgetc (inFile);
//If it's at the end of the file
            if (feof (inFile)) {
                break;
            }
        }
        scafLength += gapLength - 1;
        ...
        Do stuff
        ...
//Reset for next gap and allow normal processing of next character after the gap
        gapLength = 0;
        fseek (inFile, -1, SEEK_CUR);
    }
}

> is a character used to denote a new scaf.  This is the only area where scafLength and gapLength are altered, except to set them back to 0 for a new gap/scaf.  Now, I expected an off-by-one in method A, which is why I made method B, but the numbers I'm getting are way off.  Method A is giving me 16,777,216 as the longest scaf while Method B gives me 23,080,784.  The real longest scaf (verified by multiple other programs) is 23,428,386 and there are not 5 million gaps to account for a fencepost error (the most is 180).
I'm curious why would these two approaches give such drastic differences?  Also, if anyone can see a mistake I'm making, I'd appreciate it being pointed out.
EDIT: From the first few comments I need to clarify, the gapLength is reset to 0 after it serves it's purpose in the same else if ().  I've updated the code.
Comment: `scafLength += gapLength - 1;` : I seem `gapLength` should be reset.
Comment: for both methods,  right after the line: if (in == 'N') {, the var gapLenght needs to be re-set to 0.
Comment: I already do reset it, I just didn't post it, sorry for the confusion.  I've updated my code.
Answer: In the first version it looks like you only incrementing scafLength when (in != '\n') but in the second version you continually add the value of gapLength - 1 whenever you enter the outer if-block and not just when you enter the inner (in != '\n')
Presumably the value of gapLength isn't reset and therefore the second version grows faster.
As your code is incomplete it's really hard to say, so consider this a guess.
Comment: I already have it reset within the same `else if ()` block, I have updated my code to show as much, sorry for the confusion.
Answer: Turns out the issue was with my variable type caused by my compiler. gapLength and scafLength were originally declared as int.  Having run out of options, I switch them to long and the code performs perfectly.  Apparently my compiler has the short int limit of 32,768.


How to test string for valid double content with boost::spirit::x3?

Question: I am trying to determine if a given string is a valid double representation.
The code I am using looks like this:
<code>bool testNumeric(const std::string& s)
{
    try
    {
        const auto doubleParser = boost::spirit::x3::double_;
        auto iter = s.begin();
        auto end_iter = s.end();
        double result = 0.;
        boost::spirit::x3::parse(iter, end_iter, doubleParser, result);
        return iter == end_iter;
    }
    catch (...)
    {
        return false;
    }
}
</code>
I am not interested in the resulting double (for now).
If I give this function an input of "1e10000000", which is obviously too large for double, the program fails with an assertion (BOOST_ASSERT). Can this somehow be changed to either fail by return code or throw an exception, which I can catch?
Or do I have to write my own double parser with spirit::x3?
Comment: You can use the `pos` argument to detect trailing characters
Comment: @Christophe Those functions support checking for that too. `std::stod` with the `pos` argument and `std::strtod` with the `str_end` argument.
Comment: I tested performance of std::strtod against boost::spirit::x3::double_ (micro-benchmark with nonius) and it takes about 50% longer to test with this one. Also it uses errno...
Will try std::from_chars next and post results here
Comment: Why not simply use [`std::stod`](https://en.cppreference.com/w/cpp/string/basic_string/stof) or [`std::strtod`](https://en.cppreference.com/w/cpp/string/byte/strtof)?
Comment: @Someprogrammerdude certainly because these functions are not bothered with trailing non numeric chars after a valid numeric entry (e.g. if locale expects a dot and not a comma, the programme might understand 3 when user may type 3,1415 and nobody would notice the error since the data would be considered as correct.
Answer: In the end, I created a custom parsing method which first uses boost::spirit::x3::int_ on the exponent part of the double's string representation (if it exists) and returns if the exponent does not satisfy the bounds of the double type. Afterwards I call the boost::spirit::x3::double_ parser on valid strings.


Serialization of 'Closure' is not allowed

Question: I am getting the following error on .../checkout/ID/order_information page after submitting payment details for Review.

Exception: Serialization of 'Closure' is not allowed in serialize() (line 14 of core/lib/Drupal/Component/Serialization/PhpSerialize.php).

I have tried to catch the exception with a try/catch block, but it  always gives that fatal error, if I unchecked My billing information is the same as my shipping information checkbox in the Payment information form.
I am using my custom payment method module for payment. Where should I look in the code to find what is causing the fatal error?
__construct() method :-
public function __construct(array $configuration, $plugin_id, $plugin_definition, EntityTypeManagerInterface $entity_type_manager, PaymentTypeManager $payment_type_manager, PaymentMethodTypeManager $payment_method_type_manager, TimeInterface $time) {
parent::__construct($configuration, $plugin_id, $plugin_definition, $entity_type_manager, $payment_type_manager, $payment_method_type_manager, $time);

  if ($this->getMode() === 'test') {
    $url = "url given here";
  }
  else {
    $url = "url given here";
  }

  try {
    $this->soapClient = new SoapClient($url);
  }
  catch (SoapFault $e) {
    throw new PaymentGatewayException($e->getMessage());
  }
}

Comment: Do you have a __construct() method of your class? If so, please add it to the post. It may be causing your issue.
Comment: `PhpSerialize.php` is drupal's `core` file, no construct method  for `PhpSerialize` class
Comment: No, in your custom module
Comment: Sorry, I have updated my question
Comment: This is probably because you are adding (possibly indirectly) something to a form that can't be serialized. In case it's your custom payment method class I suggest refactoring so the soap client is initialized lazily instead of in the constructor.
Answer: I believe this comes from loading a connection in the SOAP client, and storing it in memory with $this->soapClient. The problem is that the soap client cannot be serialized. Serialization is the process of turning something into a string, generally so it can be stored in a databse or a file or something, to be retrieved later. The SOAP connection is not something that can be stored, which is why you are facing the issue.
You could potentially store the SOAP client in the construct method, then make the connection using the client when you actually need it. I'm guessing that the client, without a connection, can probably be serialized. I may be wrong though, and you may need to call the soap client dynamically every time you need it.
Comment: taking out `$this->soapClient = new SoapClient($url);` from construct method has fixed this issue for now
Comment: Thank you for the hint of looking around my constructor. While writing a custom form controller extending ConfigFormBase commenting out temporarily all the lines setting a value to object attributes has solved this serialization issue of my Ajax requests. Now I reorganize my code to inject dependencies differently.
Answer: You might try adding use DependencySerializationTrait; to the class.
You could also try disabling caching if you can do without: $form_state->disableCache();


Select only if row not exists in joined table

Question: I have a db_select that selects row from t_project_proposal_writer table only if in joined t_project_milestone table row with milestone_id 10 is found:
<code>$query = db_select('t_project_proposal_writer', 'p')->fields('p');
$query->innerJoin('t_project_milestone', 'm', 'p.id=m.proposal_id');
$query->condition('p.initiative_nid', $node->nid)->condition('m.milestone_id', 10);
</code>
One project row can have 10 milestone rows. Now I need to do another query that selects only the rows from t_project_proposal_writer where milestone_id 10 not exists in joined t_project_milestone.
Is there any other possiblity to do that, instead of query all the projects and iterate throught them while checking if milestone 10 exists?
Answer: You can use isNull() method :
<code>$query = db_select('scald_atoms', 'a');
$query->fields('a', array('sid','title'));
$query->leftjoin('table_name','table_alias','table_alias.entity_id = a.sid');
$query->isNull('table_alias.mon_field_value');
$query->execute();
$query->fetchAllAssoc('nid');
</code>
with your example something like that should do it :
<code>$query = db_select('t_project_proposal_writer', 'p')->fields('p');
$query->leftjoin('t_project_milestone', 'm', 'p.id=m.proposal_id');
$query->isNull('m.milestone_id');
</code>
Comment: Instead the innerJoin do a leftJoin on "p.id=m.proposal_id AND m.milestone_id=10", and then you can check whether the milestone_id is NULL using the method proposed by @Kgaut.
Comment: It doesn't work - it will select nothing, because for one project are in milestone table 9 rows (with milestone_id from 1 to 9, but not 10).
Comment: Good point Mario, Thanks, my copy/paste of the original post was too fast ;).


How Pusher Connection is calculated?

Question: I am trying to understand the pricing shceme of Pusher. According to their pricing, the Boostrap allows 100 max. Connections. My question is this: if I have 10,000 daily visitors to my page, each one subscribed to a different channel to receive messages, how much I need to pay.
With realtime.co it's easier to understand because I know that I pay $1.00 per 1,000,000 messages without any other limitations. So I need to know how to calculate and estimate the total cost for my application, becaues I might designed it in a different way to reduce the costs.
I am considering choosing betwee, PubNub, Pusher and realtime.co, but knowing how to calculate estimated total cost is crucial for me because beginning to develop my application and going with a specific client/server library.
Answer: See the Pusher FAQ post: How are Connections Counted?
Comment: Link outdated. Current link:
https://support.pusher.com/hc/en-us/articles/360019428173-How-are-connections-counted-
Comment: Link again outdated: https://support.pusher.com/hc/en-us/articles/4412239949969-How-Are-Concurrent-Connections-Counted-

How Pusher Connection is calculated?


Errors while using opengl buffers using visual studio 2010 in windows7

Question: I am writing CUDA C codes and trying to use OpenGL for the visualization of simulation data.
I am using Visual Studio 2010 for development.
I was going through the "CUDA by example" book and tried to reproduce the examples in the book. So in the CUDA OpenGL interoperability section everything did work fine until I began making use of glGenBuffers. Other functions related to buffer objects, like glBindBuffer did not identify during compilation either. I googled a lot about this and there are many suggestions like including "GL/glext.h", which I all tried.
I would also like to mention that all of the headers (glut.h, glew.h, glxew.h and wglew.h) and lib files (glut.lib, glew32.lib, glew32s.lib) are present in the Visual Studio SDK lib and inc directories. In the VS 2010 Project → properties → linker → input → additional dependencies I added the library files in the following order:
cudart.lib
glut32.lib
glu32.lib
glew32.lib
glew32s.lib
freeglut.lib
opengl32.lib
Here's my program's source core for reference
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define GL_GLEXT_PROTOTYPES
#include <GL/gl.h>
#include <GL/glut.h>
#include <GL/freeglut.h>
#include <GL/glew.h>
#include <GL/glext.h>
#include <cuda.h>
#include <cuda_runtime.h>
#include <cutil.h>
#include <cudagl.h>
#include <cuda_gl_interop.h>

#define DIM 512;

GLuint bufferObj;
cudaGraphicsResource *resource;

    void display (void)
    {
    glClearColor(1.0f, 0.0f, 0.0f, 1.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    glLoadIdentity();
    glFlush();
    }
    void reshape (int width, int height)
    {
    glViewport(0, 0, (GLsizei)width, (GLsizei)height);
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(60, (GLfloat)width / (GLfloat)height, 1.0, 100.0);
    glMatrixMode(GL_MODELVIEW);
    }

    int main(int argc,char **argv)
    {
    cudaDeviceProp prop;
    int dev;

    memset(&prop,0,sizeof(cudaDeviceProp));
    prop.major = 1;
    prop.minor = 0;

    cudaChooseDevice(&dev,&prop);
    cudaGLSetGLDevice(dev);
    glutInit(&argc, argv);
    glutInitDisplayMode(GLUT_DOUBLE|GLUT_RGBA);
    glutInitWindowSize(512, 512);
    glutInitWindowPosition (100, 100);
    glutCreateWindow("Bitmap");
    glutDisplayFunc(display);
    glutReshapeFunc(reshape);
    glutMainLoop();
    glGenBuffers(1,&bufferObj);
    //glBindBuffer()
    }

When compiling, I'm presented with the following errors:
1> C:\ProgramData\NVIDIA Corporation\NVIDIA GPU Computing SDK 4.2\C\common\inc\GL/glut.h(574) : see previous definition of 'GLUT_GAME_MODE_DISPLAY_CHANGED'
1>C:\ProgramData\NVIDIA Corporation\NVIDIA GPU Computing SDK 4.2\C\common\inc\GL/glew.h(84): fatal error C1189: #error : gl.h included before glew.h
1>
1>C:\Program Files (x86)\MSBuild\Microsoft.Cpp\v4.0\BuildCustomizatio ns\CUDA 4.2.targets(361,9): error MSB3721: The command ""C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.2\bin\nvcc.exe" -gencode=arch=compute_10,code=\"sm_10,compute_10\" --use-local-env --cl-version 2008 -ccbin "c:\Program Files (x86)\Microsoft Visual Studio 9.0\VC\bin" -I"C:\ProgramData\NVIDIA Corporation\NVIDIA GPU Computing SDK 4.2\C\common\inc" -I"C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v4.2\include" -G --keep-dir "Debug" -maxrregcount=0 --machine 32 --compile -g -Xcompiler "/EHsc /nologo /Od /Zi /MDd " -o "Debug\OPENGL_PRAC_1.cu.obj" "C:\Users\umdutta\Desktop\SANKHA_ALL_MATERIALS\PRO GRAMMING_FOLDER\CUDA_OPENGL_C\2_PRACTICE_PROG_FOLD ER_(OPENGL_PRAC)\PROJ_NUM_1_OPENGL\PROJ_NUM_1_OPEN GL\OPENGL_PRAC_1.cu"" exited with code 2.
1>
1>Build FAILED.

Comment: There were also tons of warnings which I couldn't provide above.
Answer: It really helps to read the error messages. Your problem is, that you mindlessly include a bunch of headers. First, you need only glew.h, and don't use glext.h. Then it's also important to include the headers in the right order.
This should work:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

/* GLEW covers everything OpenGL.
   When you use GLEW you do not need any other OpenGL header */
#include <GL/glew.h>

/* GLUT is not part of OpenGL. Either use glut.h or freeglut.h – not both. */
#include <GL/glut.h>

#include <cuda.h>
#include <cuda_runtime.h>
#include <cutil.h>
#include <cuda_gl_interop.h>

BTW: cudagl.h is for the old, deprecated GL interaction API. If you use cuda_gl_interop.h you should not use cudagl.h.
Comment: Thank you for your reply. I think that I am just few steps away from getting everything correct. I am still getting one error. I am posting the errors in another comment.
Comment: 1>------ Build started: Project: PROJ_NUM_1_OPENGL, Configuration: Debug Win32 ------
1>Build started 8/22/2012 6:40:36 PM.
1>InitializeBuildStatus:
1>  Touching "Debug\PROJ_NUM_1_OPENGL.unsuccessfulbuild".
1>AddCudaCompileDeps:
1>Skipping target "AddCudaCompileDeps" because all output files are up-to-date with respect to the input files.
1>CudaBuild:
1>Skipping target "CudaBuild" because all output files are up-to-date with respect to the input files.
1>ManifestResourceCompile:
1>  All outputs are up-to-date.
1>LINK : fatal error LNK1104: cannot open file 'glew32.lib'
1>
1>Build FAILED.
Comment: @duttasankha: Usually the GLEW library file is named `glew.lib` (without the 32).
Comment: @datenwilf : But all the library files that are present in the lib folders are like glew32.lib and I have included all the lib files in C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Lib and also in the C:\ProgramData\NVIDIA Corporation\NVIDIA GPU Computing SDK 4.2\C\common\lib\Win32 folder. I already mentioned that I already included glew32.lib in VS 2010 Project → properties → linker → input → additional dependencies. Then why this error is showing?
Comment: @duttasankha: Well, the problem is, that the Linker is not able to either find glew32.lib or cannot make use of it. Make sure, that you installed the right version, matching your build toolchain (on the GLEW website you can download also a version for the MinGW toolchain which is incompatible to VC++).
Comment: @datenwilf : I am very glad to let u know that the error is gone. But still I am not confident that what I have done is correct or not and so I want to clarify with you. So,previously I didn't included the library path  "C:\ProgramData\NVIDIA Corporation\NVIDIA GPU Computing SDK 4.2\C\common\lib\Win32" in the project properties ->linker ->general ->Additional library directories. Later when I provided the path then the error is gone and builded successfully. Have I done it correct? Tons of thanks for all your help.


Push Notification com Firebase + regras de negócio

Question: Tenho que receber push notification do firebase, mas não são para todos os celulares que essas notificações serão enviadas. Meu app checa alterações em contratos, o usuário informa um número de CPF e o app busca no banco de dados informações sobre os contratos sob esse CPF, e esses contratos são alterados com frequência. Então eu queria que o usuário recebesse notificação no app quando algum contrato sob o CPF informado fosse modificado. Já pensei enviar push para todos os celulares, e de alguma forma no Ionic mostrar executar o push somente se o CPF for do usuário, mas achei muito errada essa solução.
Answer: Tenta o seguinte, no momento em o usuário se registrar tem como gerar um token do fcm pra ele:
<code>this.fcm.getToken().then(token => {
  console.log(token);
  //Aqui você pode armazenar esse token em algum lugar (Local Storage) e depois na hora de criar o usuário você passa o mesmo.
});
</code>
Depois na hora de enviar o push é só percorrer a lista de CPF que você quer, pegar e enviar as mensagens de acordo com o token de cada um.
Referencias:
https://ionicframework.com/docs/native/fcm/
https://firebase.google.com/docs/cloud-messaging/http-server-ref
Comment: Ah, acho que agora entendi. Eu geraria um token no fcm, depois na hora de criar a conta eu gravaria esse token la no firebase, depois eu varreria o documento de tokens e enviaria para os cadastrados para aquele CPF? É isso? Acho que dá certo mesmo. No firebase dá pra fazer isso com functions, neh? Vou dar uma lida nas referências que você me passou. Vlws.
Comment: Isso mesmo hehe, da uma olhada. É só vc atrelar o token pra um usuário
Comment: Entendi, mais ou menos. Como no firebase eu relacionaria o token que foi cadastrado para criar esse vinculo de token e cpf??  Vamos supor: app gerou um token = 34 , app que possui o CPF 2222, criou usuário pelo token gerado. Como no firebase vou saber que para o CPF 222 tenho que enviar para o app de token 34?


Commutator Subgroup of Free Group

Question: In the Combinatorial Group Theor-Lyndon, Schup, the authors say (start with)

Informally, a group is free on a set of generators if no relation holds among these generators except trivial relations that hold among any set of elements in any group.

With this definition of Free group, I tried to see why the commutator subgroup of free group $F_2=\langle a,b\rangle$ on two generators is not finitely generated. The hint given was that the set $\{[a^i,b^j]\colon i,j\in\mathbb{Z}\}$ is a (free) generating set for $[F_2,F_2]$.
As an example, I tried to see why $[a^2,b]$ and $[a,b]$ are free? Informally, if they were not free, then they would a non-trivial relation between them, and hence between $a,b$.
But, I am not satisfied myself with this informal proof of $[a,b]$ and $[a^2,b]$ are free.
How can we prove precisely this last statement? Should we go back to the precise definition of free groups?
Answer: Let $x=[a^2,b]=a^{-2}b^{-1}ab$ and $y=[a,b]=a^{-1}b^{-1}ab$.
Conisder all words of the form $uvw$, where $u,v,w \in \{x,x^{-1},y,y^{-1}\}$, and $v\ne u^{-1}$, $v \ne w^{-1}$. You will find that there is no such product $uvw$ in which the whole of $v$ cancels.
So the reduction of an reduced word $u_1u_2\cdots u_k$ with $u_i \in \{x,x^{-1},y,y^{-1}\}$ has length at least $k$ and so cannot reduce to the identity. So the subgroup generated by $x$ and $y$ is free.
The Nielsen proof that a subgroup of a free group is free involves an algorithmic method for reducing a generating set of a subgroup to a free generating set, so you could apply that method to examples like this.
Comment: You dropped the second $2$ from $x=a^{-2}b^{-1}a^2b.$
Comment: Yes thanks! I don't think I will edit the post, because that would take it to the top of the active questions list, which seems like overkill.

Commutator Subgroup of Free Group


How to scale a PDAnnotation?

Question: I have a pdf that has been passed to me with a signature (annotation) and I have to scale the pdf, but when I scale the pdf the annotation does not scale, and it comes out out out of shape. Any suggestions? I'll show you the code of the method and the pdf before and after
PDF BEFORE

PDF AFTER

Method
    public static byte[] adjustPages(byte[] content) {
    try (PDDocument pdf = PDDocument.load(content)) {
        float letterWidth = PDRectangle.LETTER.getWidth();
        float letterHeight = PDRectangle.LETTER.getHeight();
        PDPageTree tree = pdf.getDocumentCatalog().getPages();
        for (PDPage page : tree) {
            if (page.getMediaBox().getWidth() > letterWidth || page.getMediaBox().getHeight() > letterHeight) {
                float fWidth = letterWidth / page.getMediaBox().getWidth();
                float fHeight = letterHeight / page.getMediaBox().getHeight();
                float factor = Math.min(fWidth, fHeight);

                PDPageContentStream contentStream = new PDPageContentStream(pdf, page, PDPageContentStream.AppendMode.PREPEND, false);
                contentStream.transform(Matrix.getScaleInstance(factor, factor));
                contentStream.close();
                page.setMediaBox(PDRectangle.LETTER);
            }
        }
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        pdf.save(baos);
        return baos.toByteArray();
    }catch (IOException ioe) {
        return content;
    }
}

Comment: For each page you should not only scale the content stream but also all other coordinates on it, in particular the rectangles of each annotation thereon.
Comment: Can you give an example?
Answer: As already said in a comment, for each page you should not only scale the content stream but also all other coordinates on it, in particular the rectangles of each annotation thereon. In response you asked for an example.
You can extend your inner if block to
if (page.getMediaBox().getWidth() > letterWidth || page.getMediaBox().getHeight() > letterHeight) {
    float fWidth = letterWidth / page.getMediaBox().getWidth();
    float fHeight = letterHeight / page.getMediaBox().getHeight();
    float factor = Math.min(fWidth, fHeight);

    PDPageContentStream contentStream = new PDPageContentStream(pdf, page, PDPageContentStream.AppendMode.PREPEND, false);
    contentStream.transform(Matrix.getScaleInstance(factor, factor));
    contentStream.close();
    page.setMediaBox(PDRectangle.LETTER);

    for (PDAnnotation pdAnnotation : page.getAnnotations()) {
        PDRectangle rectangle = pdAnnotation.getRectangle();
        PDRectangle scaled = new PDRectangle(factor * rectangle.getLowerLeftX(), factor * rectangle.getLowerLeftY(),
                factor * rectangle.getWidth(), factor * rectangle.getHeight());
        pdAnnotation.setRectangle(scaled);
    }
}

(ScalePageWithAnnots test testForPereZix)
This will scale the rectangular area on the page into which the respective annotation is drawn.
Beware, though: Depending on the exact type of annotations in your documents, you'll have to scale other properties of the annotations, too.
On one hand there are a number of annotations with some extra coordinate information, e.g. the QuadPoints of link, markup, and redaction annotations.
On the other hand there are annotation properties relevant for a PDF viewer to create an annotation appearance if it does not have an accompanying appearance stream, e.g. border widths of annotations in general and DA font sizes for widgets of text fields.

How to scale a PDAnnotation?


PHP session is not setting

Question: I cannot understand why the PHP session is not working. It just simply won't set the session... How can I fix it?
<?php
    ini_set('display_errors', 1);
    ini_set('display_startup_errors', 1);
    error_reporting(E_ALL);

    session_name('dfm_session');
    session_start();

    if(isset($_SESSION['dfm_session'])){
        echo "yes";
    }
    else{
        echo "no";
    }
?>

Comment: first call session_start function then set $_SESSION['dfm_session'] = "some value"
Comment: Possible duplicate of [Data stored in Session but when fetch in other php file some objects is null](http://stackoverflow.com/questions/32836536/data-stored-in-session-but-when-fetch-in-other-php-file-some-objects-is-null)
Comment: `session_name()` sets the session name, it does not set a session variable with that key.
Comment: Yay they deleted their awful answers
Answer: Like jeroin and filip said, you are trying to check if the session variable dfm_session exists which it doesn't. So change your if statement to this:
if (session_status() == PHP_SESSION_ACTIVE

Or set that session value:
 $_SESSION['dfm_session'] = "some value")

Comment: He is starting the session right it's just his if statement

PHP session is not setting


How to access the static System.IO.File class from an MVC Controller?

Question: I try to delete file in controller:
Controller:
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult EliminarDocFotoContrato(int? DocFotoID)
{
DocumentosFotosContrato docFoto = db.DocumentosFotosContrato.Find(DocFotoID);
var nomeDocFoto = docFoto.CaminhoDocFoto;
var dir = Server.MapPath("/uploads");
var path = Path.Combine(dir, nomeDocFoto);
var result = "Documento / Foto apagada.";
return Json(result, JsonRequestBehavior.AllowGet);
}

The var nameDocFoto has the name file
The var dir has the directory
And the path has the nameDocFoto + dir (it's correct)
Now i need the code to delete file. Can i help me?
I just try something like this:
File.Delete(path);

but get this error:
Error   2   'System.Web.Mvc.Controller.File(string, string, string)' is a 'method', which is not valid in the given context D:\VS2010\Projects\MvcTesteLayout\MvcTesteLayout\Controllers\_DadosComerciais\ContratoController.cs 1511    17  MvcTesteLayout

Comment: Use `System.IO.File.Delete()`, as `File()` is a method of `Controller`.
Comment: and im using `using System.IO;`
Comment: @CesarMiguel and still have `File()` method from your controller.
Answer: In place of File.Delete(path) which, within the context of a controller will use the controllers version of the method; you need to use System.IO.File.Delete() exactly like that to access the system input/output version (which is the one you need). If you don't specify System.IO.File. before delete it will default to the controllers version even if you have a using statement for System.IO at the top of your file.


What is a good preparation for mathematical studies for someone who hasn't done mathematics in recent years?

Question: I was a computer science student but due to some unfortunate events I had to halt my studies. Now I'd like to continue studying, but somehow the sheer power and beauty of mathematics has struck me, and I'd really like to change my career path towards it.
To put it simple, I'd like ask you, the experts, for books and other material that I could use to hone my mathematics skills, in preparation for a full study of mathematics at my local university. It's been a while since I've had to use mathematics, so a refresher would be no luxury. Because I was enrolled in a computer science course, I do have some experience, but I'd really like to fill the gaps that have grown in my knowledge and be as prepared as I can be.
Any references are much appreciated!
Some related questions:

Second year mathematics textbook recommendations.

Are older mathematics textbooks still "valid"?
How to fill my mathematical gaps?
Comment: It would help to know what course you're taking and what it covers, and what applications of mathematics interest you, be it for the course or otherwise. For example, does computer science motivate any particular interest?
Comment: Thanks. That's two very varied lists of topics. You may wish to dip into general lists of maths books for ideas of what to read, such as [this](https://mathblog.com/mathematics-books/) one. It also looks like you *may* benefit more from reading a little of each of many books with very different topics, rather than a smaller variety in full. (Or it may not, depending on what you're after.) However, for now I doubt any advice can be given that's worthy of being an answer rather than a comment.
Comment: You'll get back the lost reputation if you delete, but I'll leave you to decide whether to close, delete or do neither.
Comment: Hi, J.G., thanks for the comment. It is [this trajectory](https://www.uantwerpen.be/nl/onderwijs/opleidingsaanbod/wiskunde-studeren/bachelor/studieprogramma/) I'm interested in, unfortunately only available in Dutch. I have several interests, and though things might change (and I know it is difficult and requires dedication) I've currently set my eyes on [fundamental mathematics](https://www.uantwerpen.be/en/education/education-and-training/master-of-mathematic/study-programme/).
Comment: I updated the question accordingly.
Comment: Thanks for the link! That's a really good list. I notice this question getting a lot of negative votes so maybe I'll close it as irrelevant.
Comment: **Wrong close reason? Close this as duplicate of https://math.stackexchange.com/q/22513**
Answer: 1 I had this textbook recommended for my first year BSc logic and set theory modules, this book won't make you a great mathematician on it's own but it will certainly teach you how to approach a lot of problems in a more mathematical way.
2 For the basics of calculus I would recommend Schaum's outlines. This fantastic series of books covers most topics and has countless worked problems to help with your understanding. As before this book won't make you an expert but since you're asking about a way in to Maths this is what I would recommend.
I hope you find these books interesting and engaging. The best advice I can give is to actively work on problems that you find challenging and to not be afraid of failure. Best of luck with your studies.
Comment: Thank you so much for your answer! I was getting afraid I was being inappropriate asking this question ... I'll leave it open for a little while to see if anyone else has recommendations and otherwise mark yours as accepted.
Comment: You're more than welcome.


How do I create an AJAX callback to Drupal video link?

Question: We have a number of videos which are hosted locally and are simple HTML5 video tags. We want to keep track of play clicks. So to be clear, we don't want to track clicks on the URL, we want click tracks on the video tag.
So I want to write a little jQuery() to get the onclick() and then call a Drupal function to update a Drupal entity to store the # of clicks and their source.
I've written AJAX in other environments (PHPBB, Wordpress) but not Drupal. I guess I'm looking for a 'starter kit' which demonstrates interfacing Drupal CRUD functions with js.
Answer: You need a route and callback defined in a hook_menu. Below is a kickstarter not a complete example ;)
function example_module_menu() {
  $items = array();

  // an endpoint to add an entity to the default flag_list
  $items['node/%/play'] = array(
    'page callback' => 'example_module_video_count',
    'page arguments' => array(1),
    'access callback' => 'user_access',
    'access arguments' => array('access content'),
    'type' => MENU_CALLBACK,
    'delivery callback' => 'ajax_deliver',
  );
  return $items;
}

Here is the callback
function example_module_video_count($nid = NULL) {
    /* do you stuff */
    $node = node_load($nid);
    $commands = array();
    /* add some ajax commands if required, look at ajax_command_invoke */
    return array('#type' => 'ajax', '#commands' => $commands);
}

Hit the URL from jQuery.ajax()
$.post("/node/1/play", function(data) {});

Comment: Thanks, I think a lightbulb just went on. So basically, I'm creating a dummy menu item because Drupal menu items have a built-in callback facility?
Comment: Yes hook_menu is the Drupal router. It's not got much to do with menus really. So in that sense it's not a dummy at all. Any path you want to create needs to be registered with hook_menu. And yes it has callbacks, arguments, permissions. Lots of stuff.
Comment: I know one is not supposed to 'thank' people, but... Thanks. This was one of those 'big concept' ideas I seem to need in my Drupal-adventure.


Como fazer o visual studio 2015 publicar apenas os arquivos que são mais atuais?

Question: Coloquei um projeto no visual studio 2015 para experimentar a ferramenta.
É uma aplicação asp.net mvc, faço a publicação dela direto no servidor por FTP.
Botão direito no projeto, publish, aí criei um profile FTP e falei para não excluir os arquivos antes de publicar.
No visual studio 2013 isso é o suficiente para ele não publicar tudo toda vez, no 2015 ele está publicando tudo, não deleta os arquivos como solicitado, mas sobre escreve todos eles.
Alguém sabe como fazer isso não acontecer?
Comment: Acho que não existe este comportamento que você quer por publicação normal. Só por Web Deploy o Visual Studio faz isso, mas de repente pode ser que eu precise pesquisar um pouco mais.
Comment: O que não entendo é pq o visual studio 2013 faz isso, um exemplo que consigo ver claramente é a dll log4net, ela fica dentro do bin, quando mando publicar pelo 2013 ele não a substitui, quando eu mando pelo 2015 ele substitui ela e todas as outras, já conferi a configuração do profile de ftp e os dois estão idênticos, isso que não entendo.
Comment: Não usei o VS2015 tempo suficiente pra te dar uma resposta, mas acredito que este comportamento ocorra pela segurança do *Build*. Antigamente era comum ocorrer erros muito esquisitos por esse comportamento de evitar a escrita, principalmente em DLL's de bancos de dados.
Answer: Essa funcionalidade que existia no VS2012 para publicação parcial por FTP não existe mais, foi removida. Acho que só no Web Deploy ainda é possível fazer a publicação parcial de acordo com modificações.
Outra forma, seria você fazer o upload por fora do VS (totalmente externo, ou até mesmo configurado em um "build step" de uma configuração de build específica, por exemplo a RELEASE ou criar uma configuração exclusiva para publicação)
Ai neste caso você teria que criar os scripts (pode até ser um outro projeto do VS, uma DLL que faz o trabalho sujo, pode ser um PowerShell, Node.JS, etc) para fazer a validação do que foi alterado e para fazer o upload.
Segue um exemplo usando GULP (Node.js) para monitorar as alterações: https://stackoverflow.com/a/39795922/1890220
Neste exemplo ele monitora os arquivos em tempo real e a cada modificação salva, ele efetua o envio (upload) do arquivo (pode ser catastrófico em ambiente de produção, já que você pode mudar algo para testar e ele fazer o upload em produção e parar sua aplicação toda, se não for bem configurado. Entenda bem configurado como selecionando apenas extensões/tipos de arquivos que não apresentam riscos a saúde da aplicação)


Simulations and The Entity Framework

Question: I'm coming from a background developing business applications so am used to MVC/n-Tier development.
Most of my applications have an architecture something like this:
GUI -> BL (which deals with entities) -> DAL (SQL DB)

Now, I'd like to write something which is a cross between an interactive story and a simulation - There is a persistent "world" which allows you to affect objects/NPCs. The state of objects/NPCs changes over time (sometimes as a result of your actions) which affects options later on. Think Oblivion but on a far smaller scale with no combat
I know that this is a massive project and I'm aware that I won't be able to achieve anything like modern game complexity by myself - But that doesn't mean I shouldn't try :)
My question is this: What sort of architecture should I use?
I'm going to need a library of story elements - Characters (NPCs), locations, transportation mechanisms, objects, quests, etc. etc.
I'd naturally tend to store these in a SQL database and access them using the entity framework.
I then need to be able to perform actions/events against these elements. This is where I get unclear. My usual method would be to have (say) an NPCManager which would have methods to manipulate NPC entities - But this doesn't work well with polymorphism.
I imagine that I;m going to need to use inheritance (an interfaces) to handle all the functionality that each element will have. eg:

Element (Base object for story elements - equivalent to Object in .Net)
NPC (Inherits Element)
Guard (Inherits NPC)
MountedGuard (Inherits Guard)
etc...

I can then say:

All elements would have an id
All NPCs would have an id and a name
All Guards would have an id, name and allegiance
All MountedGuards would have an id, name, allegiance and mount

This doesn't seem to mesh well with the EF - eg I can't have a method of NPCManager.GiveClothing(NPC as NPC, ClothingItem as Clothing) - because passing it a MountedGuard will fail (specifically, the class will be treated as an NPC which has no meaning in terms of a database...)
It also feels like I should be having methods to deal with MountedGuards specifically on the MountedGuard object - not on a Guard or NPC manager.
Should I have a set of entities for storing information and a completely separate set of classes to represent the object data stored by the entities. eg:
Entities.MountedGuard
Elements.MountedGuard - same properties as Entities.MountedGuard but also has a `Dismount()` method which affects the associated entity?

so should I be using non-POCO entities? or no entities at all (in which case, how do I define the "world"? I definitely don't want to have to do it all in code)
At present, I'm not even considering how these elements will be displayed to the user - for the time being, simple text seems likely
If someone could please point me at an appropriate architecture or some good resources.
Many thanks
Answer: My $0.02: you can have multiple inheritance strategies in entity framework, see here; this would allow you to model your domain pretty much however you want - I see especially Table-Per-Type (as opposed to table-per-concrete-type) being useful to you; this would mean that the inheritance structure in your code would be closely mirrored by the database in a pretty self-explanatory structure. Where you take it from there is up to you, but the point is you can then use pretty much the same strategies as you would with any object-oriented code.
Comment: Thanks, that looks like exactly what I need. Now I just need to figure out how to implement it using EF4 Code-Only :)
Comment: You're welcome! However, in researching this answer I came across this, which may or may not discourage you: http://samscode.com/index.php/2010/01/the-entity-framework-v1-and-v4-deal-breaker-tpt-inheritance/
Comment: It's funny but I _knew_ I'd read something about inheritance being broken in EF - That's partially what prompted me to post the question but I couldn't find it myself so assumed I must've been imagining it... Guess not. In any case, thanks for the solution and heads up :)

Simulations and The Entity Framework


Can't install curses package in pycharm [ Could not find a version that satisfies the requirement curses-win(from versions: none)]

Question: when i try to install curses-win package i head ERROR
ERROR: Could not find a version that satisfies the requirement curses-win (from versions: none)
Try to run this command from the system terminal. Make sure that you use the correct version of 'pip' installed for your Python interpreter
command output:
ERROR: Could not find a version that satisfies the requirement curses-win (from versions: none)
ERROR: No matching distribution found for curses-win
i've installed numpy and tensorflow clearly
Comment: There is no such thing as `curses-win`: https://pypi.org/project/curses-win/ returns error 404. What are you trying to install? Do you mean https://www.lfd.uci.edu/~gohlke/pythonlibs/#curses or https://pypi.org/project/windows-curses/ ?
Comment: i want to download curses
Comment: What do you mean by this: "Try to run this command from the system terminal. Make sure that you use the correct version of 'pip' installed for your Python interpreter"
_What command_ are you running at the terminal?
Answer: I faced with this problem when I tried to install cantools using pip on Ubuntu 16.04 LTS. I solved this issue by installing the pytest-runner package previously:
$ pip install pytest-runner --user


Custom class no work in input type checkbox after pagination DataTables

Question: Well, I have a table, por example:

            Título
            Data
            Delete
            Estatus

Title1

Data1

<button class="btn btn-danger eliminar"  id="785">Eliminar</button>

<input type="checkbox"  name="activoinactivo" id="123">

I want to add a personalized style to each entry and I do it this way
 var table = $('#datatable-example').DataTable();
    table.$('input[type="checkbox"]').each(function(){
        $(this).addClass('input-switch');
   });

the problem is that it does not work on the next page

What do I need to make it work properly?
Plugin URL: https://datatables.net/manual/
Comment: please add any custom css
Comment: It does not work either What I have to see because manually does not work.
Comment: I try it:
 but, not work.
Comment: what is in class input-switch?
Comment: your table has no id called datatable_example, it is #mytable
Comment: they have the same identifier, it was an error when copying and pasting
Comment: i think ,you have to reinitialize switch plugin everytime you click the page number
Comment: And how is that done? I do not understand :(
Answer: $('input[type="checkbox"]').each() will only target inputs that is visible (or exists) in the DOM. Look at createdCell and columnDefs. You do not provide your DT initialization, but basically you should go with :
columnDefs: [{
  targets: 3,
  createdCell: function(cell, cellData, rowData) {
    $(cell).find('input').addClass('input-switch')
  }
}]

By that you ensure you target all inputs, also those DT removes and injects to the DOM when you switch page. Besides that you have malformed markup

Title1

Data1

<button class="btn btn-danger eliminar"  id="785">Eliminar</button>

<input type="checkbox"  name="activoinactivo" id="123">

should be

  Title1
  Data1
  <button class="btn btn-danger eliminar"  id="785">Eliminar</button>
  <input type="checkbox"  name="activoinactivo" id="123">


Extra accidents in Roman Numeral analysis in Modulation by Max Reger

Question: I've been thumbing though Modulation by Max Reger and while he explains most of his notation, there is one thing about the figured bass in his Roman Numeral analysis that bothers me. For example, in the passage below when in the key of D# major, he puts a double sharp next to the V and I chord even though the double sharp would be in the key.

I'm really curious if this noation is standard  and if it is not what the alternative way to represent the passage is.
Comment: @SaggingRufus, knowing Max, he probably did write in D♯ at some point or another. D♯ & A♯ can make sense if the next stop in the journey is something like B, F♯ or C♯.
Comment: The extra sharp is probably just there to remind you, because no one writes music in D#
Comment: @NeilMeyer there definitely is and one of the only places you'll see it is in Modulation.
Comment: @SaggingRufus, about a year ago, I wrote a piece in D♯ minor. Does that count? It has still got double sharps... (It actually started in E♭ minor, but, given where it was going, it made sense to use the sharp key.)
Comment: He seems to be using the figures very much as if they were placed over the bass, eh?
Comment: There is no key called D# Major or A# Major. There is off course Bb and Eb Major. This notation is highly confused.
Comment: They spent so much time asking if they could, they didn't stop to think if they should! I mean they are just enharmonic equivalents of Bb and Eb. Once you get used to them they aren't so bad. They are a pain to sight read, but other than that not a huge issue.
Comment: @Patrx2 I agree, I was trying to say that you will probably never find a piece written in D# major. Once you start modulating anything is possible.
Comment: @Patrx2 neat. as a guitar player, I don't mind enharmonic equivalents. I have seen many pieces where people just use auto-transpose buttons because it is your are supposed to have a capo on whatever fret. Apparently other instrumentalists don't like these keys, but personally I don't mind them once you get used to reading them they are not any harder to play, they just suck to sight read.
Answer: If you look at his Example 1 (C major to G major), you'll see that he doesn't include the F♯ in the figures because it's assumed in G major. The same is true in Example 2, the F♯ and C♯ are assumed in D major, so there's no need to put them in the figures.
When he gets to Example 6, though, he needs to throw in those accidentals on the Neapolitan sixth, because, since he's resolving to F♯ major, he needs to clarify B♮ and D♮. (You've already addressed these two issues in your original question, I'm just setting the stage.)
The double-sharp first appears in Example 8, and the only possible explanation is that it's a courtesy accidental. Looking through the book, he always uses a courtesy accidental whenever there is a double-sharp; the example in your question is just one of many.
I've been looking for a citation to prove my answer, or maybe scores of his where he also follows this rule, but I've been unable to find one. But looking throughout the book, it must be that Reger only uses double-sharps as courtesy accidentals in the figures.
Comment: This makes perfect sense.  And why not? Even knowing the theory full well, it would be easy to forget an "implied" double sharp for the simple fact that we so rarely see them.  But, like all courtesy accidentals, it'd be better if they were in brackets.


Node Metatag data migration with the Migrate-Update\Drupal-Upgrade module

Question: I ask this for freshmen like myself, and others, who want to make sure they are making the best migrate-update possible:
I have created a local copy of a Drupal 7 site and have also created a brand-new Drupal 8 site. I have no content to migrate-update into the Drupal 8 site besides Nodes, their Metatag data, and a list of Redirects. I've already installed the modules Migrate update, Metatag, and Redirect (via GitHub) in the Drupal 8 site as well.
Is here something special that needs to be configured after the installation and enabling of the module in the Drupal 8 site to which I plan to migrate and upgrade content?
In other words, should I configure something in the D8 site Metatag module settings to insure a stable and correct migration of each node's meta title, description, and keywords from the D7 site?
Answer: Both redirect and Metatag have to provide their own migrations (migration templates), it's not something that you can just configure.
All you can do, if you don't know how to do it yourself is open issues for those projects and hope someone will do it. Or find someone you can pay that does it for you.
Comment: @benos I might be wrong, but I think the point of Berdir's second paragraph is that the templates don't currently exist. You need to code them yourself, or get someone else to code them. Probably not a trivial task, and probably not something that's going to fit in an answer here. Again though, might be wrong
Comment: Everything you need to know about what migration templates are is here: https://www.drupal.org/node/2527568.
Comment: @Clive is absolutely right. This is a development task that needs to happen, not something that can be answered away here.
Comment: *Nothing* that is not in core has a migration path out of the box. Every single module that has data needs to provide a migration path itself. In fact, not even a fair amount of things that are, like views. As it was mentioned in another issue, the migration is experimental and still in development.
Comment: Berdir, can you please edit the question and explain what are these migration templates? Do you mean it can only be done via Migrate update and cannot be copied separately?
Comment: I just want to comment this: Is is true to say that from the day Drupal rose up, there wasn't a free-for-all way to migrate Node metadata, and redirects? Both metadata and redirects are important for SEO, so it's hard for me to understand how this has never been part of any migrate module or plan for the sake of all users. Am I correct @Berdir ? Or I'm having a terrible mistake in that conclusion?
Comment: We also need to do Metatags migration in our project and exploring the ways to do it. Any pointers will be helpful?


Counting product pairs in a store whose difference in expenses is less than a certain amount in SQL

Question: I have a table with the serial number of each product, whether it is in stock (1- in stock, 0- not in stock), the level of revenue from the product and the level of expenses from the product in the store. I would like to write a query that counts all customer pairs (without duplication of the same pair), that the expense difference between them is less than NIS 1,000 and both are in stock or both are out of stock. Show the average income gap (approximately) of all pairs, how many such pairs are in stock And how much is not in stock.
Sample table:

serial
Is_in_stock
Revenu_ from_the_product
Expenses_from_the_product

1
1
27627
57661

2
0
48330
20686

3
0
26010
861

4
1
22798
37771

5
0
24606
8905

6
1
48311
6433

7
0
29929
6278

8
0
24254
8590

Unfortunately I am lost and unable to find a solution to my problem.
I was thinking of creating subqueries but could not find a suitable solution
The result should show something like this(Please do not refer to this data for illustration):

Average income gap (in absolute value) of all pairs
Quantity of pairs in stock
The amount of pairs that are not in stock

13
10
5

In addition it is very important that the count be done without duplicates of the same pair
Comment: Please mention your desired output.
Comment: I'm confused too where are  customer pairs?
Comment: Please could you explain the business logic to help us follow the SQL logic of what you're looking for? If you could post a fiddle it would help.
Comment: Hi
Thank you very much for responding to the help
I edited the question I hope it is now more understandable
Comment: @AidaMotay Definition of pair does not clear. Maybe this is the definition of pair `the expense difference between them is less than NIS 1,000 and both are in stock or both are out of stock`?
Answer: I have solved it in stored procedure.

Starting with variables definition.

Cursor iterate results of sorted list and check if the following condition it TRUE according to your definition of pair.
prev_exp - curr_Expenses_from_the_product < 1000 AND prev_in_stock - curr_Is_in_stock = 0

In case it TRUE counter increased by 1.

In the end I closing the cursor and returning the counter value.

* You can add more logic to procedure and return more columns.
** Usage of this procedure is just to call to stored procedure by its name.
Table creation:
CREATE TABLE A(serial INT(11), Is_in_stock INT(11), Revenu_from_the_product INT(11), Expenses_from_the_product INT(11));

Data insertion:
INSERT INTO A (serial,Is_in_stock,Revenu_from_the_product,Expenses_from_the_product) VALUES
  (1,1,27627,57661),
  (2,0,48330,20686),
  (3,0,26010,861  ),
  (4,1,22798,37771),
  (5,0,24606,8905 ),
  (6,1,48311,6433 ),
  (7,0,29929,6278 ),
  (8,0,24254,8590 );

Query:
BEGIN
    DECLARE finished INTEGER DEFAULT 0;
    DECLARE prev_exp int(11) DEFAULT 0;
  DECLARE prev_in_stock int(11) DEFAULT 0;
  DECLARE curr_Is_in_stock int(11) DEFAULT 0;
  DECLARE curr_Expenses_from_the_product int(11) DEFAULT 0;
    DECLARE duplications_counter int(11) DEFAULT 0;

    -- declare cursor for relevant fields
    DEClARE curs
        CURSOR FOR
            SELECT A.Is_in_stock,A.Expenses_from_the_product FROM A ORDER BY A.Expenses_from_the_product DESC;

    -- declare NOT FOUND handler
    DECLARE CONTINUE HANDLER
        FOR NOT FOUND SET finished = 1;

    OPEN curs;

    getRow: LOOP
        FETCH curs INTO curr_Is_in_stock,curr_Expenses_from_the_product;
        IF finished = 1 THEN
            LEAVE getRow;
        END IF;
        IF prev_exp - curr_Expenses_from_the_product < 1000 AND prev_in_stock - curr_Is_in_stock = 0 THEN
                SET duplications_counter = duplications_counter+1;
        END IF;
    END LOOP getRow;
    CLOSE curs;
-- return the counter
SELECT duplications_counter;
END

Result:
Counter: 5
Comment: Hi Is an explanation possible?
Answer: We can do this with two queries, without a procedure or user defined function

CREATE TABLE products(serial INT, Instock INT, Revenu INT, Expenses INT);

INSERT INTO products VALUES
  (1,1,27627,57661),
  (2,0,48330,20686),
  (3,0,26010,861  ),
  (4,1,22798,37771),
  (5,0,24606,8905 ),
  (6,1,48311,6433 ),
  (7,0,29929,6278 ),
  (8,0,24254,8590 );

✓

✓

SELECT a.serial,b.serial from
products a
join products b
on abs(a.expenses-b.expenses)<1000
where a.serial<b.serial
and a.instock=b.instock

serial | serial
-----: | -----:
     5 |      8

select count(a.expenses) 'number of pairs',
  avg(abs(a.expenses-b.expenses)) 'average difference',
  sum(case when a.instock=1 and b.instock=1 then 1 else 0 end) pairsInstock,
  sum(case when a.instock=0 and b.instock=0 then 1 else 0 end) pairsneitherStock,
  sum(case when (a.instock+b.instock)=1 then 1 else 0 end ) oneInStock
from products a
cross join products b
where a.serial < b.serial;

number of pairs | average difference | pairsInstock | pairsneitherStock | oneInStock
--------------: | -----------------: | -----------: | ----------------: | ---------:
             28 |         21362.1071 |            3 |                10 |         15

db<>fiddle here
Comment: Is one in stock on the condition that you placed it is present or does not exist or is there only one of the item?
Comment: I have used the column Is_in_stock as an indicator of in stock or not.


Consultar uma tabela inserindo "" em campo de número no Oracle

Question: Essa query precisa trazer o campo número do endereço entre ""
SELECT a.ds_endereco,
       a.nr_endereco,
       a.nm_bairro,
       c.nm_cidade,
       c.cd_uf,
       a.nr_cep,
       A.nr_fone,
       a.nr_celular
FROM   paciente A,
       cidade c
WHERE  a.cd_cidade = c.cd_cidade
       AND a.tp_situacao = 'N'
       AND a.cd_paciente <> 1
ORDER  BY 1

Answer: SELECT a.ds_endereco,
       '"' || TO_CHAR(a.nr_endereco) || '"',
       a.nm_bairro,
       c.nm_cidade,
       c.cd_uf,
       a.nr_cep,
       A.nr_fone,
       a.nr_celular
FROM   paciente A,
       cidade c
WHERE  a.cd_cidade = c.cd_cidade
       AND a.tp_situacao = 'N'
       AND a.cd_paciente <> 1
ORDER  BY 1

|| Operator
The Oracle/PLSQL || operator allows you to concatenate 2 or more strings together.

Ou em tradução livre:

O operador || do Oracle/PLSQL permite que você concatene 2 ou mais strings juntas.

TO_CHAR
The Oracle/PLSQL TO_CHAR function converts a number or date to a string.

Em tradução livre:

A função TO_CHAR do Oracle/PLSQL converte um number ou date para uma string.
Comment: Eu consegui quando adicionei dois ||


É possível incluir allegro em um Kernel feito em C?

Question: Estudo há algum tempo a construção de Sistemas Operacionais com bootloader em Assembly e kernel em C, e recentemente comecei a estudar allegro. Teoricamente é possível incluir a allegro ao kernel feito em C, mas eu quero saber na pratica... é possível?
Answer: Tecnicamente é. Qualquer biblioteca ou aplicativo pode ser implementado ou portado para dentro do kernel.
Mas qual a vantagem? Se a API do Allegro estivesse dentro do kernel e a aplicação que o utiliza do lado de fora, cada chamada ao Allegro envolveria uma syscall e uma troca de contexto, que é "cara" (demora bem mais que uma chamada de função normal).
É possível que o desempenho seja muito melhor com o Allegro fora do kernel, no mesmo espaço de memória que o jogo ou aplicativo. A não ser que você faça o jogo dentro do kernel também, aí na verdade seria uma regressão ao tempo do MS-DOS onde todo o código tem acesso direto ao hardware o tempo todo.
E como você deve saber, qualquer bug no código que está do lado de dentro do kernel faz o computador travar. Certamente o Allegro tem bugs...
No kernel só deveria estar código que precisa ter acesso total ao hardware, e precisa ter acesso controlado, seja por usuário ou por conjunto de permissões.
Também acaba ficando muito código no kernel que, por razões pragmáticas, funciona mais rápido se estiver lá. É o caso da maioria dos drivers de dispositivo, sistemas de arquivos, etc. Mesmo assim existem muitos drivers que funcionam em user mode, e há casos inclusive onde user-mode é mais rápido (por exemplo se um único aplicativo faz uso de uma placa de rede, o conjunto fica mais rápido se o próprio aplicativo conter o driver dessa placa).
Comment: Entendo. O que você recomenda para implementar imagens no kernel? No caso eu penso que é o primeiro passo para o desenvolvimento GUI
Comment: Na verdade teria de escolher em primeiro lugar a arquitetura do driver de video. Num projeto que participei ("teu passado te condena!") utilizava framebuffer do Linux, cujo driver está inteiramente dentro do kernel, então seria uma opção, fazer o driver de framebuffer do Alegro conversar diretamente com o driver do kernel sem syscall.


A problem about multiples.

Question:
For any positive integers $a$, $ b$, if $ab+1$ is a multiple of $16$, then $a+b$ must be a  multiple of $p$. Find the largest possible value of $p$.

I have no idea how to solve this. Please help. Thank you.
Comment: You mean 'biggest' instead of 'least', no?
Comment: Re berci, you are right.
Answer: Observe that $(ab,16)=1$
If $a=16A+1,b=16B-1\implies a+b=16(A+B)$
If $a=16A+3,b=16B+5\implies a+b=16(A+B)+8$
If $a=16A+7,b=16B+9\implies a+b=16(A+B+1)$
So,  in all the cases,  $8\mid (a+b)$
As to find the pairs, as $ab\equiv -1\pmod {16}$ ,so $a(-b)\equiv 1$ i.e.,$-b$ is inverse of $a\pmod {16}$.
we know by this, $\lambda(16)=4\implies a^4\equiv 1\pmod {16}\implies a^{-1}\equiv a^3$
For example, $a=3,a^3=27\equiv -5\pmod {16}\implies b\equiv 5$
But $16$ is small enough to allow mental arithmetic, we just need to multiply $m,n$ where $m\le n<16$  and $(mn,16)=1$
Comment: $8$ is indeed the maximum value of $p$. No bigger value is possible, because $ab+1=16$ has $a+b=3+5=8$ as maximum.
Comment: @barto, when we know $8|(a+b)$ is it tough to identify $2$ as the smallest?
Comment: @bhattacharjee, indeed. That means $8$ is the only possible value.
Comment: @barto But as Berci points out, the OP is asking for the _least_ possible value of $p$, which is clearly 1, or if $p$ is prime, 2.
Comment: @barto How $8$ can be the only possible value? It can be $1,2,4$ also? Also, $(a+b)$ can be $16 (15+1 or 7+9), 32(31+1)$ etc.
Comment: Sorry, that was my fault, I mean the GREATEST possible value of p.
Comment: @ lab bhattacharjee: How do you find those pairs of a, b?
Comment: @jasoncube, I've added the explanation in the answer.
Comment: @labbhattacharjee Aren't we missing $a = 16A + 11$ and $b = 16B + 13$ (or equivalently, $b = 16B - 3$)? In this case $a + b = 16(A + B) + 8$, so we get the same result.
Comment: @RichardSullivan, agreed. I've missed $16A+11$ or $16C-5$ for the ease of calculation. Now $(-5)^3=-125\equiv 3\implies b\equiv -3$. Thanks.
Answer: We can consider the problem in $\mathbb{Z}_{16}$.
Then $ab+1$ is a multiple of 16 means that $\overline{ab+1}=\overline{0}$, then $\overline{a}\overline{b}=\overline{ab}=\overline{15}$, in $\mathbb{Z}_{16}$, $\overline{15}$ only has four decompositions, means $\overline{15}=\overline{1}\cdot\overline{15}=\overline{3}\cdot\overline{5}=\overline{7}\cdot\overline{9}=\overline{11}\cdot\overline{13}$.
So $\overline{a+b}=\overline{a}+\overline{b}$ only has four cases, means $\overline{1}+\overline{15}=\overline{0}$, $\overline{3}+\overline{5}=\overline{8}$, $\overline{7}+\overline{9}=\overline{0}$ and $\overline{11}+\overline{13}=\overline{8}$.
So $\overline{a+b}=\overline{0}$ or $\overline{a+b}=\overline{8}$, $a+b$ must be a multiple of 8 (the case that $a+b$ is a multiple of 16 is include in this case), the least possible value of $p$ is 8.
Answer: Let $ab\equiv-1\pmod {2^k}$
If $a=1,b\equiv-1= c2^k-1,a+b=c2^k$, the minimum value of $c$ is $1$.
So, $p$ must divide $2^k$, so can not have any odd factor.
Now, $b\equiv -\frac 1 a\pmod {2^k}$ as $ab\equiv-1$
So, $b\equiv -\frac 1 a\pmod {2^t}$
Let $2^t||(a+b)$ clearly, $t\le k$
So,$a\equiv -b \pmod{2^t}\equiv \frac 1 a \implies a^2\equiv 1\pmod{2^t}$ as $(a,2)=1$
As $a$ is odd, $=2d+1$ (say), $a^2-1=8\frac{d(d+1)}2\implies 8\mid (a^2-1) ∀$ odd $a$.
Now $\frac{d(d+1)}2$ will be even if $4\mid d(d+1)\implies d=4e$ or $d+1=4e$ as $(d,d+1)=1$
So, $\frac{d(d+1)}2$ will be odd if $d=4e+1$ or if $d=4e+2$
If $d=4e+1,a=2d+1=8e+3,a^2-1=64e^2+48e+8=8(8e^2+6e+1)$
If $d=4e+2,a=2d+1=8e+5,a^2-1=64e^2+80e+24=8(8e^2+10e+3)$
In a more compact way,if $a=8e\pm 3, a^2-1=(8e\pm 3)^2-1=64e^2\pm48c+8=8(8c^2\pm6c+1)$
$\implies 2^3||(a^2-1)$ if $a\equiv  3,5\pmod 8$
$\implies p=8  ∀ k\ge 3$  as $k=2\implies a+b=4c$
Comment: @jasoncube, could you please have look into this generalized  & simpler(?) answer, unless you've already one?

A problem about multiples.


Processing huge yaml-files via php

Question: I need to process a huge yaml-file - which is 450 MB - to get the data in a database. Therefore I tried to use "spyc". But the file is too big.
Every chapter has the line --- !de.db.net,DB::Util::M10lDocument. And I need the content of every chapter as an array. Therefore I tried to use spyc. But the complete file is too big for that. I don't know how to split for those chapters.
Is it possible to read the complete file just block by block?
Does anyone have an idea how to work with that big file?
Comment: Without an example of the content, it's hard to say. In theory the YAML format should make it reasonably trivial to break things down by going line by line and cutting off at certain events, e.g. a new document or new scalar.
Comment: If the chapters are small enough, you can simply use fgets until you hit the start of a new one, then parse this individual chapter.
Comment: Yes, the chapters are small enough, but I don't know how to parse the chapter as you described. As far as I know spyc just reads a file - and this is too big. I'm open minded for another parser. I would be very thankful if you could write an example of your described solution.
Answer: --- is the document boundary marker for a YAML stream. Using a YAML parser that processes the file as a stream should allow you to process the file in document sized chunks as long as each document is small enough to fit in available memory.
The yaml_parse_file function provided by the yaml PECL extension includes the ability to parse a single document out of a stream of documents. There is no built in method to iterate over the documents (eg foreach support) but you could implement your own loop that fetched sequential documents and halted when yaml_parse_file returns false indicating that the requested document was not found.
<?php
$docNum = 0;
while (false !== ($doc = yaml_parse_file('example.yaml', $docNum))) {
    var_dump($doc);
    $docNum++;
}

Processing huge yaml-files via php


Prove there exists $k$ s.t. $\log_2(n)-\frac{n-1}{n}\log_2(n-1)\le k $

Question: Prove for $n\ge 2$ there exists constant $k$ such that
$$
\log_2(n)-\frac{n-1}{n}\log_2(n-1)\le k
$$
for $n=2,\dots,8$ I see that LHS equals below values respectively
<code>1 0.918296 0.811278 0.721928 0.650022 0.591673 0.543564
</code>
So I guess $k=1$ ? However I not good at math so I cannot prove easily. I tried proving by contradiction but failed : assume that's not the case, that means there exists $u\ge 2$ such that
$$
\log_2(u)-\frac{u-1}{u}\log_2(u-1)> 1\\
\implies \frac{1}{u\ln 2}-\frac{u-1}{u}\frac{1}{(u-1)\ln 2}+\frac{u-(u-1)}{u^2}\log_2(u-1)> 0 \\
\frac{1}{u\ln 2}-\frac{1}{u\ln 2}+\frac{1}{u^2}\log_2(u-1)> 0 \\
\frac{1}{u^2}\log_2(u-1)> 0
$$
where I derived both sides (I'll be even more clueless if I don't), but this isn't going anywhere... I'd appreciate some help.
Comment: @Angelo thanks pretty cool to see binomial expansion used here
Comment: C.C., could you read my answer? Tell me if you like it.
Comment: C.C., you are welcome!
Answer: Consider the real-valued function $f(x) = \log_2{x} - \frac{x - 1}{x}\log_{2}(x - 1)$. Its domain is $(1, +\infty)$. If we can prove that this function is decreasing for $x \ge 2$, then we'll be able to take $k = f(2) = 1$.
Indeed, we have
$$f'(x) = -\frac{\log_2(x - 1)}{x^2}$$
Now verify when $f'(x)$ is negative, meaning that $f(x)$ is decreasing.
Answer: HINT: try to start with $f(n) = \log_2(n) - \frac{n-1}{n} \log_2(n-1)$, then:
$$
2^{f(n)} = \frac{n}{(n-1)^{\frac{n-1}{n}}} = \frac{n}{(n-1)}\times (n-1)^{1/n}
$$
Prove that both of the terms are bounded.
Answer: At the outset, it's worth paying attention to the order of quantifiers. The question in the title is about finding a good $k$ for all $n$. Yet, you asked

Prove for $n≥2$
there exists constant $k$
such that $$\log_2(n)-\frac{n-1}{n}\log_2(n-1)\le k.$$

Which is a much simpler task, just $k=\log_2(n)-\frac{n-1}{n}\log_2(n-1)$ will do the job. Therefore, I'll assume it's about $k$ independent from $n$. Then, $$\begin{split}
\log_2n-\frac{n-1}{n}\log_2(n-1)&=\log_2 \sqrt[n]{\frac{n^n}{(n-1)^{n-1}}}\\
&=\log_2 \sqrt[n]{\frac{n^{n-1}}{(n-1)^{n-1}}\times n}\\
&\le \log_2 2\sqrt[n]{n}.
\end{split}
$$ Whereas the last inequality comes from observation $$\Big(\frac{n}{n-1}\Big)^{\frac{n-1}{n}}\le 2,$$ which is the result of a simple observation that $x\le 2^x$, and set $x=n/(n-1)$. And finally we can say that $\sqrt[n]{n}$ is also bounded since, $\sqrt[n]{n}\to 1$.
Answer: Working with natural logarithms
$$A_n=\log_2(n)-\frac{n-1}{n}\log_2(n-1)$$ $$A_n=\frac 1 {\log(2)}\left(\frac{\log (n)+1}{n}-\sum_{k=2}^\infty \frac 1{k(k-1)n ^k} \right)~<~\frac{\log (n)+1}{n\,\log(2)}$$
Now, you could use any upper bound of $\log(x)$ (have a look at table $(3)$ in this paper) to finish.
Answer: Here is another way to prove that
$\log_2n-\dfrac{n-1}n\log_2(n-1)\leqslant1\quad$ for any $\;n\in\Bbb N\,\land\,n\geqslant2\,.$
Proof :
For any $\;n\in\Bbb N\,\land\,n\geqslant2\,$ it results that
$\log_2n-\dfrac{n-1}n\log_2(n-1)=\dfrac1n\log_2\left[\dfrac{n^n}{(n-1)^{n-1}}\right]=$
$=\dfrac1n\log_2\left[\dfrac{\big((n\!-\!1)\!+\!1\big)^{\!n}}{(n-1)^{n-1}}\right]=\dfrac1n\log_2\left[\dfrac{\sum\limits_{k=0}^n\binom nk(n-1)^k}{(n-1)^{n-1}}\right]=$
$=\dfrac1n\log_2\left[\dfrac{1\!+\!n(n\!-\!1)\!+\!\sum\limits_{k=2}^{n-1}\binom nk(n\!-\!1)^k\!+\!(n\!-\!1)^n}{(n-1)^{n-1}}\right]=$
$=\dfrac1n\log_2\left[\dfrac{1\!+\!(n\!-\!1)^2\!+\!(n\!-\!1)\!+\!\sum\limits_{k=2}^{n-1}\binom nk(n\!-\!1)^k\!+\!n(n\!-\!1)^{n-1}\!-\!(n\!-\!1)^{n-1}\;}{(n-1)^{n-1}}\right]\leqslant$
$\require{cancel}\!\leqslant\!\dfrac1n\log_2\left[\dfrac{1\!+\!(n\!-\!\!1)^{n-1}\!+\!\color{#8888FF}{\cancel{\color{black}{\!(n\!-\!\!1)^{n-1}}}}\!\!+\!\!\sum\limits_{k=2}^{n-1}\!\binom nk(n\!-\!\!1)^k\!+\!n(n\!-\!\!1)^{n-1}\!-\!\!\color{#8888FF}{\cancel{\color{black}{(n\!-\!\!1)^{n-1}}}}}{(n-1)^{n-1}}\right]\!=$
$=\dfrac1n\log_2\left[\dfrac{\binom n0\!+\!\binom nn(n\!-\!1)^{n-1}\!+\!\sum\limits_{k=2}^{n-1}\binom nk(n\!-\!1)^k\!+\!\binom n1(n\!-\!1)^{n-1}\;}{(n-1)^{n-1}}\right]\leqslant$
$\leqslant\!\dfrac1n\log_2\left[\dfrac{\binom n0(n\!-\!1)^{n-1}\!+\!\binom nn(n\!-\!1)^{n-1}\!+\!\sum\limits_{k=2}^{n-1}\binom nk(n\!-\!1)^{n-1}\!+\!\binom n1(n\!-\!1)^{n-1}\;}{(n-1)^{n-1}}\right]\!=$
$=\dfrac1n\log_2\left[\dfrac{\color{#8888FF}{\cancel{\color{black}{(n-1)^{n-1}}}}\!\!\sum\limits_{k=0}^n\binom nk}{\color{#8888FF}{\cancel{\color{black}{(n-1)^{n-1}}}}}\right]=\displaystyle\dfrac1n\log_2\left[\sum\limits_{k=0}^n\binom nk\right]=$
$=\dfrac1n\log_2\bigg[\big(1+1\big)^n\bigg]=\dfrac1n\log_22^n=1\,.$


Compute equivalence classes of equivalence relation

Question: I have already proven that the  relation $R=\{(x,y) \in \mathbb Z \times \mathbb Z \mid x+y\text{ is even}\}$ is an equivalence relation by showing reflexive, symmetric, and transitive properties of the relation. But when I try to find the equivalence classes of it I'm stuck.
Since $x$ and $y$ are either both even or both odd, does this simply come down to the equivalence classes of "congruence modulo $2$"?
Comment: What are all the numbers equivalent to $0?$
Answer: Your intuition is correct. To describe the equivalence classes explicitly, it often helps to find the equivalence classes of numbers that are easy to work with.
Let's find, for example, the equivalence classes $[0]$ and $[1]$.
$0+a$ is even for which integers $a$? All these will form $[0]$.
$1+b$ is even for which integers $b$? All these will form $[1]$.
Are there any other equivalence classes? (You can be sure you've found them all when your equivalence classes form a partition of $\Bbb Z$.)
Answer: Suppose $x+y$ is even. What does that tell you about $x$ and $y$? HINT: Write down some examples . . .
Comment: it would either tell that both x and y are even, or both x and y are odd. ex. 2+4 = 6. 3+5 = 8. etc...
Comment: So from this, can you tell me what the equivalence classes are? (Hint: there's two of them . . .)
Answer: $x+y$ is even if and only if $x-y$ is even because $x-y=(x+y)-2y$. So the even integers form one equivalence class, and the odd integers form the other.


File name/path of javax.xml.transform.Source object

Question: I have an input supplier that extends Source: InputSupplier<? extends Source> supplier and I would like to get the file name (and path) of the source.
Currently the Source is always a StreamSource, so I don't know if that makes it more or less challenging.
Comment: The source does not necessarily refer to a file or path... it could just be a stream from a remote location. So it all depends on your code (the way you create the source).
Comment: @home What other code could I show?
Comment: You can't... What are you trying to do that means you want to get the file name / path?
Answer: StreamSource.getSystemId returns the system identifier that was set with setSystemId, or null if setSystemId was not called. Examples:
System.out.println(new StreamSource(new File("1.xml")).getSystemId());
System.out.println(new StreamSource(new FileReader("1.xml")).getSystemId());
System.out.println(new StreamSource(new FileReader("1.xml"), "d://workspace/x/1.xml").getSystemId());

prints
file:/D:/workspace1/x/1.xml
null
d://workspace/x/1.xml

So it depends on how StreamSource was created.


continuity, uniformly continuous

Question: I was wondering if you could help me with this:
$$
f(x)=\begin{cases}
x^2\sin\left(\frac{1}{x}\right) & \text{ for } x \ne 0\\
0 & \text{ for } x=0
\end{cases}.
$$
I need to observe that f is continuous on $\mathbb{R}$ and then explain why it is uniformly continuous bounded subset of $\mathbb{R}$.
Finally, is $f$ uniformly continuous on $\mathbb{R}$? Do I take $f'(x)$?
I know that I should be using the theorem for f being continuous, which says that f is continuous for some $x_0$ and then evaluating it for the entire $\text{dom}(f)$.
Apologizes for the format of my post!
Comment: What do you mean by "explain why it is uniformly continuous bounded subset of $\mathbb{R}$"? It sounds like you're supposed to prove the range of this function is bounded, which is not the case. Perhaps you meant to write $f(x) = x \sin(\frac{1}{x})$ for $x \neq 0$?
Comment: Perhaps the OP meant to say "it is uniformly continuous *on a* bounded subset of $\mathbb{R}$"?
Comment: this is a similar question where the idea may be borrowed
http://math.stackexchange.com/questions/223147/simple-calculus-inquiry/223191#223191
Answer: Hint I'll prove continuity at $x=0$.
To prove it is continuous at zero, you need to prove $\lim_{x\to 0} f(x)=f(0)$.
You are given $ f(0)=0 \,.$ You need to prove the limit of the function is $0$ too. Now, notice this,
$$ \left |x^2\sin\left(\frac{1}{x}\right) \right|\leq |x^2|=x^2 \implies  x^2\sin\left(\frac{1}{x}\right) \to 0 \quad \mathrm{as}\,\,\, x\to 0 \,, $$
By the sandwich theorem. Note that the fact that $|\sin(x)|\leq 1$ has been used.
Answer: Mhenni has already proved continuity. To prove$ f$ is uniformly continuous on any bounded subset of $\mathbb{R}$, use the fact that a continuous function on a compact set is uniformly continuous on that set. Note that a bounded set in $\mathbb{R}$ is contained in a bounded interval, which is compact.
To prove that $f$ is uniformly continuous on all of $\mathbb{R}$: note that $\displaystyle\lim_{x\to\infty} x^2 \sin(1/x) = \lim_{|x|\to\infty} x \frac{\sin(1/x)}{1/x} = x$ and $x$ is a uniformly continuous function. You can formalize this relatively easily.
Comment: You can observe that $|f^{'}(x)|<2$ is bounded fore every x in $\mathbb{R}$ and so $f(x)$ is a lipschitz function and then it is uniformly continuous.

$$f^{'}(x)= 2*x*sin(1/x)+x^2*cos(1/x)*(-1/x^2)$$
Comment: Also we note that $f^{'}(x)$ has the point of discontinuity of the second species in x = 0 (in fact, the derivative may have only types of discontinuity of the second species)

continuity, uniformly continuous


3.85 of LADR by Sheldon Axler

Question: I'm a little confused on the proof of the implication of $(c)\to(a)$. In his proof, Axler says to take two elements $u_1, u_2$ of $U$ such that $v+u_1=w+u_2$. Whatever follows after that, I understand, but this beginning I don't. How can we just suppose this from $(c)$?
Here is the theorem:
Suppose $U$ is a subspace of $V$ and $v,w\in V$. Then, the following are equivalent.
(a) $v-w\in U$
(b) $v+U=w+U$
(c) $(v+U)\cap(w+U)\neq \varnothing$
Comment: Hi Maries, [here](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) is a useful guide to learn how to typeset equations in MathJax!
Comment: Thanks, I'll be sure to use this from now on :)
Answer: Axler is assuming that $(v+U)\cap(w+U)\ne\emptyset$. So, take a vector $z\in(v+U)\cap(w+U)$. Then $z=v+u_1$ for some $u_1\in U$ (since $z\in v+U$) and $z=w+u_2$ for some $u_2\in U$ (since $z\in w+U$). But then $v+u_1=w+u_2$.
Comment: I'm glad I could help.
Comment: Thank you so much!
Answer: If you have that $(v+U)\cap (w+U)\neq \emptyset$, this means that exists an element $r\in (v+U)\cap (w+U)$ such that is in the intersection, and by the description of the set $v+U$, $r$ can be seen of the form $v+u_1$ for an $u_1\in U$. Analogously, since $r\in w+U$, it also can be seen as $w+u_2$ for an $u_2\in U$.
This imply that $v+u_1=r=w+u_2$, so $v-w=u_2-u_1$, and since $u_1,u_2\in U$, you have that $v-w=u_2-u_1\in U$.
Comment: Thank you so much!
Comment: It's always a pleasure to be able to help :).

3.85 of LADR by Sheldon Axler


Conditional distributions of correlated normal random variables

Question: Suppose that $X$ and $Y$ are normally distributed with mean zero and nonzero covariance. I want to know the distributions of $X | X - Y > c$ and $Y | X - Y > c$, which I believe should be jointly distributed as a multivariate normal distribution. I can compute the conditional expectations, using this answer and this answer, but I also want to know the variances and covariance.
That is, I want to compute
$$\text E[X | X - Y > c], \quad \text E[Y | X - Y > c],$$
$$\text {Var}(X | X - Y > c), \quad \text {Var}(Y | X - Y > c),$$
and
$$\text {Cov}(X, Y | X - Y > c).$$
How do I go about this?
Answer: If $X$ and $Y$ both have unit variance, then the formulas for this may be unilluminating but at least there are some formulas.
The trick is to express everything as integrals in terms of the variables $U=(X+Y)/\sqrt{2}$ and $V=(X-Y)/\sqrt{2}$.
This leads to a conditional covariance of
$$K=\rho
+\frac{(1-\rho)e^{-a^2}}{4\pi\, \Phi^2(-a)}
-\frac{(1-\rho)e^{-a^2/2}a}{\sqrt{2\pi}\, \Phi(-a)}$$
where $a=c/\sqrt{2(1-\rho)}$, $\rho$ is the correlation between the original $X$ and $Y$, and $\Phi$ is the standard normal cdf.
The conditional variances are both equal to $1+\rho-K$.


Conda dependency resolution error unintelligible

Question: Can anyone help me to understand how this is supposed to be read?  Whenever I get dependency resolution errors from Conda, I wind up just having to basically do my own investigation, because the error message (though it looks like it's really trying to be helpful) basically feels useless.
Would love to better understand how I'm supposed to read this.
UnsatisfiableError: The following specifications were found to be incompatible with each other:

Package libffi conflicts for:
python=3.7 -> libffi[version='>=3.2.1,<3.3.0a0|>=3.2.1,<4.0a0']
Package python conflicts for:
workflow -> python
Package pip conflicts for:
python=3.7 -> pip
Package xz conflicts for:
python=3.7 -> xz[version='>=5.2.3,<5.3.0a0|>=5.2.4,<5.3.0a0|>=5.2.4,<6.0a0']
Package libstdcxx-ng conflicts for:
python=3.7 -> libstdcxx-ng[version='>=4.9|>=7.2.0|>=7.3.0']
Package jinja2 conflicts for:
workflow -> jinja2
Package readline conflicts for:
python=3.7 -> readline[version='>=7.0,<8.0a0|>=8.0,<9.0a0']
Package pygraphviz conflicts for:
workflow -> pygraphviz
Package pyfunctional conflicts for:
workflow -> pyfunctional[version='>=1.2.0']
Package click conflicts for:
workflow -> click[version='>=7']
Package snakemake conflicts for:
workflow -> snakemake[version='>=5.3.0']
Package networkx conflicts for:
workflow -> networkx
Package openssl conflicts for:
python=3.7 -> openssl[version='>=1.0.2o,<1.0.3a|>=1.0.2p,<1.0.3a|>=1.1.1a,<1.1.2a|>=1.1.1b,<1.1.2a|>=1.1.1c,<1.1.2a|>=1.1.1d,<1.1.2a']
Package zlib conflicts for:
python=3.7 -> zlib[version='>=1.2.11,<1.3.0a0']
Package sqlite conflicts for:
python=3.7 -> sqlite[version='>=3.24.0,<4.0a0|>=3.25.1,<4.0a0|>=3.25.2,<4.0a0|>=3.25.3,<4.0a0|>=3.26.0,<4.0a0|>=3.27.2,<4.0a0|>=3.28.0,<4.0a0|>=3.29.0,<4.0a0|>=3.30.1,<4.0a0']
Package libgcc-ng conflicts for:
python=3.7 -> libgcc-ng[version='>=4.9|>=7.2.0|>=7.3.0']
Package pygments conflicts for:
workflow -> pygments
Package tk conflicts for:
python=3.7 -> tk[version='>=8.6.7,<8.7.0a0|>=8.6.8,<8.7.0a0|>=8.6.9,<8.7.0a0']
Package psutil conflicts for:
workflow -> psutil[version='>=5.6.3']
Package bzip2 conflicts for:
python=3.7 -> bzip2[version='>=1.0.6,<2.0a0']
Package ncurses conflicts for:
python=3.7 -> ncurses[version='>=6.1,<6.2.0a0|>=6.1,<7.0a0']

Comment: I've found that most of the time it is utterly useless and completely fails to identify the underlying conflicts. On the rare exception that it works it shows at least two dependency strings (`dependent-pkg -> dependency_pkg[version constraints]`) where the version constraints are incompatible on some package. I definitely regard this "feature" as a work-in-progress.
Answer: Package libffi conflicts for:
python=3.7 -> libffi[version='>=3.2.1,<3.3.0a0|']

I think this means you are trying to install python 3.7 which requires libffi version to be >=3.2.1 and <3.3.0a0 (or >=3.2.1 and<4.0a0). But the libffi version you installed in the past was required to be outside of this range of compatible versions (e.g. you required it to be <3.2).
Maybe post the command that generated the error and the output of conda list (assuming you are trying to install/upgrade in the current environment).
Comment: Perhaps a more useful output to include would be the YAML from `conda env export --from-history`. That would tell us explicit specs. Things that don't have explicit specs are freely adjustable (i.e., wouldn't generate a conflict), and you can't tell what is explicit in `conda list` alone.


Proving orthogonality of vectors in a complex vector space

Question: I'm taking a course in Real Analysis and have come across the following question which I initially thought looked quite simple:
Let $X$ be an inner product space over $\mathbb{K}$ ($\mathbb{K} = \mathbb{C}$ or $\mathbb{R}$) Show that x and y are orthogonal if and only if $||\lambda x  + \mu y||^2 = ||\lambda x||^2 + ||\mu y||^2$ for all $\mu, \lambda \in \mathbb{K}$.
I have proven the statement in one direction (starting with orthogonality and ending up with $||\lambda x  + \mu y||^2 = ||\lambda x||^2 + ||\mu y||^2$). However, I seem to be getting stuck trying to go in the other direction.
The following is what I have so far:
$||\lambda x  + \mu y||^2 = ||\lambda x||^2 + 2\bar{\lambda}\mu Re<x,y> + ||\mu y||^2$
Then we must have 2$\bar{\lambda}\mu Re<x,y> = 0$ for the desired equality to hold, and so $Re<x,y> = 0$.
However, for orthogonality I want $<x,y> = 0$ and can't see how I can make this next step.
Any help would be greatly appreciated.
Comment: The formula

$$ \|\lambda x + \mu y \|^2 = \|\lambda x \|^2+ \|\mu y \|^2 + 2 \bar \lambda \mu \operatorname{Re}\langle x, y \rangle$$

is not correct (the left hand side is real, while the right hand side may not be real). The correct formula is

$$  \|\lambda x + \mu y \|^2 = \|\lambda x \|^2+ \|\mu y \|^2 + 2  \operatorname{Re}\left( \bar \lambda \mu \langle x, y \rangle\right). $$
Answer: We can assume
$$\| \lambda x + \mu y\|^2 = \|\lambda x\|^2+\|\mu y\|^2 $$
for all $\lambda, \mu \in \mathbb C$. Taking $\lambda = \mu =1$ gives
$$\|x+y\|^2 = \|x\|^2+\|y\|^2+\langle x, y \rangle + \langle y, x \rangle  $$
$$ =\|x\|^2+\|y\|^2 +\langle x, y \rangle + \overline{\langle x, y \rangle} = \|x\|^2+\|y\|^2+2 \operatorname{Re}\langle x, y \rangle$$
so that $\operatorname{Re}\langle x, y \rangle = 0$.
Now take $\lambda = i$, $\mu=1$. We obtain
$$\|ix+y\|^2 = \|ix\|^2+ \|y\|^2+\langle ix, y  \rangle + \langle y,ix \rangle$$
$$ =\|ix\|^2+\|y\|^2-i \langle x,y\rangle + i \langle y, x\rangle$$
$$=\|ix\|^2+\|y\|^2-i \left(\langle x,y\rangle - \overline{\langle x,y \rangle}\right) $$
$$ =\|ix\|^2+\|y\|^2- 2i \operatorname{Im}\langle x,y\rangle,$$
so that $\operatorname{Im}\langle x,y\rangle = 0.$


Multiple T Tests

Question: On one of my questionnaires, which measure learning behaviours, after PCA, I have 4 subgroups, Efficacy/Perseverance/Effort/Achievement - I have run a T-Test and I have 4 sets of data comparing my samples of Undergrads to Graduates - Is it appropriate to only use T Test to report the results. Similar with my next questionnaire...Approaches to learning - 3 subgroups, Deep/Surface/Strategic - T Test with 3 results for each. This would mean that I would so far report 7 sets of T Test results? (+ 1 questionnaire with no subgroups)(So 8 altogether)
This has been edited to give a little more information
Comment: I thing you should edit your initial question to add more details on your data and what are the aims of your analysis.
Comment: Could you elaborate a little bit more, because it is not clear what you are asking..?
Comment: On one of my questionnaires, which measure learning behaviours, after PCA, I have 4 subgroups, Efficacy/Perseverance/Effort/Achievement - I have run a T-Test and I have 4 sets of data comparing my samples of Undergrads to Graduates - So should I report all 4 results. Similar with my next questionnaire...Approaches to learning - 3 subgroups, Deep/Surface/Strategic - T Test with 3 results for each. This would mean that I would so far report 7 sets of T Test results?
Comment: Could you clarify what type of t-tests and for what differences you are checking? How do the t-tests relate to your hypotheses?
Comment: Do you mean you have two independent groups, graduates and undergraduates and that you have seven dependent variables, for each of which you like to test if the two groups differ? In that case, yes, you run seven tests to compare the two groups. But how many cases in each group? What values do the seven dependents have. These things determine if a t test would apply or some other test..... We really need more info before any advice can be given.
Answer: EDIT: With PCA you can report how the (rotated) variables load onto the various factors (Efficacy, Perserverance, Effort, Achievement). By doing so you justify the grouping of variables. If an instrument/questionnaire is designed to group in this way, you could confirm/disprove that using the factor loadings. If it is an established instrument I would check how it is generally reported in the literature.
Use a correction of alpha for multiple comparisons, such as the Holm-Bonferroni method. If you have a hierarchical situation, you might be better of using a nested ANOVA for group comparisons. Just check that all the assumptions of the test are fulfilled.
Comment: The question of whether to use a 'correction' for multiple comparisons is a complicated one that is strongly dependent on the context of the experiment and analysis. See here, for example: https://stats.stackexchange.com/questions/628319/p-value-correction-in-multiple-outcomes-study

Multiple T Tests


Cannot create an instance of class viewmodel hilt

Question: I use hilt for the first in my dictionary app, but when I run my app, it crash and show this log:
E/AndroidRuntime: FATAL EXCEPTION: main
    Process: ir.arinateam.dictionary, PID: 23787
    java.lang.RuntimeException: Cannot create an instance of class ir.arinateam.dictionary.feature_dictionary.presentation.WordInfoViewModel
        at androidx.lifecycle.ViewModelProvider$NewInstanceFactory.create(ViewModelProvider.kt:204)
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:322)
        at androidx.lifecycle.ViewModelProvider$AndroidViewModelFactory.create(ViewModelProvider.kt:304)
        at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.kt:175)
        at androidx.lifecycle.SavedStateViewModelFactory.create(SavedStateViewModelFactory.kt:138)

this is my module class:
`@Module
@InstallIn(SingletonComponent::class)
object WordInfoModule {
@Provides
@Singleton
fun provideGetWordInfoUseCase(repository: WordInfoRepository): GetWordInfo {
    return GetWordInfo(repository)
}

@Provides
@Singleton
fun provideWordInfoDatabase(app: Application): WordInfoDatabase {
    return Room.databaseBuilder(
        app.applicationContext, WordInfoDatabase::class.java, "word_db"
    ).addTypeConverter(Converters(GsonParser(Gson())))
        .build()
}

@Provides
@Singleton
fun provideWordInfoRepository(
    db: WordInfoDatabase,
    api: DictionaryApi
): WordInfoRepository {
    return WordInfoRepositoryImpl(api, db.dao)
}

@Provides
@Singleton
fun provideDictionaryApi(): DictionaryApi {
    return Retrofit.Builder()
        .baseUrl(DictionaryApi.BASE_URL)
        .addConverterFactory(GsonConverterFactory.create())
        .build()
        .create(DictionaryApi::class.java)
}

}`

And this is my mainActivity class that init viewmodel and try to use it:
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

private lateinit var bindingActivity: ActivityMainBinding

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    bindingActivity = DataBindingUtil.setContentView(this, R.layout.activity_main)

    val viewModel: WordInfoViewModel by viewModels {
        SavedStateViewModelFactory(application, this)
    }

    lifecycleScope.launch {

        viewModel.eventFlow.collectLatest { event ->

            when (event) {

                is WordInfoViewModel.UIEvent.ShowSnackbar -> {
                    Snackbar.make(bindingActivity.root, event.message, Snackbar.LENGTH_SHORT)
                        .show()
                }

            }

        }

    }
}
}

And this is my ViewModel:
@HiltViewModel
class WordInfoViewModel @Inject constructor(
private val getWordInfo: GetWordInfo
) : ViewModel() {

private val _searchQuery = mutableStateOf<String>("")
val searchQuery: State<String> = _searchQuery

private val _state = mutableStateOf<WordInfoState>(WordInfoState())
val state: State<WordInfoState> = _state

private val _eventFlow = MutableSharedFlow<UIEvent>()
val eventFlow = _eventFlow.asSharedFlow()

private var searchJob: Job? = null

fun onSearch(query: String) {

    _searchQuery.value = query
    searchJob?.cancel()
    searchJob = viewModelScope.launch {
        delay(500L)
        getWordInfo(query)
            .onEach { result ->
                when (result) {
                    is Resource.Success -> {
                        _state.value = state.value.copy(
                            wordInfoItems = result.data ?: emptyList(),
                            isLoading = false
                        )
                    }
                    is Resource.Error -> {
                        _state.value = state.value.copy(
                            wordInfoItems = result.data ?: emptyList(),
                            isLoading = false
                        )
                        _eventFlow.emit(UIEvent.ShowSnackbar(result.message ?: "Unknown Error"))
                    }
                    is Resource.Loading -> {
                        _state.value = state.value.copy(
                            wordInfoItems = result.data ?: emptyList(),
                            isLoading = true
                        )
                    }
                }
            }.launchIn(this)
    }

}

sealed class UIEvent {
    data class ShowSnackbar(val message: String) : UIEvent()
}

}

where is the problem and how can i solve it?
Comment: Did you add `@HiltViewModel` annotation to your viewmodel?
Comment: yes i add it to my viewmodel
Comment: please, add your viewModel code, and style your answer correct
Comment: @VeraIureva Sorry for that, I edit my question
Answer: In your activity, you can now just use KTX viewModels() directly.
 val viewModel: WordInfoViewModel by viewModels {
        SavedStateViewModelFactory(application, this)
    }

replace that part to
private val viewModel: MyViewModel by viewModels()

Comment: it return this error:
`E/AndroidRuntime: FATAL EXCEPTION: main
    Process: ir.arinateam.dictionary, PID: 25218
    java.lang.IllegalArgumentException: CreationExtras must have a value by `SAVED_STATE_REGISTRY_OWNER_KEY`
        at androidx.lifecycle.SavedStateHandleSupport.createSavedStateHandle(SavedStateHandleSupport.kt:91)

`
Comment: please, show your hilt and navigation dependencies
Comment: where do you try to call that code? in onCreate or as a property? You should do that as property
Comment: //Dagger - Hilt
    implementation 'com.google.dagger:hilt-android:2.44'
    kapt 'com.google.dagger:hilt-compiler:2.44'

    // For instrumentation tests
    androidTestImplementation  'com.google.dagger:hilt-android-testing:2.44'
    kaptAndroidTest 'com.google.dagger:hilt-compiler:2.44'

    // For local unit tests
    testImplementation 'com.google.dagger:hilt-android-testing:2.44'
    kaptTest 'com.google.dagger:hilt-compiler:2.44'

    implementation 'androidx.hilt:hilt-navigation:1.0.0'

I test both in onCreate and as property.
Answer: Hilt lets you to inject SavedStateHandle into viewmodels, you could use it as:
@HiltViewModel
class WordInfoViewModel @Inject constructor(
    private val savedStateHandle: SavedStateHandle,
    private val getWordInfo: GetWordInfo
) : ViewModel() {
    ...
}

And in your activity:
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {

    private val viewModel: WordInfoViewModel by viewModels()

    override fun onCreate(savedInstanceState: Bundle?) { ... }
}

If you feel comfortable with the still alpha library:
implementation 'androidx.hilt:hilt-lifecycle-viewmodel:1.0.0-alpha03'

Comment: when I initialize viewmodel as property, gives me this crash log:

`java.lang.IllegalArgumentException: CreationExtras must have a value by
 SAVED_STATE_REGISTRY_OWNER_KEY`


How to make ssh based vpn?

Question: I have some problems with making ssh-based VPN.
Situation:
LOCAL ->            GATE                 -> SERVICES
                (ssh server)     (Many other servers with some services)
192.168.0.10     10.1.0.154             172.26.106.0/24
255.255.255.0    255.255.0.0

From LOCAL I can login through the ssh to the GATE and then from here I have access to all of the SERVICES servers.
However i want to access services directly from my LOCAL computer. How can I acheive this?
Here is what i tried to do after reading ssh manual:
On LOCAL:
# ssh -f -w 1:2 root@GATE true
# ifconfig tun1 10.66.1.1 10.66.1.2 netmask 255.255.255.252
# route add -net 172.26.106.0 netmask 255.255.255.0 gw 10.66.1.2

On GATE:
# ifconfig tun2 10.66.1.2 10.66.1.1 netmask 255.255.255.252

It doesn't work. I get timeouts when i try to ssh to some SERVICE from LOCAL ;-(
Comment: Have you tried this script: https://github.com/oicu/vpn-over-ssh/blob/master/svpn.sh it uses a few more options than you did, which might work better.
Comment: thaaanks! Script itself did not worked for me. But I figured that I needed also to set some rules in iptables to make it work. I adjusted it to my needs, and finally it worked ;-). My script is in the answer below
Answer: Two and half year left since I asked that question... Now I found another solution which is extremely simple. You can just use tool called sshuttle.
From sshuttle manual:

sshuttle allows you to create a VPN connection from your machine to any remote server that you can connect to via ssh, as long as that server has python 2.3 or higher.

i.e.:
sshuttle -r user@gate 172.26.100.0/24 172.26.106.0/24 172.26.103.0/24

Then in another terminal you can do ssh to any server from routed subnets directly:
i.e.:
ssh email@example.com

Answer: Thanks to Jeff Meden comment I managed to do it. I adjusted that script:
github.com/oicu/vpn-over-ssh/blob/master/svpn.sh to my needs, and finally it worked:
My version:
#!/bin/bash
PATH=/usr/local/sbin:/usr/sbin:/sbin:/usr/local/bin:/usr/bin:/bin
export PATH

[ "$(whoami)" != 'root' ] && echo "Run it as root." && exit 1

SERVER_SSH_PORT="22"
SERVER_SSH_IP="10.1.0.154"
CLIENT_TUNNEL="tun5"
SERVER_TUNNEL="tun4"
CLIENT_TUN_IP="192.168.55.5"
SERVER_TUN_IP="192.168.55.4"
TUN_NETMASK="255.255.255.0"
CLIENT_ETHERNET="enp12s0"
SERVER_ETHERNET="eth0"
ROUTES=("172.26.100.0/24" "172.26.106.0/24" "172.26.103.0/24")

function start() {
    ssh -NTCf -w "${CLIENT_TUNNEL#tun}:${SERVER_TUNNEL#tun}"  root@${SERVER_SSH_IP} -p ${SERVER_SSH_PORT}
    if [ $? -ne 0 ];
        then exit 1;
    fi
    echo "ssh tunnel is working."
    ssh -T root@${SERVER_SSH_IP} -p ${SERVER_SSH_PORT}  << eeooff
        ifconfig ${SERVER_TUNNEL} ${SERVER_TUN_IP} pointopoint ${CLIENT_TUN_IP} netmask ${TUN_NETMASK}
        iptables -t nat -A POSTROUTING -s ${CLIENT_TUN_IP}/32 -o ${SERVER_ETHERNET} -j MASQUERADE
        iptables -A FORWARD -p tcp --syn -s ${CLIENT_TUN_IP}/32 -j TCPMSS --set-mss 1356
        exit
eeooff

    for ROUTE in ${ROUTES[*]}
    do
        ssh -T root@${SERVER_SSH_IP} -p ${SERVER_SSH_PORT} "iptables -t nat -A POSTROUTING -s $ROUTE -o ${CLIENT_TUNNEL} -j MASQUERADE"
    done

    if [ $? -ne 0 ];
        then exit 1;
    fi
    echo "remote start."
    ifconfig ${CLIENT_TUNNEL} > /dev/null 2>&1
    if [ $? -eq 0 ]; then
        echo 1 > /proc/sys/net/ipv4/ip_forward
        ifconfig ${CLIENT_TUNNEL} ${CLIENT_TUN_IP} pointopoint ${SERVER_TUN_IP} netmask ${TUN_NETMASK}

        for ROUTE in ${ROUTES[*]}
        do
            ip route add $ROUTE via ${CLIENT_TUN_IP} metric 102
            printf "Adding route: %s\n" $ROUTE
        done

        iptables -t nat -A POSTROUTING -s ${SERVER_TUN_IP}/32 -o ${CLIENT_ETHERNET} -j MASQUERADE
        iptables -A FORWARD -p tcp --syn -s ${SERVER_TUN_IP}/32 -j TCPMSS --set-mss 1356
        for ROUTE in ${ROUTES[*]}
        do
            iptables -t nat -A POSTROUTING -s $ROUTE -o ${CLIENT_TUNNEL} -j MASQUERADE
        done

        ping ${SERVER_TUN_IP} -i 60 > /dev/null 2>&1 & echo "local start."
    else
        exit 1
    fi
}

function  stop(){
    echo "Flushing iptables on server..."
    ssh -T root@${SERVER_SSH_IP} -p ${SERVER_SSH_PORT} "iptables -F"

    echo "Flushing iptables on localhost..."
    iptables -F

    echo "Killing ssh tunnel..."
    CLIENT_SSH_PID=`ps -ef | grep "ssh -NTCf -w ${CLIENT_TUNNEL#tun}:${SERVER_TUNNEL#tun}" | grep -v grep | head -n1 | awk '{print $2}'`
    if [ -n "${CLIENT_SSH_PID}" ]; then
        kill -9 ${CLIENT_SSH_PID}
    fi
    if [ -n "`pidof ping`" ]; then
        pidof ping | xargs kill -9
    fi
}

function usage(){
    echo "usage:"
    echo "    $0 -start"
    echo "    $0 -stop"
    echo ""
    echo "for ssh:"
    echo "    nohup $0 -start > /dev/null 2>&1"
}

case $1 in
    "--start" | "-start")
        start
        ;;
    "--stop" | "-stop")
        stop
        ;;
    *)
        usage
        ;;
esac

How to make ssh based vpn?