问:
Java Multi-threading : Unexpected result
I am working on a Enterprise application. I am facing some issues while running application in multithreaded environment. I am writing a program in which there is a variable whose value is getting updated(incremented) at very fast rate (for example 10000 updates/persecond). A loop runs for certain iterations and the value of the variable is incremented and stored in HashMap. Once the loop terminates and value the variable in HashMap is printed. I am getting unexpected value of the variable.

Here is demo program (Please read comments for better understanding) :

class test implements Runnable {

    static ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
    static AtomicInteger value_to_be_incremented_stored = new AtomicInteger(0); // variable whose value to be updated
    static AtomicInteger i = new AtomicInteger(0);  // this runs the loop

    @Override
    public void run() {

        for (i.set(0); i.get() < 100000; i.incrementAndGet()) {
            /*
                This loop should run 100000 times and when loop terminates according to me value of variable
                "value_to_be_incremented_stored" should be 100000 as its value is incremented
                100000 times the loop also runs 100000 times.
            */
            System.out.println("Thread > " + Thread.currentThread() + "  " + value_to_be_incremented_stored.incrementAndGet());
            map.put("TC", value_to_be_incremented_stored.intValue());
        }

        System.out.println("Output by Thread  " + Thread.currentThread() + "     " + map.toString());
    }

    public static void main(String[] args) {

        test t1 = new test();
        Thread thread1 = new Thread(t1);
        thread1.setName("Thread 1");

        Thread thread2 = new Thread(t1);
        thread2.setName("Thread 2");

        Thread thread3 = new Thread(t1);
        thread3.setName("Thread 3");

        Thread thread4 = new Thread(t1);
        thread4.setName("Thread 4");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

    }
}
```

Output (it varies) :

Issue :
I am running loop for 100000 times (i.get() < 100000) then how come value of variable value_to_be_incremented_stored becomes more than 100000.

答:
Everytime a new thread enters the run method it will reset your i count to zero via the first statement in the for loop by calling i.set(0).

Update: Next step after fixing reset issue, is to step through the code and see how the threads will behave.
Lets say three threads get inside the for loop while the fourth thread increments i. What will happen is that value_to_be_incremented_stored will increment 3 times and i only one time.

Body:
I am working on a Enterprise application. I am facing some issues while running application in multithreaded environment. I am writing a program in which there is a variable whose value is getting updated(incremented) at very fast rate (for example 10000 updates/persecond). A loop runs for certain iterations and the value of the variable is incremented and stored in HashMap. Once the loop terminates and value the variable in HashMap is printed. I am getting unexpected value of the variable.

Here is demo program (Please read comments for better understanding) :

class test implements Runnable {

    static ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
    static AtomicInteger value_to_be_incremented_stored = new AtomicInteger(0); // variable whose value to be updated
    static AtomicInteger i = new AtomicInteger(0);  // this runs the loop

    @Override
    public void run() {

        for (i.set(0); i.get() < 100000; i.incrementAndGet()) {
            /*
                This loop should run 100000 times and when loop terminates according to me value of variable
                "value_to_be_incremented_stored" should be 100000 as its value is incremented
                100000 times the loop also runs 100000 times.
            */
            System.out.println("Thread > " + Thread.currentThread() + "  " + value_to_be_incremented_stored.incrementAndGet());
            map.put("TC", value_to_be_incremented_stored.intValue());
        }

        System.out.println("Output by Thread  " + Thread.currentThread() + "     " + map.toString());
    }

    public static void main(String[] args) {

        test t1 = new test();
        Thread thread1 = new Thread(t1);
        thread1.setName("Thread 1");

        Thread thread2 = new Thread(t1);
        thread2.setName("Thread 2");

        Thread thread3 = new Thread(t1);
        thread3.setName("Thread 3");

        Thread thread4 = new Thread(t1);
        thread4.setName("Thread 4");

        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();

    }
}

Output (it varies) :

Issue :
I am running loop for 100000 times (i.get() < 100000) then how come value of variable value_to_be_incremented_stored becomes more than 100000.


来源: stackexchange

问:
ReactiveX Java process finishing early?
```<code>public class ReactiveExample {

    public static void main(String[] args) throws InterruptedException, NumberFormatException, UnsupportedEncodingException {

        Observable.range(1, 5).subscribe(
                System.out::println,
                error -> System.out.println("error"),
                () -> System.out.println("completed")
        );

    }

}
</code>```

The result that is printed out is rx.internal.util.ScalarSynchronousObservable@2fad386b

After the observable is printed I get:

Process finished with exit code 0.

I just started out with ReactiveX and have been following a few tutorials. My assumption was that the code above will continuously stream data as such:

1-2-3-4-5-1-2-3-4-5... and continue to print the value. Why does my program stop immediately? Does it just end after the first 5 digits have been observed? How can I change this to continuously stream values and print them as those values are looped through? Also, how do I actually print the values instead of the observable object reference?

答:
range: Returns an Observable that emits a sequence of Integers within a specified range.

So your assumption is wrong. range does not repeat anything. For that you need to use repeat

```<code>Observable.range(1, 5).repeat().subscribe(
  System.out::println,
  error -> System.out.println("error"),
  () -> System.out.println("completed")
);
</code>```

ContentLicense: CC BY-SA 3.0

Title: ReactiveX Java process finishing early?

Body:
public class ReactiveExample {

    public static void main(String[] args) throws InterruptedException, NumberFormatException, UnsupportedEncodingException {

        Observable.range(1, 5).subscribe(
                System.out::println,
                error -> System.out.println("error"),
                () -> System.out.println("completed")
        );

    }

}

The result that is printed out is rx.internal.util.ScalarSynchronousObservable@2fad386b

After the observable is printed I get:

Process finished with exit code 0.

I just started out with ReactiveX and have been following a few tutorials. My assumption was that the code above will continuously stream data as such:

1-2-3-4-5-1-2-3-4-5... and continue to print the value. Why does my program stop immediately? Does it just end after the first 5 digits have been observed? How can I change this to continuously stream values and print them as those values are looped through? Also, how do I actually print the values instead of the observable object reference?

Body:
range: Returns an Observable that emits a sequence of Integers within a specified range.

So your assumption is wrong. range does not repeat anything. For that you need to use repeat

Observable.range(1, 5).repeat().subscribe(
  System.out::println,
  error -> System.out.println("error"),
  () -> System.out.println("completed")
);


问:
Synchronise Apache logout with django logout
I have a site with static elements like images. I wanted to protect them (so that you cannot access them directly using a hotlink). For this purpose I used the part "Authentication with mod_wsgi" from the Django documentation:
Authentication with mod_wsgi

I don't like that fact that the user has to log in twice (one time Django auth and then Apache auth when there is an image on the page) but it's not the main issue (if you know how to handle this it would also be nice)

My main problem is that after I log out I still can access the protected image. I know that this is because the fact that Apache uses only Djangos check_password method but maybe there is a way to synchronise it?

答:
You should take a look at Apache 'X-SENDFILE' header: https://tn123.org/mod_xsendfile/

It allow Django to check if your user can access it and if he the access is granted the static file is then served by Apache.

With this solution your user don't have to log twice and you can have any kind of control your want !

I wrote a blog post about it here with nginx, but it work the same way :)


问:
AWS S3 : limit file size and billing
I've looked others answers about this question but didn't find what I am looking for.

I am uploading file to S3 from the browser using an ajax POST request. The signature is generated and send to the client from the server. I limit file upload size to 3MB using ['content-length-range', 0, 3000000] and it works.

Here is my issue. If I upload a bigger file, let's say 25MB, the file is first entirely uploaded, then S3 send back an error because the file is too large. But the error is only sent after it was fully uploaded and rejected, so It seems I used AWS bandwith.

If the file is then rejected by AWS, will I be billed for the bandwith used during my POST request?

答:
As jarmod replied, you won't be charged for put requests (income data transfer). </p>

<p>Also, if you can manage restrictions on client side to prevent large uploads, it is good enough. </p>

Title: AWS S3 : limit file size and billing

Body:
As jarmod replied, you won't be charged for put requests (income data transfer).

Also, if you can manage restrictions on client side to prevent large uploads, it is good enough.


问:
Android App - webview not opening file upload
I created an Android app(On Android Studio) that loads/open a website. Everything is OK on the browser but on the app, the image upload is not opening my phone's photos so that I can select the pic to upload - how to solve this??.

package com.example.opex.shoutout;

import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.webkit.WebResourceRequest;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {

    WebView webView;
    ProgressBar progressBar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        webView = (WebView) findViewById(R.id.webView);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);

        webView.getSettings().setJavaScriptEnabled(true);
        webView.setWebViewClient(new MainActivity.myWebClient());

        webView.loadUrl("http://rms.irsglobal.net/mobile/");

        webView.setWebViewClient(new WebViewClient(){
            public boolean shouldOverrideUrlLoading(WebView view, String url) {

                String url2="http://rms.irsglobal.net/mobile/";
                // all links  with in ur site will be open inside the webview
                //links that start ur domain example(http://www.example.com/)
                if (url != null && url.startsWith(url2)){
                    return false;
                }
                // all links that points outside the site will be open in a normal android browser
                else  {
                    view.getContext().startActivity(
                            new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                    return true;
                }
            }
        });

    }

    public class myWebClient extends WebViewClient
    {
        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            progressBar.setVisibility(View.GONE);
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        /*@Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            return super.shouldOverrideUrlLoading(view, request);
        }*/
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if(keyCode == KeyEvent.KEYCODE_BACK && webView.canGoBack()){
            webView.goBack();
        }
        return super.onKeyDown(keyCode, event);
    }
}```

答:
Full working code :)</p>

```<code>public class MyWb extends Activity {
/** Called when the activity is first created. */

WebView web;
ProgressBar progressBar;

private ValueCallback<Uri> mUploadMessage;
 private final static int FILECHOOSER_RESULTCODE=1;

 @Override
 protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
  if(requestCode==FILECHOOSER_RESULTCODE)
  {
   if (null == mUploadMessage) return;
            Uri result = intent == null || resultCode != RESULT_OK ? null
                    : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
  }
  }

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    web = (WebView) findViewById(R.id.webview01);
    progressBar = (ProgressBar) findViewById(R.id.progressBar1);

    web = new WebView(this);
    web.getSettings().setJavaScriptEnabled(true);
    web.loadUrl("http://www.script-tutorials.com/demos/199/index.html");
    web.setWebViewClient(new myWebClient());
    web.setWebChromeClient(new WebChromeClient()
    {
           //The undocumented magic method override
           //Eclipse will swear at you if you try to put @Override here
        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {

            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            MyWb.this.startActivityForResult(Intent.createChooser(i,"File Chooser"), FILECHOOSER_RESULTCODE);

           }

        // For Android 3.0+
           public void openFileChooser( ValueCallback uploadMsg, String acceptType ) {
           mUploadMessage = uploadMsg;
           Intent i = new Intent(Intent.ACTION_GET_CONTENT);
           i.addCategory(Intent.CATEGORY_OPENABLE);
           i.setType("*/*");
           MyWb.this.startActivityForResult(
           Intent.createChooser(i, "File Browser"),
           FILECHOOSER_RESULTCODE);
           }

        //For Android 4.1
           public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
               mUploadMessage = uploadMsg;
               Intent i = new Intent(Intent.ACTION_GET_CONTENT);
               i.addCategory(Intent.CATEGORY_OPENABLE);
               i.setType("image/*");
               MyWb.this.startActivityForResult( Intent.createChooser( i, "File Chooser" ), MyWb.FILECHOOSER_RESULTCODE );

           }

    });

    setContentView(web);

}

public class myWebClient extends WebViewClient
{
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        // TODO Auto-generated method stub
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub

        view.loadUrl(url);
        return true;

    }

    @Override
    public void onPageFinished(WebView view, String url) {
        // TODO Auto-generated method stub
        super.onPageFinished(view, url);

        progressBar.setVisibility(View.GONE);
    }
}

//flipscreen not loading again
@Override
public void onConfigurationChanged(Configuration newConfig){
    super.onConfigurationChanged(newConfig);
}

// To handle "Back" key press event for WebView to go back to previous screen.
/*@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
        web.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}*/
}
</code>```

Body:
Full working code :)

public class MyWb extends Activity {
/** Called when the activity is first created. */

WebView web;
ProgressBar progressBar;

private ValueCallback<Uri> mUploadMessage;
 private final static int FILECHOOSER_RESULTCODE=1;

 @Override
 protected void onActivityResult(int requestCode, int resultCode,
                                    Intent intent) {
  if(requestCode==FILECHOOSER_RESULTCODE)
  {
   if (null == mUploadMessage) return;
            Uri result = intent == null || resultCode != RESULT_OK ? null
                    : intent.getData();
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
  }
  }

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    web = (WebView) findViewById(R.id.webview01);
    progressBar = (ProgressBar) findViewById(R.id.progressBar1);

    web = new WebView(this);
    web.getSettings().setJavaScriptEnabled(true);
    web.loadUrl("http://www.script-tutorials.com/demos/199/index.html");
    web.setWebViewClient(new myWebClient());
    web.setWebChromeClient(new WebChromeClient()
    {
           //The undocumented magic method override
           //Eclipse will swear at you if you try to put @Override here
        // For Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg) {

            mUploadMessage = uploadMsg;
            Intent i = new Intent(Intent.ACTION_GET_CONTENT);
            i.addCategory(Intent.CATEGORY_OPENABLE);
            i.setType("image/*");
            MyWb.this.startActivityForResult(Intent.createChooser(i,"File Chooser"), FILECHOOSER_RESULTCODE);

           }

        // For Android 3.0+
           public void openFileChooser( ValueCallback uploadMsg, String acceptType ) {
           mUploadMessage = uploadMsg;
           Intent i = new Intent(Intent.ACTION_GET_CONTENT);
           i.addCategory(Intent.CATEGORY_OPENABLE);
           i.setType("*/*");
           MyWb.this.startActivityForResult(
           Intent.createChooser(i, "File Browser"),
           FILECHOOSER_RESULTCODE);
           }

        //For Android 4.1
           public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture){
               mUploadMessage = uploadMsg;
               Intent i = new Intent(Intent.ACTION_GET_CONTENT);
               i.addCategory(Intent.CATEGORY_OPENABLE);
               i.setType("image/*");
               MyWb.this.startActivityForResult( Intent.createChooser( i, "File Chooser" ), MyWb.FILECHOOSER_RESULTCODE );

           }

    });

    setContentView(web);

}

public class myWebClient extends WebViewClient
{
    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        // TODO Auto-generated method stub
        super.onPageStarted(view, url, favicon);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub

        view.loadUrl(url);
        return true;

    }

    @Override
    public void onPageFinished(WebView view, String url) {
        // TODO Auto-generated method stub
        super.onPageFinished(view, url);

        progressBar.setVisibility(View.GONE);
    }
}

//flipscreen not loading again
@Override
public void onConfigurationChanged(Configuration newConfig){
    super.onConfigurationChanged(newConfig);
}

// To handle "Back" key press event for WebView to go back to previous screen.
/*@Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
    if ((keyCode == KeyEvent.KEYCODE_BACK) && web.canGoBack()) {
        web.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}*/
}


问:
Segmentation Fault in Initializing a structure
I'm aiming to implement an algorithm to check if a graph is topologic. But well, that's not the issue here. I'm getting a core dump when trying to initialize my graph structure with the given data.

```<code>Program received signal SIGSEGV, Segmentation fault.
0x00000000004009a3 in initGraph (numberNode=15, numberArc=17, g=0x1) at src/topologicGraphOp.c:45
45          g->numberNode = numberNode;
</code>```

I'm really confused because the issue seems so obvious and yet, I cannot find it after various tries so I'm hoping that someone will find that dumb error like "bah, it's obvious" because well... I'm out of luck...

Here is the structure :

```<code>typedef struct {
   int numberNode;
   int numberArc;

   int *distances;
   int *predecessors;

   float **matrix;
   queue *successors;

   char *graphTitle;
   char **nodeDescription;
   int *time;

} graph;
</code>```

And the function where the core dump seem to appear:

```<code>void initGraph(int numberNode, int numberArc, graph *g) {
    int i, j;

    g->numberNode = numberNode;
    g->numberArc = numberArc;
    g->nodeDescription = malloc(numberNode * sizeof (char));
    g->matrix = (float **) calloc(g->numberNode, sizeof (float*));

    for (i = 0; i < g->numberNode; i++) {
        g->matrix[i] = (float *) calloc(g->numberNode, sizeof (float));
        g->nodeDescription[i] = malloc(sizeof (char));
    }
}
</code>```

My main function just calls the initializing function.
Thanks a lot!

edit: The solution in the comment :)
I forgot to malloc my graph pointer before using it in the function.

答:
Calling from main() must be like this:

```<code>graph g;
initGraph(1, 1, &g);
</code>```

or like this:

```<code>graph *g = malloc( sizeof(graph) );
initGraph(1, 1, g);
</code>```

EDIT:

In the comments there is a multivoted question about how I explained that there is an error in the code that is not shown in the OP query.

Lets see beginning of the function:

```<code>void initGraph(int numberNode, int numberArc, graph *g) {
    int i, j;
    g->numberNode = numberNode;
}
</code>```

And the error:

```<code>Program received signal SIGSEGV, Segmentation fault.
0x00000000004009a3 in initGraph (numberNode=15, numberArc=17, g=0x1) at src/topologicGraphOp.c:45
45          g->numberNode = numberNode;
</code>```

The error mention line 45 and I was asked question in comment about how we can know where the line 45. However, I immediately removed question because near the line number error show line content, so we can find that line in mentioned code.

Code at line 45 is enough simple and may cause error only when pointer g is referred to wrong memory.

The pointer g is not modified by this function before use. This function supposes the valid memory pointed by function param g.

Therefore, function is called with wrong pointer for param g. So I just suggested valid and typical approach to proper initialize variable and call such function with such param.

Body:
I'm aiming to implement an algorithm to check if a graph is topologic. But well, that's not the issue here. I'm getting a core dump when trying to initialize my graph structure with the given data.

Program received signal SIGSEGV, Segmentation fault.
0x00000000004009a3 in initGraph (numberNode=15, numberArc=17, g=0x1) at src/topologicGraphOp.c:45
45          g->numberNode = numberNode;

I'm really confused because the issue seems so obvious and yet, I cannot find it after various tries so I'm hoping that someone will find that dumb error like "bah, it's obvious" because well... I'm out of luck...

Here is the structure :

typedef struct {
   int numberNode;
   int numberArc;

   int *distances;
   int *predecessors;

   float **matrix;
   queue *successors;

   char *graphTitle;
   char **nodeDescription;
   int *time;

} graph;

And the function where the core dump seem to appear:

void initGraph(int numberNode, int numberArc, graph *g) {
    int i, j;

    g->numberNode = numberNode;
    g->numberArc = numberArc;
    g->nodeDescription = malloc(numberNode * sizeof (char));
    g->matrix = (float **) calloc(g->numberNode, sizeof (float*));

    for (i = 0; i < g->numberNode; i++) {
        g->matrix[i] = (float *) calloc(g->numberNode, sizeof (float));
        g->nodeDescription[i] = malloc(sizeof (char));
    }
}

My main function just calls the initializing function.
Thanks a lot!

edit: The solution in the comment :)
I forgot to malloc my graph pointer before using it in the function.

Body:
Calling from main() must be like this:

graph g;
initGraph(1, 1, &g);

or like this:

graph *g = malloc( sizeof(graph) );
initGraph(1, 1, g);

EDIT:

In the comments there is a multivoted question about how I explained that there is an error in the code that is not shown in the OP query.

Lets see beginning of the function:

void initGraph(int numberNode, int numberArc, graph *g) {
    int i, j;
    g->numberNode = numberNode;
}

And the error:

Program received signal SIGSEGV, Segmentation fault.
0x00000000004009a3 in initGraph (numberNode=15, numberArc=17, g=0x1) at src/topologicGraphOp.c:45
45          g->numberNode = numberNode;

The error mention line 45 and I was asked question in comment about how we can know where the line 45. However, I immediately removed question because near the line number error show line content, so we can find that line in mentioned code.

Code at line 45 is enough simple and may cause error only when pointer g is referred to wrong memory.

The pointer g is not modified by this function before use. This function supposes the valid memory pointed by function param g.

Therefore, function is called with wrong pointer for param g. So I just suggested valid and typical approach to proper initialize variable and call such function with such param.


问:
python click subcommand unified error handling
In the case where there are command groups and every sub-command may raise exceptions, how can I handle them all together in one place?

Given the example below:

```<code>import click

@click.group()
def cli():
    pass

@cli.command()
def foo():
    pass

if __name__ == '__main__':
    cli()
</code>```

Both cli and foo may raise. I know that one possible solution is to place try-except around cli() in the if clause. But that does not work when you distribute a package. In setup.py, you have to specify an entry point (in this case, cli). The if clause will not be executed.

答:
You can create a custom click.Group by inheriting from same.  The custom group can be used by passing it as the cls parameter to the click.group() decorator.  If you override the __call__ method, you can insert an exception handler like:

Code:

```<code>class CatchAllExceptions(click.Group):

    def __call__(self, *args, **kwargs):
        try:
            return self.main(*args, **kwargs)
        except Exception as exc:
            click.echo('We found %s' % exc)
</code>```

Test Code:

```<code>import click

@click.group(cls=CatchAllExceptions)
def cli():
    pass

@cli.command()
def foo():
    raise Exception('an exception!')

if __name__ == '__main__':
    cli('foo'.split())
</code>```

Results:

```<code>We found an exception!
</code>```

Body:
In the case where there are command groups and every sub-command may raise exceptions, how can I handle them all together in one place?

Given the example below:

import click

@click.group()
def cli():
    pass

@cli.command()
def foo():
    pass

if __name__ == '__main__':
    cli()

Both cli and foo may raise. I know that one possible solution is to place try-except around cli() in the if clause. But that does not work when you distribute a package. In setup.py, you have to specify an entry point (in this case, cli). The if clause will not be executed.

Body:
You can create a custom click.Group by inheriting from same.  The custom group can be used by passing it as the cls parameter to the click.group() decorator.  If you override the __call__ method, you can insert an exception handler like:

Code:

class CatchAllExceptions(click.Group):

    def __call__(self, *args, **kwargs):
        try:
            return self.main(*args, **kwargs)
        except Exception as exc:
            click.echo('We found %s' % exc)

Test Code:

import click

@click.group(cls=CatchAllExceptions)
def cli():
    pass

@cli.command()
def foo():
    raise Exception('an exception!')

if __name__ == '__main__':
    cli('foo'.split())

Results:

We found an exception!


问:
Why is my WinForms panel's scrollbars freezing the app?
I only have 2,000 32wx32h PictureBoxes within the panel in a grid-like fashion. I thought that was the issue, so I set it to 1,250 PictureBoxes (50w25h), and I'm getting the same problem.

This is not a real-time event loop. It's just a bunch of controls side by side waiting on events.

What I do is scroll down and up.. works fine. Left and right... works fine. After some scrolling for 1-2 minutes, it freezes up the entire app.

My panel's AutoScroll is set to True. None of my own code operates on the scrollbars. All it does is scroll a billion PictureBoxes around.

And I noted that disabling the scrollbars does not freeze the app later, so I'm figuring it's a scrollbar issue.

The debugger is giving no information.

Process Memory says 17.9mb is being used.

It seems to be always be reproducible with these following steps: Scroll the vertical bar down somewhat, such as half way down, then let go of mouse button, move up toward the red 'X' at the top-right of the window, and it freezes.

Other times it's just moving the vertical and horizontal scrollbars around for 30 seconds to 2 minutes, and it randomly freezes.

New Note: During a freeze, I noticed in about 5-10 seconds later the scrollbars can be moved again. Then it's quick to go back into a short freeze and repeat.

On load, this is used for initializing the grid:

```<code>        // Initialize a blank map
        for (int row = 0; row < m_mapInfo.Rows; row++)
        {
            for (int col = 0; col < m_mapInfo.Columns; col++)
            {
                PictureBox pb = new PictureBox();
                pb.Size = size;
                Point loc = new Point(m_mapInfo.TileWidth * col, m_mapInfo.TileHeight * row);
                Rectangle srcRect = new Rectangle(loc, size);
                pb.Location = loc;
                pb.Tag = -1;
                pb.Name = String.Format("Col={0:00}-Row={1:00}", col, row);
                pb.BackColor = Color.Gray;
                pb.MouseDown += pbMap_MouseDown;
                pb.MouseUp += pbMap_MouseUp;
                pnlMap.Controls.Add(pb);
            }
        }
</code>```

答: The hanging appears to be a bug while in debug mode in Visual Studio 2017. My solution was to maximize the window and panel and not use the scrollbars. If I have my window maxed initially without the use of scrollbars, it works fine with excellent performance. If I reduce the window to its original size and use the scrollbars, it hangs the application within 30 seconds - 2 minutes. Both of these cases have been tested with the same amount of PictureBoxes. </p>

Body:
I only have 2,000 32wx32h PictureBoxes within the panel in a grid-like fashion. I thought that was the issue, so I set it to 1,250 PictureBoxes (50w25h), and I'm getting the same problem.

This is not a real-time event loop. It's just a bunch of controls side by side waiting on events.

What I do is scroll down and up.. works fine. Left and right... works fine. After some scrolling for 1-2 minutes, it freezes up the entire app.

My panel's AutoScroll is set to True. None of my own code operates on the scrollbars. All it does is scroll a billion PictureBoxes around.

And I noted that disabling the scrollbars does not freeze the app later, so I'm figuring it's a scrollbar issue.

The debugger is giving no information.

Process Memory says 17.9mb is being used.

It seems to be always be reproducible with these following steps: Scroll the vertical bar down somewhat, such as half way down, then let go of mouse button, move up toward the red 'X' at the top-right of the window, and it freezes.

Other times it's just moving the vertical and horizontal scrollbars around for 30 seconds to 2 minutes, and it randomly freezes.

New Note: During a freeze, I noticed in about 5-10 seconds later the scrollbars can be moved again. Then it's quick to go back into a short freeze and repeat.

On load, this is used for initializing the grid:

        // Initialize a blank map
        for (int row = 0; row < m_mapInfo.Rows; row++)
        {
            for (int col = 0; col < m_mapInfo.Columns; col++)
            {
                PictureBox pb = new PictureBox();
                pb.Size = size;
                Point loc = new Point(m_mapInfo.TileWidth * col, m_mapInfo.TileHeight * row);
                Rectangle srcRect = new Rectangle(loc, size);
                pb.Location = loc;
                pb.Tag = -1;
                pb.Name = String.Format("Col={0:00}-Row={1:00}", col, row);
                pb.BackColor = Color.Gray;
                pb.MouseDown += pbMap_MouseDown;
                pb.MouseUp += pbMap_MouseUp;
                pnlMap.Controls.Add(pb);
            }
        }


问:
MS Outlook 2010 .SenderEmailAddress returns a huge string of characters
I've searched and searched for an answer so I'll post this here.  I'm trying to create a macro that will move 2 week old messages from my inbox to a specific folder I created for each of my coworkers.  The macro successfully loops though all inbox message older than two weeks.  However, when I use the .SenderEmailAddress it retuns a huge string of characters instead of ###@####.com.  How do I just get the senders email address?

Without giving the exact string (security issue), here is what I get with "X"'s in place of some characters:

```<code>/o=XXXXXXX/ou=Exchange Administrative Group (XXXXXXXXXXXXXXX)/cn=Recipients/cn=XXXXX@XXXXX
</code>```

At the end of the string is the Subject line text.

Any help would be greatly appreciated! :-)

答: This MSDN documentation will help.</p>

Body:
I've searched and searched for an answer so I'll post this here.  I'm trying to create a macro that will move 2 week old messages from my inbox to a specific folder I created for each of my coworkers.  The macro successfully loops though all inbox message older than two weeks.  However, when I use the .SenderEmailAddress it retuns a huge string of characters instead of ###@####.com.  How do I just get the senders email address?

Without giving the exact string (security issue), here is what I get with "X"'s in place of some characters:

/o=XXXXXXX/ou=Exchange Administrative Group (XXXXXXXXXXXXXXX)/cn=Recipients/cn=XXXXX@XXXXX

At the end of the string is the Subject line text.

Any help would be greatly appreciated! :-)

Body: This MSDN documentation will help.


问:
Growing NSTableView Row Height
I have a view-based NSTableView in a MacOSX app that structures data nicely. I would like to implement the NSTableView to have row heights which grow with the content of the data entered into one of the NSTextViews. I've subclassed an NSTextView to "grow" with the user text but the issue is that having the field embedded in the TableView causes the field to be clipped.

Does anyone have any suggestions as to how to go about implementing a growing row size?

答:
I've managed to implement this in Swift 3 (with the help of this great tip and this and this SO answer):

Make sure the table view cell in the NSTableView has a delegate connection to your subclass/view controller which adopts the NSTextFieldDelegate protocol.

Also give it these constraints to make sure it resizes according to the height of the row:

In the delegate use this code:

```<code>var editedString: String? = nil
var textCellForHeight: NSTextFieldCell = NSTextFieldCell.init()

func control(_ control: NSControl, textShouldBeginEditing fieldEditor: NSText) -> Bool {
    editedString = fieldEditor.string ?? ""
    return true
}

func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool {
    editedString = nil
    return true
}

 func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
    if commandSelector == #selector(insertNewline(_:)) {
         textView.insertNewlineIgnoringFieldEditor(self)
         editedString = textView.string ?? ""
         //The NSAnimationContext lines get rid of the animation that normally happens when the height changes
         NSAnimationContext.beginGrouping()
         NSAnimationContext.current().duration = 0
         myTableView.noteHeightOfRows(withIndexesChanged: IndexSet.init(integer: selected))
         NSAnimationContext.endGrouping()
         myTable.needsDisplay = true
         return true
    }
    return false
}

func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
    if let temp = editedString { //we know it’s currently being edited if it’s not nil
        textCellForHeight.stringValue = temp
        //in my case, there was a specific table column that I knew would be edited
        //you might need to decide on the column width another way.
        let column = myTable.tableColumns[myTable.column(withIdentifier: “TheColumnThatsBeingEdited”)]
        let frame: NSRect = NSMakeRect(0, 0, column.width, CGFloat.greatestFiniteMagnitude)
        return textCellForHeight.cellSize(forBounds: frame).height
    }
  return yourStandardHeightCGFloat
}
</code>```

Title: Growing NSTableView Row Height

Body:
I've managed to implement this in Swift 3 (with the help of this great tip and this and this SO answer):

Make sure the table view cell in the NSTableView has a delegate connection to your subclass/view controller which adopts the NSTextFieldDelegate protocol.

Also give it these constraints to make sure it resizes according to the height of the row:

In the delegate use this code:

var editedString: String? = nil
var textCellForHeight: NSTextFieldCell = NSTextFieldCell.init()

func control(_ control: NSControl, textShouldBeginEditing fieldEditor: NSText) -> Bool {
    editedString = fieldEditor.string ?? ""
    return true
}

func control(_ control: NSControl, textShouldEndEditing fieldEditor: NSText) -> Bool {
    editedString = nil
    return true
}

 func control(_ control: NSControl, textView: NSTextView, doCommandBy commandSelector: Selector) -> Bool {
    if commandSelector == #selector(insertNewline(_:)) {
         textView.insertNewlineIgnoringFieldEditor(self)
         editedString = textView.string ?? ""
         //The NSAnimationContext lines get rid of the animation that normally happens when the height changes
         NSAnimationContext.beginGrouping()
         NSAnimationContext.current().duration = 0
         myTableView.noteHeightOfRows(withIndexesChanged: IndexSet.init(integer: selected))
         NSAnimationContext.endGrouping()
         myTable.needsDisplay = true
         return true
    }
    return false
}

func tableView(_ tableView: NSTableView, heightOfRow row: Int) -> CGFloat {
    if let temp = editedString { //we know it’s currently being edited if it’s not nil
        textCellForHeight.stringValue = temp
        //in my case, there was a specific table column that I knew would be edited
        //you might need to decide on the column width another way.
        let column = myTable.tableColumns[myTable.column(withIdentifier: “TheColumnThatsBeingEdited”)]
        let frame: NSRect = NSMakeRect(0, 0, column.width, CGFloat.greatestFiniteMagnitude)
        return textCellForHeight.cellSize(forBounds: frame).height
    }
  return yourStandardHeightCGFloat
}


问:
Android application giving a weird error in Eclipse
i put this question in this forum because i am not sure whether this is an eclipse error or an Android error.
yesterday i created an Android application using Google Maps and GPS on Eclipse and it build and ran successfully however today i wanted to do some modification to the code so i started eclipse but it gave me an error.

```<code>SDK parse failed
</code>```

if i try to run it. it says the apk cannot find. how can that be happened? the same application ran successfully on the same environment yesterday. i am using Ubuntu 10.04

Thanks !!

答:
I get this problem all the time, hopefully my solution works for you.

To work around, goto your libraries inside the properties page.

Add any library and then rebuild your project.

Go back and remove the library later for clean up.

The project should still build.

ContentLicense: CC BY-SA 2.5

Body:
i put this question in this forum because i am not sure whether this is an eclipse error or an Android error.
yesterday i created an Android application using Google Maps and GPS on Eclipse and it build and ran successfully however today i wanted to do some modification to the code so i started eclipse but it gave me an error.

SDK parse failed

if i try to run it. it says the apk cannot find. how can that be happened? the same application ran successfully on the same environment yesterday. i am using Ubuntu 10.04

Thanks !!


问:
Swiftkey ignores TextInputEditText flag InputType.TYPE_TEXT_FLAG_CAP_WORDS - doesn't capitalize
I have a simple TextInputLayout. TextInputEditText which is inside TextInputLayout has two InputType flags -

```<code>InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
</code>```

and

```<code>InputType.TYPE_TEXT_FLAG_CAP_WORDS
</code>```

These flags are set programmatically. It should disable suggestions and capitalize each single word which you write. It works without problem on default Android keyboard.
Unfortunately, if you use Swift Keyboard instead it ignores the second flag (it doesn't automatically capitalize the first letter of each word.
I don't have any experience with 3rd party soft keyboards. Does anybody have any idea how to solve it?

答: In the end, I found out that SwiftKey ignores all InputType.TYPE_TEXT_FLAG_XXX if you set them programmatically. I tried to set them in XML and it worked fine. However, it still isn't the best solution because sometimes it is necessary to set it programmatically. I somebody find some better solution please leave a comment :)</p>

Body:
I have a simple TextInputLayout. TextInputEditText which is inside TextInputLayout has two InputType flags -

InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS

and

InputType.TYPE_TEXT_FLAG_CAP_WORDS

These flags are set programmatically. It should disable suggestions and capitalize each single word which you write. It works without problem on default Android keyboard.
Unfortunately, if you use Swift Keyboard instead it ignores the second flag (it doesn't automatically capitalize the first letter of each word.
I don't have any experience with 3rd party soft keyboards. Does anybody have any idea how to solve it?


问:
reload a specific section of a web page
Please I'm working with php, ajax and jquery. when I post a status the status is posted with ajax and php, so no entire page reloading happens, but the problem is I want the posted status to be viewed along side the already posted status which means that the old status need to  be refreshed so the new posted status appear with me....I wish I could do that and update only the status section without the whole page...this is the code I use to Post the status without reloading.

$('input#post-submit').on('click', function(){
     var post = $('textarea#userPost').val();
     var azoul = $('input#token').val();
     if($.trim(post) != '' && $.trim(azoul) === 'azoul_majidi15AJH45skLD')
     {
         $.ajax({
         url:"post-post.php",
         method:"POST",
         data:{post:post,azoul},`enter code here`
         dataType:"text",
         success:function(data){
                   $('#post-state').text('Your Status was posted successfully');
                }
          });
     }
});
    ```

答:
Inside the success of your ajax, replace the html of your old post div with new post content. $("#old_post_div").html("new_post_content");
Or you can use prepend or append so that the new content will be prepended or appended along with old content.

Title: reload a specific section of a web page


问:
page show only the files in iis 7
I have an Mvc 5 application, for development I used IIS Express, everything works normally on it, but I'm having a problem uploading it to IIS 7. Still on my local machine, I'll later take it to Windows 2008. The problem is that when I run http://localhost/Aprovacoes/ my page does not open, displays the message:
HTTP Error 403.14 - Forbidden
The Web server is configured not to list the contents of this directory.

Enabled to be able to list files in the directory, and only shows me the files not opening my page Index.cshtml

```<code>localhost - /

03/06/2017    12:39        <dir> Areas
03/06/2017    12:39        <dir> bin
03/06/2017    12:39        <dir> Content
26/05/2017    17:23         1078 packages.config
03/06/2017    12:39           49 PrecompiledApp.config
03/06/2017    12:39        <dir> Scripts
03/06/2017    12:39        <dir> Views
03/06/2017    15:00         7905 Web.config
</code>```

Configuration of access to the inetpub folder where the project publish is with access, has already been tested in iis.

I have tested with all application pools, currently the Integrated is currently set to 4.0.

My route config did not make any changes, it is as follows:

```<code> public static class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.LowercaseUrls = true;
            routes.MapRoute("Default", "{controller}/{action}/{id}", new
            {
                controller = "Home",
                action = "Index",
                id = UrlParameter.Optional
            }).RouteHandler = new DashRouteHandler();
        }
    }
</code>```

I have already tried adding standard Index.cshtml document to iis but it did not work either.

When accessing the Home / Index, the action will identify that there is no user logged in by Forms Authentication, and will redirect to the Account / Login, this whole process works on IIS Express.

Could you help me solve this problem?

答:
If you are publishing your site from Visual Studio quick checks such as,

UnCheck PreCompile During Publishing

Check if your global.asax file is part of the published files

, and you may want to try one or more of the following

Give the necessary permission to the IIS_IUSRS user on IIS Server. Right click on the web site then Edit Permissions > Security. Grant the IIS_IURS permission to

Read & Execute, List folder contents and Read permissions

Try adding the following you to your Web.Config file

 <system.webServer>
        <modules runAllManagedModulesForAllRequests="true"/>
 </system.webServer>```

Title: page show only the files in iis 7

Body:
I have an Mvc 5 application, for development I used IIS Express, everything works normally on it, but I'm having a problem uploading it to IIS 7. Still on my local machine, I'll later take it to Windows 2008. The problem is that when I run http://localhost/Aprovacoes/ my page does not open, displays the message:
HTTP Error 403.14 - Forbidden
The Web server is configured not to list the contents of this directory.

Enabled to be able to list files in the directory, and only shows me the files not opening my page Index.cshtml

localhost - /

03/06/2017    12:39        <dir> Areas
03/06/2017    12:39        <dir> bin
03/06/2017    12:39        <dir> Content
26/05/2017    17:23         1078 packages.config
03/06/2017    12:39           49 PrecompiledApp.config
03/06/2017    12:39        <dir> Scripts
03/06/2017    12:39        <dir> Views
03/06/2017    15:00         7905 Web.config

Configuration of access to the inetpub folder where the project publish is with access, has already been tested in iis.

I have tested with all application pools, currently the Integrated is currently set to 4.0.

My route config did not make any changes, it is as follows:

 public static class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.LowercaseUrls = true;
            routes.MapRoute("Default", "{controller}/{action}/{id}", new
            {
                controller = "Home",
                action = "Index",
                id = UrlParameter.Optional
            }).RouteHandler = new DashRouteHandler();
        }
    }

I have already tried adding standard Index.cshtml document to iis but it did not work either.

When accessing the Home / Index, the action will identify that there is no user logged in by Forms Authentication, and will redirect to the Account / Login, this whole process works on IIS Express.

Could you help me solve this problem?


问:
SyntaxError: missing ) after argument list in cart.js
I'm getting

SyntaxError: missing ) after argument list | in cart.js file

```<code>// Purchase button.
        add('<button onclick="yaCounter44762137.reachGoal('zakaz'); return true;" class="btn btn-primary cart-purchase-button" type="button"></button>')
</code>```

答:
If you escape the single quotes like this:

```<code>add('<button onclick="yaCounter44762137.reachGoal(\'zakaz\'); return true;" class="btn btn-primary cart-purchase-button" type="button"></button>');
</code>```

It'll work.

Body:
I'm getting

SyntaxError: missing ) after argument list | in cart.js file

// Purchase button.
        add('<button onclick="yaCounter44762137.reachGoal('zakaz'); return true;" class="btn btn-primary cart-purchase-button" type="button"></button>')

Body:
If you escape the single quotes like this:

add('<button onclick="yaCounter44762137.reachGoal(\'zakaz\'); return true;" class="btn btn-primary cart-purchase-button" type="button"></button>');

It'll work.


问:
appendToLi() function requiring a return?
Quick question... what is the reason that I need to return the 'element' variable when using the appendToLi? If I remove the line, the code will not add anything to the list. It's confusing to me because the appendToLi function calls are not returning the element to anything.

For example, I would understand if it looked like this...

```<code>let element = appendToLi(property, value, text);
</code>```

But that is not the case. I have...

```<code>appendToLi(property, value, text);
</code>```

```<code>document.addEventListener('DOMContentLoaded', () => {

  //Targets the unordered list element
  const list = document.getElementById("myUL");
  //Targets the children of the unordered list
  const li = list.children;

  //Targets the form element.
  const form = document.getElementById("registrar");

  //Function declaration (Begins process of creating list item)
  function createListItem(text){
    //Creates the list item
    const li = document.createElement('li');
    //Function delcaration (creates an element and returns element)
    function createElement(elementName, property, value) {
      const element = document.createElement(elementName);
      element[property] = value;
      return element;
    }

    //Function declaration (Adds the created element to the list)
    function appendToLi(elementName, property, value){
      const element = createElement(elementName, property, value);
      li.appendChild(element);
      return element;
    }

      //Appends all children to the list item.
      appendToLi('span', 'textContent', text);
      appendToLi('label', 'textContent', 'Completed')
        .appendChild(createElement('input', 'type', 'checkbox'));
      appendToLi('button', 'textContent', 'remove');
      appendToLi('button', 'textContent', 'edit');

      /*Returns the list item and it's children to what has called the
      createListItem function*/
      return li;
  }

    //Event listener (listens for click on submit button/enter press)
    form.addEventListener('submit', (e) => {
      e.preventDefault();

      //Targets the input element.
      const input = document.querySelector('input');

      //If the user has not entered any text in the  input field, alerts.
      if(input.value === '') {
        alert('Please enter an item!');

      //Otherise begins the process of creating the list item.
      } else {

        //Holds the user text input.
        const text = input.value;

        /*Calls the createListItem function which will begin the process
          through various other functions.*/
        const listItem = createListItem(text);
        list.appendChild(listItem);
        input.value = '';
      }

  });
</code>```

答:
This:

```<code>appendToLi('label', 'textContent', 'Completed')
  .appendChild(createElement('input', 'type', 'checkbox'));
</code>```

... throws an error and interrupts script execution if appendToLi() doesn't return the element.

The above lines of code are equivalent to this:

```<code>var element = appendToLi('label', 'textContent', 'Completed');
element.appendChild(createElement('input', 'type', 'checkbox'));
</code>```

Here, it's easier to see what happens when appendToLi() doesn't return anything: element becomes undefined and you then try to invoke a method called appendChild on it which throws an error since undefined doesn't have any methods or properties.

Body:
Quick question... what is the reason that I need to return the 'element' variable when using the appendToLi? If I remove the line, the code will not add anything to the list. It's confusing to me because the appendToLi function calls are not returning the element to anything.

For example, I would understand if it looked like this...

let element = appendToLi(property, value, text);

But that is not the case. I have...

appendToLi(property, value, text);

document.addEventListener('DOMContentLoaded', () => {

  //Targets the unordered list element
  const list = document.getElementById("myUL");
  //Targets the children of the unordered list
  const li = list.children;

  //Targets the form element.
  const form = document.getElementById("registrar");

  //Function declaration (Begins process of creating list item)
  function createListItem(text){
    //Creates the list item
    const li = document.createElement('li');
    //Function delcaration (creates an element and returns element)
    function createElement(elementName, property, value) {
      const element = document.createElement(elementName);
      element[property] = value;
      return element;
    }

    //Function declaration (Adds the created element to the list)
    function appendToLi(elementName, property, value){
      const element = createElement(elementName, property, value);
      li.appendChild(element);
      return element;
    }

      //Appends all children to the list item.
      appendToLi('span', 'textContent', text);
      appendToLi('label', 'textContent', 'Completed')
        .appendChild(createElement('input', 'type', 'checkbox'));
      appendToLi('button', 'textContent', 'remove');
      appendToLi('button', 'textContent', 'edit');

      /*Returns the list item and it's children to what has called the
      createListItem function*/
      return li;
  }

    //Event listener (listens for click on submit button/enter press)
    form.addEventListener('submit', (e) => {
      e.preventDefault();

      //Targets the input element.
      const input = document.querySelector('input');

      //If the user has not entered any text in the  input field, alerts.
      if(input.value === '') {
        alert('Please enter an item!');

      //Otherise begins the process of creating the list item.
      } else {

        //Holds the user text input.
        const text = input.value;

        /*Calls the createListItem function which will begin the process
          through various other functions.*/
        const listItem = createListItem(text);
        list.appendChild(listItem);
        input.value = '';
      }

  });

Body:
This:

appendToLi('label', 'textContent', 'Completed')
  .appendChild(createElement('input', 'type', 'checkbox'));

... throws an error and interrupts script execution if appendToLi() doesn't return the element.

The above lines of code are equivalent to this:

var element = appendToLi('label', 'textContent', 'Completed');
element.appendChild(createElement('input', 'type', 'checkbox'));

Here, it's easier to see what happens when appendToLi() doesn't return anything: element becomes undefined and you then try to invoke a method called appendChild on it which throws an error since undefined doesn't have any methods or properties.


问:
Error when reading from byte stream:'System.ArgumentOutOfRangeException'
I've opened a byte stream on a file that's about 3.5 meg. The contents are Int32's in arrays, each arrays is separated by a unique 64-bit magic number and then some Int32s with the dimensions, followed by the data.

I'm about half way through the file, array 548 of 1001, when I get this error:

```<code>Exception thrown: 'System.ArgumentOutOfRangeException' in mscorlib.dll

Additional information: MemoryStream length must be non-negative and less than 2^31 - 1 - origin.
</code>```

The error occurs on this line:

```<code>S.Position = ByteStart + 8
</code>```

S is the stream. ByteStart is 873552. The addition produces the correct value, 873560. The file is much longer than this. Can anyone offer a suggestion as to why I might be getting this error?

答: Ok, so this appears to have turned out to be a threading issue. I noticed that when I hovered the mouse over the variables I got one set of values, and a different set in the Watch window and neither of these appeared to be the actual value. For whatever reason, at some point ByteStart became a super-large value, although this didn't seem to be happening if I just traced though the code step-by-step, it only happened if it was just running on its own. Weird!</p>

Body:
I've opened a byte stream on a file that's about 3.5 meg. The contents are Int32's in arrays, each arrays is separated by a unique 64-bit magic number and then some Int32s with the dimensions, followed by the data.

I'm about half way through the file, array 548 of 1001, when I get this error:

Exception thrown: 'System.ArgumentOutOfRangeException' in mscorlib.dll

Additional information: MemoryStream length must be non-negative and less than 2^31 - 1 - origin.

The error occurs on this line:

S.Position = ByteStart + 8

S is the stream. ByteStart is 873552. The addition produces the correct value, 873560. The file is much longer than this. Can anyone offer a suggestion as to why I might be getting this error?


问:
whats wrong with this code?
I am reading contents from files of a directory. I have to segregate the files according to their names and then read their contents. When I run the code simply without reading the contents, all the files are being listed of a particular file name, but when I try to read the contents, it reads contents from only few files, in fact just 10 of them. But the directory has about 1000 files of a particular name. I am posting the code here.

```<code>for (i = 0; i <= filenames.length; i++) {
    read = new FileReader("trainfiles/"+filenames[i]);
    br = new BufferedReader(read);

    if (filenames[i].matches(".*ham.*")) {
        System.out.println("ham:" + filenames[i]);
        while ((lines = br.readLine()) != null) {
            st = new StringTokenizer(lines);
            while (st.hasMoreTokens()) {
                System.out.println(st.nextToken());
            }
        }
        br.close();
    }
}
</code>```

Could anyone tell me where am i doing wrong!?

thanks

EDIT #1 I did some modifications which I have been told here, but the problem still persists, here is the code.

```<code>for(i=0;i<=filenames.length;i++){
            read = new FileReader("trainfiles/"+filenames[i]);

            br = new BufferedReader(read);

            if(filenames[i].matches(".*ham.*")){
                System.out.println("ham:"+filenames[i]);

                        while((lines = br.readLine())!= null){
                            st = new StringTokenizer(lines);
                            while(st.hasMoreTokens()){
                                System.out.println(st.nextToken());
                            }

                        }

            }
            br.close();
            read.close();

                        }
</code>```

EDIT #2 Now the code looks like this, but again...its not giving me the result I want.

```<code>for (i = 0; i < filenames.length; i++) {
               try {

                if (filenames[i].matches(".*ham.*")) {
                     read = new FileReader("trainfiles/"+filenames[i]);
                        br = new BufferedReader(read);
                    System.out.println("ham:" + filenames[i]);
                    while ((lines = br.readLine()) != null) {
                        st = new StringTokenizer(lines);
                        while (st.hasMoreTokens()) {
                            System.out.println(st.nextToken());
                        }
                    }
                }
               } finally {

                read.close();
                br.close();
               }
            }
</code>```

答:
You should close your FileReader object read as well.

Unless this is homework, I would also suggest you take a look at commons-io.

EDIT #1: I would suggest doing both close operations in a finally block.

EDIT #2: Did you try this?

```<code>for (i = 0; i <= filenames.length; i++) {
   try {
    read = new FileReader("trainfiles/"+filenames[i]);
    br = new BufferedReader(read);

    if (filenames[i].matches(".*ham.*")) {
        System.out.println("ham:" + filenames[i]);
        while ((lines = br.readLine()) != null) {
            st = new StringTokenizer(lines);
            while (st.hasMoreTokens()) {
                System.out.println(st.nextToken());
            }
        }
    }
   } finally {
    br.close();
    read.close();
   }
}
</code>```

Title: whats wrong with this code?

Body:
I am reading contents from files of a directory. I have to segregate the files according to their names and then read their contents. When I run the code simply without reading the contents, all the files are being listed of a particular file name, but when I try to read the contents, it reads contents from only few files, in fact just 10 of them. But the directory has about 1000 files of a particular name. I am posting the code here.

for (i = 0; i <= filenames.length; i++) {
    read = new FileReader("trainfiles/"+filenames[i]);
    br = new BufferedReader(read);

    if (filenames[i].matches(".*ham.*")) {
        System.out.println("ham:" + filenames[i]);
        while ((lines = br.readLine()) != null) {
            st = new StringTokenizer(lines);
            while (st.hasMoreTokens()) {
                System.out.println(st.nextToken());
            }
        }
        br.close();
    }
}

Could anyone tell me where am i doing wrong!?

thanks

EDIT #1 I did some modifications which I have been told here, but the problem still persists, here is the code.

for(i=0;i<=filenames.length;i++){
            read = new FileReader("trainfiles/"+filenames[i]);

            br = new BufferedReader(read);

            if(filenames[i].matches(".*ham.*")){
                System.out.println("ham:"+filenames[i]);

                        while((lines = br.readLine())!= null){
                            st = new StringTokenizer(lines);
                            while(st.hasMoreTokens()){
                                System.out.println(st.nextToken());
                            }

                        }

            }
            br.close();
            read.close();

                        }

EDIT #2 Now the code looks like this, but again...its not giving me the result I want.

for (i = 0; i < filenames.length; i++) {
               try {

                if (filenames[i].matches(".*ham.*")) {
                     read = new FileReader("trainfiles/"+filenames[i]);
                        br = new BufferedReader(read);
                    System.out.println("ham:" + filenames[i]);
                    while ((lines = br.readLine()) != null) {
                        st = new StringTokenizer(lines);
                        while (st.hasMoreTokens()) {
                            System.out.println(st.nextToken());
                        }
                    }
                }
               } finally {

                read.close();
                br.close();
               }
            }

Body:
You should close your FileReader object read as well.

Unless this is homework, I would also suggest you take a look at commons-io.

EDIT #1: I would suggest doing both close operations in a finally block.

EDIT #2: Did you try this?

for (i = 0; i <= filenames.length; i++) {
   try {
    read = new FileReader("trainfiles/"+filenames[i]);
    br = new BufferedReader(read);

    if (filenames[i].matches(".*ham.*")) {
        System.out.println("ham:" + filenames[i]);
        while ((lines = br.readLine()) != null) {
            st = new StringTokenizer(lines);
            while (st.hasMoreTokens()) {
                System.out.println(st.nextToken());
            }
        }
    }
   } finally {
    br.close();
    read.close();
   }
}


问:
sudo apt-get-repository: command is not found in debian linux
I was going to install firefox to debian linux. I used ubuntu command

```<code>sudo add-apt-repository ppa:mozillateam/firefox-next
</code>```

but i faced some errors it said

sudo apt-get-repository: command is not found.

So i cannot go forward to install firefox to my debian linux..

Could anyone tell me how to skip this problem and how to install firefox to debian

答:
I suggest you check the Debian version what you're using. Debian by default comes with Iceweasel web browser instead of Firefox.

How to install firefox in Debian Jessie,

Add Mozilla Archive to APT Repositories
Open a terminal as root, and add a new file to /etc/apt/sources.list.d/ directory.

$ touch /etc/apt/sources.list.d/debian-mozilla.list

edit this file in editor, deb http://mozilla.debian.net/ jessie-backports firefox-release

Add the Mozilla Archive Key
This line adds mozilla.debian.net archive to your list of archives. Since the packages at mozilla.debian.net are signed, running apt-get update now will spit out a key not found the error. To add the key you need to download the pkg-mozilla-archive-keyring package, and install it. The package requires that debian-keying package be installed.

commands,

```<code>$ cd ~/
$ wget mozilla.debian.net/pkg-mozilla-archive-keyring_1.1_all.deb
$ dpkg -i pkg-mozilla-archive-keyring_1.1_all.deb
</code>```

Install Firefox, update the archives and install Firefox:

commands,

```<code>$ apt-get update
$ apt-get install -t jessie-backports firefox
</code>```

After doing all the above steps you installed the Firefox.

Installing Firefox browser on Debian wheezy

Edit your /etc/apt/sources.list file and add the following line.

deb http://packages.linuxmint.com debian import

Update your package list.

$ apt-get update

The above command will fetch mint package repository list. As a last step install firefox browser.

$ apt-get install firefox

Debian Jessie and later, another information if you use Jessie then it can be found in the software-properties-common package:

```<code>sudo apt-get install software-properties-common
</code>```

Whereas in Debian Wheezy and earlier, The apt-get program add-apt-repository is available in Debian.

That is located in the package: python-software-properties

```<code>sudo apt-get install python-software-properties
</code>```

Actually, added to that package in version 0.75. The current version in Debian Stable ('squeeze") is 0.60, so it doesn't have it. The version currently in Debian Testing ("wheezy") is 0.82.7.1debian1, so it's available there

I request you to go through this question, it will help you.

Body:
I was going to install firefox to debian linux. I used ubuntu command

sudo add-apt-repository ppa:mozillateam/firefox-next

but i faced some errors it said

sudo apt-get-repository: command is not found.

So i cannot go forward to install firefox to my debian linux..

Could anyone tell me how to skip this problem and how to install firefox to debian

Body:
I suggest you check the Debian version what you're using. Debian by default comes with Iceweasel web browser instead of Firefox.

How to install firefox in Debian Jessie,

Add Mozilla Archive to APT Repositories
Open a terminal as root, and add a new file to /etc/apt/sources.list.d/ directory.

$ touch /etc/apt/sources.list.d/debian-mozilla.list

edit this file in editor, deb http://mozilla.debian.net/ jessie-backports firefox-release

Add the Mozilla Archive Key
This line adds mozilla.debian.net archive to your list of archives. Since the packages at mozilla.debian.net are signed, running apt-get update now will spit out a key not found the error. To add the key you need to download the pkg-mozilla-archive-keyring package, and install it. The package requires that debian-keying package be installed.

commands,

$ cd ~/
$ wget mozilla.debian.net/pkg-mozilla-archive-keyring_1.1_all.deb
$ dpkg -i pkg-mozilla-archive-keyring_1.1_all.deb

Install Firefox, update the archives and install Firefox:

commands,

$ apt-get update
$ apt-get install -t jessie-backports firefox

After doing all the above steps you installed the Firefox.

Installing Firefox browser on Debian wheezy

Edit your /etc/apt/sources.list file and add the following line.

deb http://packages.linuxmint.com debian import

Update your package list.

$ apt-get update

The above command will fetch mint package repository list. As a last step install firefox browser.

$ apt-get install firefox

Debian Jessie and later, another information if you use Jessie then it can be found in the software-properties-common package:

sudo apt-get install software-properties-common

Whereas in Debian Wheezy and earlier, The apt-get program add-apt-repository is available in Debian.

That is located in the package: python-software-properties

sudo apt-get install python-software-properties

Actually, added to that package in version 0.75. The current version in Debian Stable ('squeeze") is 0.60, so it doesn't have it. The version currently in Debian Testing ("wheezy") is 0.82.7.1debian1, so it's available there

I request you to go through this question, it will help you.


问:
C - How to make sure that an array contains 8 integers with the value 0 or 1?
That's my code so far:

```<code>int main(void) {
    int byte[8], position = 0, match8 = 0;
    printf("Please enter 1 byte as a binary sequence: ");
    match8 = scanf("%1d%1d%1d%1d%1d%1d%1d%1d", &byte[0], &byte[1], &byte[2], &byte[3], &byte[4], &byte[5], &byte[6],&byte[7]);
    return 0;
}
</code>```

Now I want to make sure that the user made a correct input and if not the program should say "Error! Please enter 1 byte as a binary sequence: " and check the input again.

I tried:

```<code>while(getchar() != '\n' || match8 != 8) {
    ...do something
}
</code>```

But I can't figure out how to check if the array contains only 0 and 1.

I hope you can help me with my problem :)

答:
try this</p>

```<code>char bits[9], ch;
int byte[8];

while(1){
    printf("Please enter 1 byte as a binary sequence: ");fflush(stdout);
    bits[8] = 1, ch = 0;
    if(2 == scanf(" %8[01]%c", bits, &ch) && ch == '\n' && bits[8] == 0)
        break;
    if(ch != '\n')
        while(getchar() != '\n');//clear input
    printf("Error! ");
}
sscanf(bits, "%1d%1d%1d%1d%1d%1d%1d%1d", &byte[0], &byte[1], &byte[2], &byte[3], &byte[4], &byte[5], &byte[6],&byte[7]);
</code>```

Body:
That's my code so far:

int main(void) {
    int byte[8], position = 0, match8 = 0;
    printf("Please enter 1 byte as a binary sequence: ");
    match8 = scanf("%1d%1d%1d%1d%1d%1d%1d%1d", &byte[0], &byte[1], &byte[2], &byte[3], &byte[4], &byte[5], &byte[6],&byte[7]);
    return 0;
}

Now I want to make sure that the user made a correct input and if not the program should say "Error! Please enter 1 byte as a binary sequence: " and check the input again.

I tried:

while(getchar() != '\n' || match8 != 8) {
    ...do something
}

But I can't figure out how to check if the array contains only 0 and 1.

I hope you can help me with my problem :)

Body:
try this

char bits[9], ch;
int byte[8];

while(1){
    printf("Please enter 1 byte as a binary sequence: ");fflush(stdout);
    bits[8] = 1, ch = 0;
    if(2 == scanf(" %8[01]%c", bits, &ch) && ch == '\n' && bits[8] == 0)
        break;
    if(ch != '\n')
        while(getchar() != '\n');//clear input
    printf("Error! ");
}
sscanf(bits, "%1d%1d%1d%1d%1d%1d%1d%1d", &byte[0], &byte[1], &byte[2], &byte[3], &byte[4], &byte[5], &byte[6],&byte[7]);


问:
For one Amazon EC2 Instance, what paid service for free SSL Certificate?
I have one EC2 Instance but need an SSL Certificate and am wanting the free one offered thru Amazon.  However I need to use another paid service. With just one (most likely low volume) EC2 instance I doubt I need Elastic Load Balancing. The only other service that makes sense would be Amazon CloudFront.

I am running a website for an online store so the other paid services don't seem to apply.

Or should I just opt for a paid SSL Certificate from a 3rd party Certificate Authority and install it on my EC2 Instance?

Any guidance is really appreciated.

答:
I am  not sure if you know that Aws offers free SSL certificates. You can use those certificates with ELB and CloudFront.

Also, Aws won't charge anything for that SSL service.

So, you can work with CloudFront + SSL -> EC2.

Hope it helps you.


问:
createReadStream pipe not working in electron 1.6
createReadStream pipe not working in electron 1.6. It was working for 1.3 version. But now when i updated the version of electron, it not working. Please refer the code below.

```<code>response.writeHead(200, {'Content-Type': 'video/mp4'});

var rs = fs.createReadStream(queryData.video);
rs.pipe(response);
response.end();
</code>```

What's i am missing in the new version?

答: as robertklep suggested, i removed response.end(). Then it's working</p>

Body:
createReadStream pipe not working in electron 1.6. It was working for 1.3 version. But now when i updated the version of electron, it not working. Please refer the code below.

response.writeHead(200, {'Content-Type': 'video/mp4'});

var rs = fs.createReadStream(queryData.video);
rs.pipe(response);
response.end();

What's i am missing in the new version?


答:
I understood that you are creating elements when form is submitted. There is guess what I can make as I don't know why you are doing what. In the code section below:

```<code>//Function declaration (Adds the created element to the list)
function appendToLi(elementName, property, value){
  const element = createElement(elementName, property, value);
  li.appendChild(element);
  return element;
}
  //Creates the list item
  const li = document.createElement('li');

  //Appends all children to the list item.
  appendToLi('span', 'textContent', text);
</code>```

Here you created the li after you have declared the function appendToLi function try to declare before the function declaration. That might help.

Title: appendToLi() function requiring a return?

Body:
I understood that you are creating elements when form is submitted. There is guess what I can make as I don't know why you are doing what. In the code section below:

//Function declaration (Adds the created element to the list)
function appendToLi(elementName, property, value){
  const element = createElement(elementName, property, value);
  li.appendChild(element);
  return element;
}
  //Creates the list item
  const li = document.createElement('li');

  //Appends all children to the list item.
  appendToLi('span', 'textContent', text);

Here you created the li after you have declared the function appendToLi function try to declare before the function declaration. That might help.


问:
Octave call a function as a variable of another function
I wrote a bisection method in Octave but it can't consume another function..

My bisection method code is like:

function[x,b] = bisection(f,a,b)

  t = 10e-8

  while abs(b-a) > t;
    c = (a+b)/2;

    if f(a) * f(b) <= 0
       a = a;
       b = c;
    else
       b = b;
       a = c
    endif
  endwhile

  x = (a+b)/2
endfunction
```

<p>And I already have a file f1.m:</p>

```function y = f1(x)
  y = x^2 - 4;
endfunction
```

<p>But when I call <code>[x,v] = bisection[f1,0,5]</code>, I get:</p>

```>> [t,v] = bisection(f1,0,5)
   error: 'x' undefined near line 2 column 5
   error: called from
          f1 at line 2 column 3
   error: evaluating argument list element number 1
```

答:
Andy has given you the answer on how to fix this. I would just like to add why you get that error and what it means. Consider the following octave session:

```<code>octave:1> function Out = g1(x); Out = x+5; end
octave:2> function Out = g2(); Out = 10;end
octave:3>
octave:3> g2
ans =  10
octave:4> g1
error: 'x' undefined near line 1 column 29
error: called from
    g1 at line 1 column 27
</code>```

I.e., when you write g1 or g2 here, this is an actual function call. The call to g2 succeeds because g2 does not take any arguments; the syntax g2 is essentially equivalent to g2(). However, the call to g1 fails, because g1 expects an argument, and we didn't provide one.

Compare with:

```<code>octave:4> a = @g1;
octave:5> b = @g2;
octave:6> a
a = @g1
octave:7> a(1)
ans =  6
octave:8> b
b = @g2
octave:9> b()
ans =  10
</code>```

where you have created handles to these functions, which you can capture into variables, and pass them as arguments into functions. These handles could then be called as a(5) or b() inside the function that received them as arguments, and it would be like calling the original g1 and g2 functions.

When you called bisection(f1,0,5), you essentially called bisection(f1(),0,5), i.e. you asked octave to evaluate the function f1 without passing any arguments, and use the result as the first input argument to the bisection function. Since function f1 is defined to take an input argument and you didn't supply any, octave complains that when it tries to evaluate y = x^2 - 4; as per the definition of f1, x was not passed as an input argument and was therefore undefined.

Therefore, to pass a "function" as an arbitrary argument that can be called inside your bisection function, you need to pass a function handle instead, which can be created using the @f1 syntax. Read up on "anonymous functions" on the octave (or matlab) documentation.

Body:
I wrote a bisection method in Octave but it can't consume another function..

My bisection method code is like:

function[x,b] = bisection(f,a,b)

  t = 10e-8

  while abs(b-a) > t;
    c = (a+b)/2;

    if f(a) * f(b) <= 0
       a = a;
       b = c;
    else
       b = b;
       a = c
    endif
  endwhile

  x = (a+b)/2
endfunction

And I already have a file f1.m:

function y = f1(x)
  y = x^2 - 4;
endfunction

But when I call [x,v] = bisection[f1,0,5], I get:

>> [t,v] = bisection(f1,0,5)
   error: 'x' undefined near line 2 column 5
   error: called from
          f1 at line 2 column 3
   error: evaluating argument list element number 1

Body:
Andy has given you the answer on how to fix this. I would just like to add why you get that error and what it means. Consider the following octave session:

octave:1> function Out = g1(x); Out = x+5; end
octave:2> function Out = g2(); Out = 10;end
octave:3>
octave:3> g2
ans =  10
octave:4> g1
error: 'x' undefined near line 1 column 29
error: called from
    g1 at line 1 column 27

I.e., when you write g1 or g2 here, this is an actual function call. The call to g2 succeeds because g2 does not take any arguments; the syntax g2 is essentially equivalent to g2(). However, the call to g1 fails, because g1 expects an argument, and we didn't provide one.

Compare with:

octave:4> a = @g1;
octave:5> b = @g2;
octave:6> a
a = @g1
octave:7> a(1)
ans =  6
octave:8> b
b = @g2
octave:9> b()
ans =  10

where you have created handles to these functions, which you can capture into variables, and pass them as arguments into functions. These handles could then be called as a(5) or b() inside the function that received them as arguments, and it would be like calling the original g1 and g2 functions.

When you called bisection(f1,0,5), you essentially called bisection(f1(),0,5), i.e. you asked octave to evaluate the function f1 without passing any arguments, and use the result as the first input argument to the bisection function. Since function f1 is defined to take an input argument and you didn't supply any, octave complains that when it tries to evaluate y = x^2 - 4; as per the definition of f1, x was not passed as an input argument and was therefore undefined.

Therefore, to pass a "function" as an arbitrary argument that can be called inside your bisection function, you need to pass a function handle instead, which can be created using the @f1 syntax. Read up on "anonymous functions" on the octave (or matlab) documentation.


问:
http to https redirect on openshift rails app
I want my rails 4.0 app on Openshift Online to serve content only over https.
There is a guide which tells to use a .htaccess in the web-root:

```<code>RewriteEngine on

RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
</code>```

I followed the guide and put a .htaccess file with the directive in my app-root/repo directory on the openshift cartridge, but nothing happens. The guide talks about a web-root dir. What is the web-root directory of a rails app, or what is a web-root directory on openshift? And is there another way to establish http to https redirect for rails on openshift?

答:
There is one solution for Ruby 1.9 for OpenShift 2 with steps for terminal:

cd your_ruby_git_project_folder/public/

vi .htaccess

```<code><IfModule mod_rewrite.c>
RewriteEngine on
</IfModule>
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R,L]
</code>```

cd ..

git add . -A

git commit -m 'message'

git push

Body:
I want my rails 4.0 app on Openshift Online to serve content only over https.
There is a guide which tells to use a .htaccess in the web-root:

RewriteEngine on

RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

I followed the guide and put a .htaccess file with the directive in my app-root/repo directory on the openshift cartridge, but nothing happens. The guide talks about a web-root dir. What is the web-root directory of a rails app, or what is a web-root directory on openshift? And is there another way to establish http to https redirect for rails on openshift?

Body:
There is one solution for Ruby 1.9 for OpenShift 2 with steps for terminal:

cd your_ruby_git_project_folder/public/

vi .htaccess

<IfModule mod_rewrite.c>
RewriteEngine on
</IfModule>
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [R,L]

cd ..

git add . -A

git commit -m 'message'

git push


问:
What do we call this type of argument passing mul(1)(2)(3) how to solve this and how to solve such scenario in case of n arguments passed like this
What do we call this type of argument passing mul(1)(2)(3) how to solve this and how to solve such scenario in case of n arguments passed like this.
I want to understand how this concept works.</p>

答:
It is called currying.

The main part is to return the same function again and again.

Then you need a mechanism to get the result. In Javascript, the toString method is called if the calling function requires a primitive value.

function mul(x) {
    function f(y) {            // the function to return
        x *= y;                // update the value
        return f;              // return the function
    };

    f.toString = function () { // overwrite toString prototype
       return x;               // return value
    };

    return f;                  // return function, enable currying
}

console.log(mul(1)(2)(3));
console.log(mul(1)(2)(3)(4)(5)(6));```


问:
Error with datetime insertion
I'm trying to insert a datetime in my table, but I can't figure why it isn't working. I'm running the following query:

```<code>DROP TABLE IF EXISTS dynamic_pricing ;
CREATE TABLE dynamic_pricing(
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    time_start  TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    time_stop TIMESTAMP NOT NULL,
    change_ratio REAL NOT NULL
    -- day_of_week INT(1)
);

INSERT INTO  dynamic_pricing(id,time_start,time_stop,change_ratio)
VALUES(1,DATETIME('2000-01-01 00:00:00'),DATETIME('2000-01-01 00:00:02'),2);
</code>```

I tried using this, only to get

```<code>ERROR 1064 (42000): You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near '('2000-01-01 00:00:00'),DATETIME('2000-01-01
00:00:02'),2)' at line 2
</code>```

What's wrong with this query?

答:
Given that you are defaulting two values, you don't need to insert them.  I would suggest:

```<code>INSERT INTO  dynamic_pricing(time_stop, change_ratio)
    VALUES('2000-01-01 00:00:02', 2);
</code>```

Then, the DATETIME() is unnecessary (is it even a function?).  Here is a SQL Fiddle example.

Title: Error with datetime insertion

Body:
I'm trying to insert a datetime in my table, but I can't figure why it isn't working. I'm running the following query:

DROP TABLE IF EXISTS dynamic_pricing ;
CREATE TABLE dynamic_pricing(
    id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
    time_start  TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
    time_stop TIMESTAMP NOT NULL,
    change_ratio REAL NOT NULL
    -- day_of_week INT(1)
);

INSERT INTO  dynamic_pricing(id,time_start,time_stop,change_ratio)
VALUES(1,DATETIME('2000-01-01 00:00:00'),DATETIME('2000-01-01 00:00:02'),2);

I tried using this, only to get

ERROR 1064 (42000): You have an error in your SQL syntax; check the
manual that corresponds to your MySQL server version for the right
syntax to use near '('2000-01-01 00:00:00'),DATETIME('2000-01-01
00:00:02'),2)' at line 2

What's wrong with this query?

Body:
Given that you are defaulting two values, you don't need to insert them.  I would suggest:

INSERT INTO  dynamic_pricing(time_stop, change_ratio)
    VALUES('2000-01-01 00:00:02', 2);

Then, the DATETIME() is unnecessary (is it even a function?).  Here is a SQL Fiddle example.


答:
This is called "currying" and is a short hand form for the result of a function call being another function that immediately gets invoked with another parameter.

First:

```<code>mul(1)
</code>```

Is called and would return a function. Then that function would be called with the second argument:

```<code>resultingFunctionFromCallingmul(2)
</code>```

Finally, that call would return yet another function that would be called with the final argument:

```<code>resultingFunctionFromCallingtheFirstResultingFunction(3)
</code>```

Here's an example:

function a(input){
  console.log("function a called with " + input);
  return b;
}

function b(input){
  console.log("function b called with " + input);
  return c;
}

function c(input){
    console.log("function c called with " + input);
}

a("This is")(" a ")(" test.");```

Body:
What do we call this type of argument passing mul(1)(2)(3) how to solve this and how to solve such scenario in case of n arguments passed like this.
I want to understand how this concept works.

Body:
This is called "currying" and is a short hand form for the result of a function call being another function that immediately gets invoked with another parameter.

First:

mul(1)

Is called and would return a function. Then that function would be called with the second argument:

resultingFunctionFromCallingmul(2)

Finally, that call would return yet another function that would be called with the final argument:

resultingFunctionFromCallingtheFirstResultingFunction(3)

Here's an example:

function a(input){
  console.log("function a called with " + input);
  return b;
}

function b(input){
  console.log("function b called with " + input);
  return c;
}

function c(input){
    console.log("function c called with " + input);
}

a("This is")(" a ")(" test.");