问:
How to make VB Console Application close itself after specified time
I created a VB console application that runs a series of tasks and I'm planning to set it up in Windows Task Scheduler so it will run by itself based on schedule.. I'd like the exe to close after 30 seconds upon completing its tasks. I'm only familiar with "Console.readline()" where you need to press anything before it closes.. can you help?</p>

```<code>Sub Main()
    If Directory.Exists(MyPath) Then
        RenameAll(MyPath)
        Console.WriteLine(vbCrLf + vbCrLf + "Press ENTER to exit...")
        Console.ReadLine()
    Else
        Console.WriteLine(vbCrLf + "Path is invalid")
        Console.WriteLine(vbCrLf + vbCrLf + "Press ENTER to exit...")
        Console.ReadLine()
    End If
End Sub
</code>```

答:
You could replace your lines ..

```<code>Console.WriteLine(vbCrLf + vbCrLf + "Press ENTER to exit...")
Console.ReadLine()
</code>```

with this.

```<code>Dim sw As New Diagnostics.Stopwatch
sw.Start()
Console.WriteLine("This console window will close in 30 seconds")
Console.WriteLine("Or press any key")
Do
Loop Until sw.ElapsedMilliseconds >= 30000 Or console.KeyAvailable
</code>```

It creates a stopwatch and keeps looping until either the number of elapsed milliseconds >=30000 or of the user presses a key.

Alternatively, if you just want the console to remain open for 30s with no user interaction, replace the lines with

```<code>Threading.Thread.Sleep(30000)
</code>```

Body:
I created a VB console application that runs a series of tasks and I'm planning to set it up in Windows Task Scheduler so it will run by itself based on schedule.. I'd like the exe to close after 30 seconds upon completing its tasks. I'm only familiar with "Console.readline()" where you need to press anything before it closes.. can you help?

Sub Main()
    If Directory.Exists(MyPath) Then
        RenameAll(MyPath)
        Console.WriteLine(vbCrLf + vbCrLf + "Press ENTER to exit...")
        Console.ReadLine()
    Else
        Console.WriteLine(vbCrLf + "Path is invalid")
        Console.WriteLine(vbCrLf + vbCrLf + "Press ENTER to exit...")
        Console.ReadLine()
    End If
End Sub

Body:
You could replace your lines ..

Console.WriteLine(vbCrLf + vbCrLf + "Press ENTER to exit...")
Console.ReadLine()

with this.

Dim sw As New Diagnostics.Stopwatch
sw.Start()
Console.WriteLine("This console window will close in 30 seconds")
Console.WriteLine("Or press any key")
Do
Loop Until sw.ElapsedMilliseconds >= 30000 Or console.KeyAvailable

It creates a stopwatch and keeps looping until either the number of elapsed milliseconds >=30000 or of the user presses a key.

Alternatively, if you just want the console to remain open for 30s with no user interaction, replace the lines with

Threading.Thread.Sleep(30000)


来源: stackexchange

问:
Django installed but throws import error in virtual env when running: sudo python manage.py collectstatic
I am working in a virtual environment.
When I run import django and django.VERISON, I get

```<code>>>> django.VERSION
(1, 10, 2, 'final', 0)
</code>```

but when I run the command

```<code>sudo python manage.py collectstatic
</code>```

it throws error:

```<code>"Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
</code>```

I checked the sys.path inside virtual env and it does not have django.
it has these:

```<code>['', '/www/XXX/venv/lib/python35.zip', '/www/XXX/venv/lib/python3.5', '/www/XXX/venv/lib/python3.5/plat-x86_64-linux-gnu', '/www/XXX/venv/lib/python3.5/lib-dynload', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/www/XXX/venv/lib/python3.5/site-packages']
</code>```

I still don't know how to make it work.
Should I install django again in virtualenv, or should I uninstall the version already there on the server, or should I just add it to python variable?
Also I if should do one of these things, how to do it?

I am working with a server for the first time, hence not doing anything intuitively.

EDIT:
I am inside a virtual environment

While trying to install django in venv I get:

```<code>(venv) ritambhara@XXX-backend:/www/XXX$ pip install Django==1.10.2
Requirement already satisfied: Django==1.10.2 in ./venv/lib/python3.5/site-packages
</code>```

when running the command with sudo, I get:

```<code>(venv) ritambhara@XXX-backend:/www/XXX$ sudo python manage.py collectstatic
Traceback (most recent call last):
  File "manage.py", line 17, in <module>
    "Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?
</code>```

when running the command without sudo, I get:

```<code>(venv) ritambhara@XXX-backend:/www/XXX$ python manage.py collectstatic
Traceback (most recent call last):
  File "/usr/lib/python3.5/logging/config.py", line 558, in configure
    handler = self.configure_handler(handlers[name])
  File "/usr/lib/python3.5/logging/config.py", line 731, in configure_handler
    result = factory(**kwargs)
  File "/usr/lib/python3.5/logging/handlers.py", line 150, in __init__
    BaseRotatingHandler.__init__(self, filename, mode, encoding, delay)
  File "/usr/lib/python3.5/logging/handlers.py", line 57, in __init__
    logging.FileHandler.__init__(self, filename, mode, encoding, delay)
  File "/usr/lib/python3.5/logging/__init__.py", line 1008, in __init__
    StreamHandler.__init__(self, self._open())
  File "/usr/lib/python3.5/logging/__init__.py", line 1037, in _open
    return open(self.baseFilename, self.mode, encoding=self.encoding)
PermissionError: [Errno 13] Permission denied: '/www/XXX/logs/log.log'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/www/XXX/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "/www/XXX/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute
    django.setup()XXX
  File "/www/XXX/venv/lib/python3.5/site-packages/django/__init__.py", line 22, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "/www/XXX/venv/lib/python3.5/site-packages/django/utils/log.py", line 75, in configure_logging
    logging_config_func(logging_settings)
  File "/usr/lib/python3.5/logging/config.py", line 795, in dictConfig
    dictConfigClass(config).configure()
  File "/usr/lib/python3.5/logging/config.py", line 566, in configure
    '%r: %s' % (name, e))
ValueError: Unable to configure handler 'file_log': [Errno 13] Permission denied: '/www/XXX/logs/log.log'
</code>```

答:
I reinstalled everything from start but it did not solve the problem. also I tried using a new virtual environment but it threw the same error.

Finally I restarted the server using sudo /etc/mod_wsgi-express-80/apachectl restart, and it worked. I don't know why exactly.

Also DO NOT use sudo with command python manage.py collectstatic, thanks Janos

ContentLicense: CC BY-SA 3.0

Body:
I am working in a virtual environment.
When I run import django and django.VERISON, I get

>>> django.VERSION
(1, 10, 2, 'final', 0)

but when I run the command

sudo python manage.py collectstatic

it throws error:

"Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?

I checked the sys.path inside virtual env and it does not have django.
it has these:

['', '/www/XXX/venv/lib/python35.zip', '/www/XXX/venv/lib/python3.5', '/www/XXX/venv/lib/python3.5/plat-x86_64-linux-gnu', '/www/XXX/venv/lib/python3.5/lib-dynload', '/usr/lib/python3.5', '/usr/lib/python3.5/plat-x86_64-linux-gnu', '/www/XXX/venv/lib/python3.5/site-packages']

I still don't know how to make it work.
Should I install django again in virtualenv, or should I uninstall the version already there on the server, or should I just add it to python variable?
Also I if should do one of these things, how to do it?

I am working with a server for the first time, hence not doing anything intuitively.

EDIT:
I am inside a virtual environment

While trying to install django in venv I get:

(venv) ritambhara@XXX-backend:/www/XXX$ pip install Django==1.10.2
Requirement already satisfied: Django==1.10.2 in ./venv/lib/python3.5/site-packages

when running the command with sudo, I get:

(venv) ritambhara@XXX-backend:/www/XXX$ sudo python manage.py collectstatic
Traceback (most recent call last):
  File "manage.py", line 17, in <module>
    "Couldn't import Django. Are you sure it's installed and "
ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment?

when running the command without sudo, I get:

(venv) ritambhara@XXX-backend:/www/XXX$ python manage.py collectstatic
Traceback (most recent call last):
  File "/usr/lib/python3.5/logging/config.py", line 558, in configure
    handler = self.configure_handler(handlers[name])
  File "/usr/lib/python3.5/logging/config.py", line 731, in configure_handler
    result = factory(**kwargs)
  File "/usr/lib/python3.5/logging/handlers.py", line 150, in __init__
    BaseRotatingHandler.__init__(self, filename, mode, encoding, delay)
  File "/usr/lib/python3.5/logging/handlers.py", line 57, in __init__
    logging.FileHandler.__init__(self, filename, mode, encoding, delay)
  File "/usr/lib/python3.5/logging/__init__.py", line 1008, in __init__
    StreamHandler.__init__(self, self._open())
  File "/usr/lib/python3.5/logging/__init__.py", line 1037, in _open
    return open(self.baseFilename, self.mode, encoding=self.encoding)
PermissionError: [Errno 13] Permission denied: '/www/XXX/logs/log.log'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "manage.py", line 22, in <module>
    execute_from_command_line(sys.argv)
  File "/www/XXX/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line
    utility.execute()
  File "/www/XXX/venv/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute
    django.setup()XXX
  File "/www/XXX/venv/lib/python3.5/site-packages/django/__init__.py", line 22, in setup
    configure_logging(settings.LOGGING_CONFIG, settings.LOGGING)
  File "/www/XXX/venv/lib/python3.5/site-packages/django/utils/log.py", line 75, in configure_logging
    logging_config_func(logging_settings)
  File "/usr/lib/python3.5/logging/config.py", line 795, in dictConfig
    dictConfigClass(config).configure()
  File "/usr/lib/python3.5/logging/config.py", line 566, in configure
    '%r: %s' % (name, e))
ValueError: Unable to configure handler 'file_log': [Errno 13] Permission denied: '/www/XXX/logs/log.log'


问:
how to memorize and randomize the questions in MCQ?
Dears,

I'm looking for assistance in visual basic with respect to multiple choices questions (MCQ).

by using visual basic for Visual Studio 2015

apply the codes without using database:

1- how to Not make any duplications in the questions?(for memorizing purpose... what is wrong and what is right?) E.g. Assuming I open the program and the first question is the word “rich” ,and I chose the correct answer, which is “IT”, I don’t want to see “rich” again until I finish with the whole list. However, if I make the wrong choice for “rich” for anything else e.g. “HR”, I want the word “rich” to appear after a while until I get the question correct. The point here to make the person memorize “rich” is “IT”.

Please write the codes down in your comment (the point you answering)

sorry for asking long question

Thank you

```<code>Public Class Form1

Private Structure questionsNanswers
    Public Q As String
    Public A As String
    Public QT As Integer
    Public QC As Integer
End Structure

Private wstart As Integer = 0
Private adad As Integer = 10
Private QA(9999) As questionsNanswers

Private word(15) As String

Private aray(15) As Integer

Private Sub RandomizeArray(a As Integer, ByRef array() As Integer)

    Dim i As Integer
    Dim j As Integer
    Dim tmp As Integer

    Randomize()
    For i = 0 To a - 1
        j = Int((6 - i + 1) * Rnd() + i)

        tmp = array(i)
        array(i) = array(j)
        array(j) = tmp

    Next

End Sub

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    ' next

    CheckEntry()

    wstart = wstart + 1
    If wstart >= adad Then
        wstart = 0
    End If

    WriteText()
End Sub

Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
    ' previous

    CheckEntry()

    wstart = wstart - 1
    If wstart < 0 Then
        wstart = adad - 1
    End If

    WriteText()
End Sub

Private Sub CheckEntry()

    RadioButton1.Visible = True
    RadioButton2.Visible = True
    RadioButton3.Visible = True
    RadioButton4.Visible = True

    RadioButton1.ForeColor = Color.Black
    RadioButton2.ForeColor = Color.Black
    RadioButton3.ForeColor = Color.Black
    RadioButton4.ForeColor = Color.Black

    RadioButton1.Checked = False
    RadioButton2.Checked = False
    RadioButton3.Checked = False
    RadioButton4.Checked = False

End Sub

Private Sub WriteText()

    Dim out As Boolean = False

    For kk = 0 To 6
        aray(kk) = kk
    Next
    RandomizeArray(7, aray)

    Do Until out
        For j = 0 To 3
            If out = False Then
                If aray(j) = QA(wstart).QT Then
                    out = True
                    Exit Do
                End If
            End If
        Next

        For kkk = 0 To 6
            aray(kkk) = kkk
        Next
        RandomizeArray(7, aray)
    Loop

    RadioButton1.Text = word(aray(0))
    RadioButton2.Text = word(aray(1))
    RadioButton3.Text = word(aray(2))
    RadioButton4.Text = word(aray(3))

    Label1.Text = CStr(wstart + 1) & ") " & QA(wstart).Q
    ' ==============================
    Dim go As Boolean = False
    If go Then
        Dim msg As String
        For ll = 0 To 6
            msg = msg + CStr(aray(ll)) + "|"
        Next

        MsgBox(msg)
    End If

End Sub

Public Sub New()

    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.

    word(0) = "TA"
    word(1) = "GR"
    word(2) = "HR"
    word(3) = "FIN"
    word(4) = "commercial"
    word(5) = "Proc"
    word(6) = "IT"

    QA(0).Q = "rich"
    QA(0).A = word(6)
    QA(0).QT = 6
    QA(0).QC = -1

    QA(1).Q = "Tal"
    QA(1).A = word(1)
    QA(1).QT = 1
    QA(1).QC = -1

    QA(2).Q = "sau"
    QA(2).A = word(2)
    QA(2).QT = 2
    QA(2).QC = -1

    QA(3).Q = "pat"
    QA(3).A = word(3)
    QA(3).QT = 3
    QA(3).QC = -1

    QA(4).Q = "del"
    QA(4).A = word(5)
    QA(4).QT = 5
    QA(4).QC = -1

    WriteText()

End Sub

End Class
</code>```

答:
Procedures :

1•Store the questions in a database(E.g. MySql/MSSQL/EXCEL)

2•In the database, create a table of 6 columns(column 1 for questions,column 2 for mcq option1,column 3 for mcq option 2, column 4 for mcq option 3,column 5 for mcq option 4 and finally column 6 for mcq answer )

3•Add 1 label and 4 Radio buttons

Now all you have to do is follow this and use the code..

That'll do the work

Body:
Dears,

I'm looking for assistance in visual basic with respect to multiple choices questions (MCQ).

by using visual basic for Visual Studio 2015

apply the codes without using database:

1- how to Not make any duplications in the questions?(for memorizing purpose... what is wrong and what is right?) E.g. Assuming I open the program and the first question is the word “rich” ,and I chose the correct answer, which is “IT”, I don’t want to see “rich” again until I finish with the whole list. However, if I make the wrong choice for “rich” for anything else e.g. “HR”, I want the word “rich” to appear after a while until I get the question correct. The point here to make the person memorize “rich” is “IT”.

Please write the codes down in your comment (the point you answering)

sorry for asking long question

Thank you

Public Class Form1

Private Structure questionsNanswers
    Public Q As String
    Public A As String
    Public QT As Integer
    Public QC As Integer
End Structure

Private wstart As Integer = 0
Private adad As Integer = 10
Private QA(9999) As questionsNanswers

Private word(15) As String

Private aray(15) As Integer

Private Sub RandomizeArray(a As Integer, ByRef array() As Integer)

    Dim i As Integer
    Dim j As Integer
    Dim tmp As Integer

    Randomize()
    For i = 0 To a - 1
        j = Int((6 - i + 1) * Rnd() + i)

        tmp = array(i)
        array(i) = array(j)
        array(j) = tmp

    Next

End Sub

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    ' next

    CheckEntry()

    wstart = wstart + 1
    If wstart >= adad Then
        wstart = 0
    End If

    WriteText()
End Sub

Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
    ' previous

    CheckEntry()

    wstart = wstart - 1
    If wstart < 0 Then
        wstart = adad - 1
    End If

    WriteText()
End Sub

Private Sub CheckEntry()

    RadioButton1.Visible = True
    RadioButton2.Visible = True
    RadioButton3.Visible = True
    RadioButton4.Visible = True

    RadioButton1.ForeColor = Color.Black
    RadioButton2.ForeColor = Color.Black
    RadioButton3.ForeColor = Color.Black
    RadioButton4.ForeColor = Color.Black

    RadioButton1.Checked = False
    RadioButton2.Checked = False
    RadioButton3.Checked = False
    RadioButton4.Checked = False

End Sub

Private Sub WriteText()

    Dim out As Boolean = False

    For kk = 0 To 6
        aray(kk) = kk
    Next
    RandomizeArray(7, aray)

    Do Until out
        For j = 0 To 3
            If out = False Then
                If aray(j) = QA(wstart).QT Then
                    out = True
                    Exit Do
                End If
            End If
        Next

        For kkk = 0 To 6
            aray(kkk) = kkk
        Next
        RandomizeArray(7, aray)
    Loop

    RadioButton1.Text = word(aray(0))
    RadioButton2.Text = word(aray(1))
    RadioButton3.Text = word(aray(2))
    RadioButton4.Text = word(aray(3))

    Label1.Text = CStr(wstart + 1) & ") " & QA(wstart).Q
    ' ==============================
    Dim go As Boolean = False
    If go Then
        Dim msg As String
        For ll = 0 To 6
            msg = msg + CStr(aray(ll)) + "|"
        Next

        MsgBox(msg)
    End If

End Sub

Public Sub New()

    ' This call is required by the designer.
    InitializeComponent()

    ' Add any initialization after the InitializeComponent() call.

    word(0) = "TA"
    word(1) = "GR"
    word(2) = "HR"
    word(3) = "FIN"
    word(4) = "commercial"
    word(5) = "Proc"
    word(6) = "IT"

    QA(0).Q = "rich"
    QA(0).A = word(6)
    QA(0).QT = 6
    QA(0).QC = -1

    QA(1).Q = "Tal"
    QA(1).A = word(1)
    QA(1).QT = 1
    QA(1).QC = -1

    QA(2).Q = "sau"
    QA(2).A = word(2)
    QA(2).QT = 2
    QA(2).QC = -1

    QA(3).Q = "pat"
    QA(3).A = word(3)
    QA(3).QT = 3
    QA(3).QC = -1

    QA(4).Q = "del"
    QA(4).A = word(5)
    QA(4).QT = 5
    QA(4).QC = -1

    WriteText()

End Sub

End Class


问:
How to add "Go Back" function in WebView inside Fragment?
UPDATE: Solved! Problem was related to my Viewpager not WebView.

I'm trying to add a "Go Back" function to my WebView which is inside a Fragment. But I can't figure out how to:

```<code>public final class TestFragment extends Fragment {

    static WebView mWeb;
    private View mContentView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState)
    {
        mContentView = inflater.inflate(R.layout.webview, null);
        mWeb = (WebView)mContentView.findViewById(R.id.webview);

        WebSettings settings = mWeb.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(false);
        mWeb.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWeb.getSettings().setBuiltInZoomControls(false);
        mWeb.loadUrl("myurl...");
        mWeb.setOnKeyListener(new OnKeyListener(){
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((keyCode == KeyEvent.KEYCODE_BACK) && mWeb.canGoBack()) {
                    mWeb.goBack();
                    return true;
                }
                return false;
            }
        });
    }
}
</code>```

I also tried something like:

```<code>@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && mWeb.canGoBack()) {
        mWeb.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}
</code>```

Another solution but same problem:

```<code>@Override
public void onBackPressed()
{
    if(webView.canGoBack())
        webView.goBack();
    else
        super.onBackPressed();
}
</code>```

Any ideas how to get this working?

答:
You can check this code :  </p>

```<code>    webView.canGoBack();
    webView.setOnKeyListener(new View.OnKeyListener() {

        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK
                    && event.getAction() == MotionEvent.ACTION_UP
                    && webView.canGoBack()) {
                webView.goBack();
                return true;
            }
            return false;
        }
    });
</code>```

Body:
UPDATE: Solved! Problem was related to my Viewpager not WebView.

I'm trying to add a "Go Back" function to my WebView which is inside a Fragment. But I can't figure out how to:

public final class TestFragment extends Fragment {

    static WebView mWeb;
    private View mContentView;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState)
    {
        mContentView = inflater.inflate(R.layout.webview, null);
        mWeb = (WebView)mContentView.findViewById(R.id.webview);

        WebSettings settings = mWeb.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(false);
        mWeb.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
        mWeb.getSettings().setBuiltInZoomControls(false);
        mWeb.loadUrl("myurl...");
        mWeb.setOnKeyListener(new OnKeyListener(){
            public boolean onKey(View v, int keyCode, KeyEvent event) {
                if ((keyCode == KeyEvent.KEYCODE_BACK) && mWeb.canGoBack()) {
                    mWeb.goBack();
                    return true;
                }
                return false;
            }
        });
    }
}

I also tried something like:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if ((keyCode == KeyEvent.KEYCODE_BACK) && mWeb.canGoBack()) {
        mWeb.goBack();
        return true;
    }
    return super.onKeyDown(keyCode, event);
}

Another solution but same problem:

@Override
public void onBackPressed()
{
    if(webView.canGoBack())
        webView.goBack();
    else
        super.onBackPressed();
}

Any ideas how to get this working?

Body:
You can check this code :

    webView.canGoBack();
    webView.setOnKeyListener(new View.OnKeyListener() {

        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_BACK
                    && event.getAction() == MotionEvent.ACTION_UP
                    && webView.canGoBack()) {
                webView.goBack();
                return true;
            }
            return false;
        }
    });


问:
Share variables between different jupyter notebooks
I have two different Jupyter notebooks, running on the same server. What I would like to do is to access some (only a few of them) of the variables of one notebook through the other notebook (I have to compare if the two different versions of the algorithm give the same results, basically). Is there a way to do this?

Thanks

答:
You can use same magic commands to do this.The Cell magic: %%cache in the IPython notebook can be used to cache results and outputs of long-lasting computations in a persistent pickle file. Useful when some computations in a notebook are long and you want to easily save the results in a file.

To use it in your notebook, you need to install the module ipycache first as this Cell magic command is not a built-in magic command.

then load the module in your notebook:

```<code>%load_ext ipycache
</code>```

Then, create a cell with:

```<code>%%cache mycache.pkl var1 var2
var1 = 1  # you can put any code you want at there,
var2 = 2  # just make sure this cell is not empty.
</code>```

When you execute this cell the first time, the code is executed, and the variables var1 and var2 are saved in mycache.pkl in the current directory along with the outputs. Rich display outputs are only saved if you use the development version of IPython. When you execute this cell again, the code is skipped, the variables are loaded from the file and injected into the namespace, and the outputs are restored in the notebook.

Alternatively use $file_name instead of mycache.pkl, where file_name is a variable holding the path to the file used for caching.

Use the --force or -f option to force the cell's execution and overwrite the file.

Use the --read or -r option to prevent the cell's execution and always load the variables from the cache. An exception is raised if the file does not exist.

ref:
The github repository of ipycache and the example notebook

Body:
You can use same magic commands to do this.The Cell magic: %%cache in the IPython notebook can be used to cache results and outputs of long-lasting computations in a persistent pickle file. Useful when some computations in a notebook are long and you want to easily save the results in a file.

To use it in your notebook, you need to install the module ipycache first as this Cell magic command is not a built-in magic command.

then load the module in your notebook:

%load_ext ipycache

Then, create a cell with:

%%cache mycache.pkl var1 var2
var1 = 1  # you can put any code you want at there,
var2 = 2  # just make sure this cell is not empty.

When you execute this cell the first time, the code is executed, and the variables var1 and var2 are saved in mycache.pkl in the current directory along with the outputs. Rich display outputs are only saved if you use the development version of IPython. When you execute this cell again, the code is skipped, the variables are loaded from the file and injected into the namespace, and the outputs are restored in the notebook.

Alternatively use $file_name instead of mycache.pkl, where file_name is a variable holding the path to the file used for caching.

Use the --force or -f option to force the cell's execution and overwrite the file.

Use the --read or -r option to prevent the cell's execution and always load the variables from the cache. An exception is raised if the file does not exist.

ref:
The github repository of ipycache and the example notebook


问:
sorting python list in recursive manner
As input I will be getting lists of lists which can up to n-levels and it will vary every time. Suppose, I have a list

```<code>[[2, 1, 3], 4, [2, 3], 7, 1, [9, [4, 2], 5]]
</code>```

here I want to sort this list and expected output is

```<code>[1, 4, [2, 3], [1, 2, 3], 7, [5, [2, 4], 9]]
</code>```

Here, first sorting is happening based of elements and then based on sum of elements inside list.

code:

```<code>input_freq = [[2,1,3],4,[2,3],7,1,[9,[4,2],5]]

res = []

def sortFreq(input_freq):
    elements = []
    list_of_elements = []

    for each in input_freq:
        if isinstance(each, list):
            print "list"
            list_of_elements.append(each)
            each.sort()
        else:
            elements.append(each)
            elements.sort()

    print elements
    print list_of_elements

sortFreq(input_freq)
</code>```

expected output:

```<code>[1, 4, [2, 3], [1, 2, 3], 7, [5, [4, 2], 9]]
</code>```

but my code returns the wrong result:

```<code>[[1, 2, 3], [2, 3], [5, 9, [4, 2]]]
</code>```

答:
You'll have to work your way down to the nested levels first, then sort the parent levels as the recursive call returns. I'm going to assume you want to return a new list (and not sort in place):

```<code>def nested_sort(l):
    def sort_key(e):
        if isinstance(e, list):
            return sum(sort_key(inner) for inner in e)
        return e
    return sorted(
        [nested_sort(e) if isinstance(e, list) else e for e in l],
        key=sort_key)
</code>```

The sort key has to recursively sum nested lists, so this can be kind of expensive if you have many nested levels. In that it may be worth adding a cache based on the identity of the list being summed:

```<code>def nested_sort(l, _sum_cache=None):
    if _sum_cache is None:
        _sum_cache = {}
    def sort_key(e):
        if isinstance(e, list):
            e_id = id(e)
            if e_id not in _sum_cache:
                _sum_cache[e_id] = sum(sort_key(inner) for inner in e)
            return _sum_cache[e_id]
        return e
    return sorted(
        [nested_sort(e, _sum_cache) if isinstance(e, list) else e for e in l],
        key=sort_key)
</code>```

Demo:

```<code>>>> nested_sort([[2, 1, 3], 4, [2, 3], 7, 1, [9, [4, 2], 5]])
[1, 4, [2, 3], [1, 2, 3], 7, [5, [2, 4], 9]]
</code>```

Title: sorting python list in recursive manner

Body:
As input I will be getting lists of lists which can up to n-levels and it will vary every time. Suppose, I have a list

[[2, 1, 3], 4, [2, 3], 7, 1, [9, [4, 2], 5]]

here I want to sort this list and expected output is

[1, 4, [2, 3], [1, 2, 3], 7, [5, [2, 4], 9]]

Here, first sorting is happening based of elements and then based on sum of elements inside list.

code:

input_freq = [[2,1,3],4,[2,3],7,1,[9,[4,2],5]]

res = []

def sortFreq(input_freq):
    elements = []
    list_of_elements = []

    for each in input_freq:
        if isinstance(each, list):
            print "list"
            list_of_elements.append(each)
            each.sort()
        else:
            elements.append(each)
            elements.sort()

    print elements
    print list_of_elements

sortFreq(input_freq)

expected output:

[1, 4, [2, 3], [1, 2, 3], 7, [5, [4, 2], 9]]

but my code returns the wrong result:

[[1, 2, 3], [2, 3], [5, 9, [4, 2]]]

Body:
You'll have to work your way down to the nested levels first, then sort the parent levels as the recursive call returns. I'm going to assume you want to return a new list (and not sort in place):

def nested_sort(l):
    def sort_key(e):
        if isinstance(e, list):
            return sum(sort_key(inner) for inner in e)
        return e
    return sorted(
        [nested_sort(e) if isinstance(e, list) else e for e in l],
        key=sort_key)

The sort key has to recursively sum nested lists, so this can be kind of expensive if you have many nested levels. In that it may be worth adding a cache based on the identity of the list being summed:

def nested_sort(l, _sum_cache=None):
    if _sum_cache is None:
        _sum_cache = {}
    def sort_key(e):
        if isinstance(e, list):
            e_id = id(e)
            if e_id not in _sum_cache:
                _sum_cache[e_id] = sum(sort_key(inner) for inner in e)
            return _sum_cache[e_id]
        return e
    return sorted(
        [nested_sort(e, _sum_cache) if isinstance(e, list) else e for e in l],
        key=sort_key)

Demo:

>>> nested_sort([[2, 1, 3], 4, [2, 3], 7, 1, [9, [4, 2], 5]])
[1, 4, [2, 3], [1, 2, 3], 7, [5, [2, 4], 9]]


问:
How to replace an entire line in a text file by line number
I have a situation where I want a bash script to replace an entire line in a file.
The line number is always the same, so that can be a hard-coded variable.

I'm not trying to replace some sub-string in that line, I just want to replace that line entirely with a new line.

Are there any bash methods for doing this (or something simple that can be thrown into a .sh script).

答:
You can even pass parameters to the sed command:

test.sh

```<code>#!/bin/bash
echo "-> start"
for i in $(seq 5); do
  # passing parameters to sed
  j=$(($i+3))
  sed -i "${j}s/.*/replaced by '$i'!/" output.dat
done
echo "-> finished"
exit
</code>```

orignial output.dat:

```<code>a
b
c
d
e
f
g
h
i
j
</code>```

Executing ./test.sh gives the new output.dat

```<code>a
b
c
replaced by '1'!
replaced by '2'!
replaced by '3'!
replaced by '4'!
replaced by '5'!
i
j
</code>```

Body:
You can even pass parameters to the sed command:

test.sh

#!/bin/bash
echo "-> start"
for i in $(seq 5); do
  # passing parameters to sed
  j=$(($i+3))
  sed -i "${j}s/.*/replaced by '$i'!/" output.dat
done
echo "-> finished"
exit

orignial output.dat:

a
b
c
d
e
f
g
h
i
j

Executing ./test.sh gives the new output.dat

a
b
c
replaced by '1'!
replaced by '2'!
replaced by '3'!
replaced by '4'!
replaced by '5'!
i
j


问:
bash script to batch truncate filenames in one dir
this question is somewhat unique among others asked.

i have a dir with a bunch of folders and they are named using periods to separate every word.

such as: foo.bar.2011.useless.words

the last two words are always the useless ones, so i would like to truncate starting with the second to last period.

not sure of the wording...

many thanks

答:
```<code>for file in *.*.*
do
  mv "$file" "${file%.*.*}"
done
</code>```

ContentLicense: CC BY-SA 2.5


问:
Listening to Map Entries with Predicates doesn't fire
I try to use map listener with predicates like on docs.

I am using .net 3.9 client and I configured my Java (also Hazelcast 3.9) code. But my listeners doesn't fire.

```<code>myTestMap.AddEntryListener(new EntryAdapter<string,MyTestMap> { Added = e => ValidateData(e) },new SqlPredicate("Status=2"),true);
</code>```

When old value does not match predicate, new value matches predicate

writes on document. But any event fire include with have no predicate.

UPDATE: I update version 3.9.1 and try to use EntryAddedListener.
I update code;

```<code>myTestMap.AddEntryListener(new TestListener(),new SqlPredicate("Status=2"),true);
public class TestListener: EntryAddedListener<string,MyTestMap> {
    public void EntryAdded(EntryEvent<string,MyTestMap> @event) {
         ValidateData(@event);
    }
}
</code>```

This time, I get:

Your app has entered a break state, but there is no code to show because all threads were executing external code (typically system or framework code).

UPDATE 2: Ok, I found the problem and try to fix it.

```<code>ClientMapProxy.AddEntryListener(MapListener listener,.....
</code>```

methods has recursive call so, I get previous exception.

答:
You're usage is exactly correct and is expected to work. From looking at our Github repository, I see you've already figured it really is a bug and reported it (https://github.com/hazelcast/hazelcast-csharp-client/issues/145) thanks for it.

For the sake of others running into the same issue, we're looking into fixing it, please see the issue linked above.

Thanks again for the report and your digging into it!

Body:
I try to use map listener with predicates like on docs.

I am using .net 3.9 client and I configured my Java (also Hazelcast 3.9) code. But my listeners doesn't fire.

myTestMap.AddEntryListener(new EntryAdapter<string,MyTestMap> { Added = e => ValidateData(e) },new SqlPredicate("Status=2"),true);

When old value does not match predicate, new value matches predicate

writes on document. But any event fire include with have no predicate.

UPDATE: I update version 3.9.1 and try to use EntryAddedListener.
I update code;

myTestMap.AddEntryListener(new TestListener(),new SqlPredicate("Status=2"),true);
public class TestListener: EntryAddedListener<string,MyTestMap> {
    public void EntryAdded(EntryEvent<string,MyTestMap> @event) {
         ValidateData(@event);
    }
}

This time, I get:

Your app has entered a break state, but there is no code to show because all threads were executing external code (typically system or framework code).

UPDATE 2: Ok, I found the problem and try to fix it.

ClientMapProxy.AddEntryListener(MapListener listener,.....

methods has recursive call so, I get previous exception.


问:
React native infinite scroll with flatlist
I followed this tutorial https://www.youtube.com/watch?v=rY0braBBlgw
When I scroll down it sends the request then it gets stuck in a loop and just requests and requests. I think this is a problem with the scrollview in the listview.</p>

答:
I am not sure if you were able to resolve this but I was having the same problem and I am adding what worked well for me.

onEndReachedThreshold=>onEndThreshold

```<code><FlatList
      data={this.state.data}
      renderItem={({ item }) => (
        <ListItem
          roundAvatar
          title={
            <Text style={{textAlign: 'left'}}> {item.name.first} {item.name.last}</Text>
          }
          subtitle={
              <Text style={{textAlign: 'left'}}>{item.email}</Text>
          }
          avatar={{ uri: item.picture.thumbnail }}
          containerStyle={{ borderBottomWidth: 0 }}
        />
      )}
      ItemSeparatorComponent={this.renderSeparator}
      ListHeaderComponent={this.renderHeader}
      ListFooterComponent={this.renderFooter}
      keyExtractor={item => item.email}
      refreshing={this.state.refreshing}
      onRefresh={this.handleRefresh}
      onEndReached={this.handleLoadMore}
      onEndThreshold={0}

    />
</code>```

I hope this helps someone.

Body:
I am not sure if you were able to resolve this but I was having the same problem and I am adding what worked well for me.

onEndReachedThreshold=>onEndThreshold

<FlatList
      data={this.state.data}
      renderItem={({ item }) => (
        <ListItem
          roundAvatar
          title={
            <Text style={{textAlign: 'left'}}> {item.name.first} {item.name.last}</Text>
          }
          subtitle={
              <Text style={{textAlign: 'left'}}>{item.email}</Text>
          }
          avatar={{ uri: item.picture.thumbnail }}
          containerStyle={{ borderBottomWidth: 0 }}
        />
      )}
      ItemSeparatorComponent={this.renderSeparator}
      ListHeaderComponent={this.renderHeader}
      ListFooterComponent={this.renderFooter}
      keyExtractor={item => item.email}
      refreshing={this.state.refreshing}
      onRefresh={this.handleRefresh}
      onEndReached={this.handleLoadMore}
      onEndThreshold={0}

    />

I hope this helps someone.


问:
WKWebView requires delay to set its scrollView's contentOffset and zoomScale after load()
I wrote some code to save off a WKWebView's scroll view's contentOffset and zoomScale, so they could be restored after the webView loads. I've found that setting those scrollView properties only works using a delay (e.g. with DispatchQueue.main.asyncAfter(). Why is this necessary? Is there a better way to achieve this?

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {
    var contentOffset = CGPoint.zero
    var zoomScale: CGFloat = 1.0
    lazy var webView: WKWebView = {
        let wv = WKWebView(frame: CGRect.zero)
        wv.translatesAutoresizingMaskIntoConstraints = false
        wv.allowsBackForwardNavigationGestures = true
        wv.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        wv.navigationDelegate = self
        return wv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(webView)
        webView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        webView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        webView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        webView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        reload()
    }

    @IBAction func refreshTapped(_ sender: UIBarButtonItem) {
        reload()
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        // Without some delay, the restoration doesn't happen!
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: {
            self.webView.scrollView.setZoomScale(self.zoomScale, animated: false)
            self.webView.scrollView.setContentOffset(self.contentOffset, animated: false)
        })
    }

    private func reload() {
        contentOffset = webView.scrollView.contentOffset
        zoomScale = webView.scrollView.zoomScale;
        webView.load(URLRequest(url: URL(string: "https://www.google.com")!))
    }
}
```

<p><strong>Update with AJ B suggestion</strong>
(Sorry for the repetition)
</p>

```import UIKit
import WebKit

class ViewController: UIViewController {
    private static let keyPath = "webView.scrollView.contentSize"
    private static var kvoContext = 0

    private var contentOffset: CGPoint?
    private var zoomScale: CGFloat?
    private var lastContentSize: CGSize?
    private var repeatedSizeCount = 0

    lazy var webView: WKWebView = {
        let wv = WKWebView(frame: CGRect.zero)
        wv.translatesAutoresizingMaskIntoConstraints = false
        wv.allowsBackForwardNavigationGestures = true
        wv.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        return wv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(webView)
        webView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        webView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        webView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        webView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        addObserver(self, forKeyPath: ViewController.keyPath, options: .new, context: &ViewController.kvoContext)
        reload()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        removeObserver(self, forKeyPath: ViewController.keyPath)
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        guard let newSize = change?[.newKey] as? CGSize, context == &ViewController.kvoContext else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
            return
        }

        print("Observed: \(NSStringFromCGSize(newSize))")

        // Nothing to restore if these are nil
        guard let offset = contentOffset, let zoom = zoomScale else { return }

        guard let lastSize = lastContentSize, lastSize == newSize else {
            print("Waiting for size to settle")
            lastContentSize = newSize
            return
        }

        repeatedSizeCount += 1

        guard repeatedSizeCount >= 4 else {
            print("Size repeated \(repeatedSizeCount) time(s)")
            return
        }

        print("Settled - set saved zoom and offset")
        contentOffset = nil
        zoomScale = nil
        lastContentSize = nil
        repeatedSizeCount = 0
        webView.scrollView.setZoomScale(zoom, animated: false)
        webView.scrollView.setContentOffset(offset, animated: false)
    }

    @IBAction func refreshTapped(_ sender: UIBarButtonItem) {
        contentOffset = webView.scrollView.contentOffset
        zoomScale = webView.scrollView.zoomScale;
        reload()
    }

    private func reload() {
        print("Reload: \(NSStringFromCGSize(webView.scrollView.contentSize))")
        webView.load(URLRequest(url: URL(string: "https://www.google.com")!))
    }
}
```

<p>Prints the following:</p>

```Reload: {781, 1453}
Observed: {781, 1453}
Waiting for size to settle
Observed: {320, 595}
Waiting for size to settle
Observed: {320, 595}
Size repeated 1 time(s)
Observed: {320, 595}
Size repeated 2 time(s)
Observed: {320, 595}
Size repeated 3 time(s)
Observed: {320, 595}
Settled - set saved zoom and offset
Observed: {781, 1453}
Observed: {781, 1453}
Observed: {781, 1453}
```

答:
```<code>//default flag is 2
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSLog(@"scrollView:%.f", scrollView.contentOffset.y);
    self.flag--;
    if (self.flag == 0) {
        [self jump];
    }
}
- (void)jump{
    if ([self.urlString isEqualToString:self.webView.URL.absoluteString]) {
        CGFloat offsetY = 0;
        offsetY = [[NSUserDefaults standardUserDefaults] floatForKey:@"history"];
        if (offsetY) {
            self.markLabel.hidden = NO;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.webView.scrollView setContentOffset:CGPointMake(0, offsetY)];
            });
        }

    }
}
</code>```

Hope this will help you.

Body:
I wrote some code to save off a WKWebView's scroll view's contentOffset and zoomScale, so they could be restored after the webView loads. I've found that setting those scrollView properties only works using a delay (e.g. with DispatchQueue.main.asyncAfter(). Why is this necessary? Is there a better way to achieve this?

import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {
    var contentOffset = CGPoint.zero
    var zoomScale: CGFloat = 1.0
    lazy var webView: WKWebView = {
        let wv = WKWebView(frame: CGRect.zero)
        wv.translatesAutoresizingMaskIntoConstraints = false
        wv.allowsBackForwardNavigationGestures = true
        wv.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        wv.navigationDelegate = self
        return wv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(webView)
        webView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        webView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        webView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        webView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        reload()
    }

    @IBAction func refreshTapped(_ sender: UIBarButtonItem) {
        reload()
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        // Without some delay, the restoration doesn't happen!
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.25, execute: {
            self.webView.scrollView.setZoomScale(self.zoomScale, animated: false)
            self.webView.scrollView.setContentOffset(self.contentOffset, animated: false)
        })
    }

    private func reload() {
        contentOffset = webView.scrollView.contentOffset
        zoomScale = webView.scrollView.zoomScale;
        webView.load(URLRequest(url: URL(string: "https://www.google.com")!))
    }
}

Update with AJ B suggestion
(Sorry for the repetition)

import UIKit
import WebKit

class ViewController: UIViewController {
    private static let keyPath = "webView.scrollView.contentSize"
    private static var kvoContext = 0

    private var contentOffset: CGPoint?
    private var zoomScale: CGFloat?
    private var lastContentSize: CGSize?
    private var repeatedSizeCount = 0

    lazy var webView: WKWebView = {
        let wv = WKWebView(frame: CGRect.zero)
        wv.translatesAutoresizingMaskIntoConstraints = false
        wv.allowsBackForwardNavigationGestures = true
        wv.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        return wv
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        view.addSubview(webView)
        webView.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
        webView.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
        webView.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
        webView.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        addObserver(self, forKeyPath: ViewController.keyPath, options: .new, context: &ViewController.kvoContext)
        reload()
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        removeObserver(self, forKeyPath: ViewController.keyPath)
    }

    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        guard let newSize = change?[.newKey] as? CGSize, context == &ViewController.kvoContext else {
            super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context)
            return
        }

        print("Observed: \(NSStringFromCGSize(newSize))")

        // Nothing to restore if these are nil
        guard let offset = contentOffset, let zoom = zoomScale else { return }

        guard let lastSize = lastContentSize, lastSize == newSize else {
            print("Waiting for size to settle")
            lastContentSize = newSize
            return
        }

        repeatedSizeCount += 1

        guard repeatedSizeCount >= 4 else {
            print("Size repeated \(repeatedSizeCount) time(s)")
            return
        }

        print("Settled - set saved zoom and offset")
        contentOffset = nil
        zoomScale = nil
        lastContentSize = nil
        repeatedSizeCount = 0
        webView.scrollView.setZoomScale(zoom, animated: false)
        webView.scrollView.setContentOffset(offset, animated: false)
    }

    @IBAction func refreshTapped(_ sender: UIBarButtonItem) {
        contentOffset = webView.scrollView.contentOffset
        zoomScale = webView.scrollView.zoomScale;
        reload()
    }

    private func reload() {
        print("Reload: \(NSStringFromCGSize(webView.scrollView.contentSize))")
        webView.load(URLRequest(url: URL(string: "https://www.google.com")!))
    }
}

Prints the following:

Reload: {781, 1453}
Observed: {781, 1453}
Waiting for size to settle
Observed: {320, 595}
Waiting for size to settle
Observed: {320, 595}
Size repeated 1 time(s)
Observed: {320, 595}
Size repeated 2 time(s)
Observed: {320, 595}
Size repeated 3 time(s)
Observed: {320, 595}
Settled - set saved zoom and offset
Observed: {781, 1453}
Observed: {781, 1453}
Observed: {781, 1453}

Body:
//default flag is 2
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    NSLog(@"scrollView:%.f", scrollView.contentOffset.y);
    self.flag--;
    if (self.flag == 0) {
        [self jump];
    }
}
- (void)jump{
    if ([self.urlString isEqualToString:self.webView.URL.absoluteString]) {
        CGFloat offsetY = 0;
        offsetY = [[NSUserDefaults standardUserDefaults] floatForKey:@"history"];
        if (offsetY) {
            self.markLabel.hidden = NO;
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.webView.scrollView setContentOffset:CGPointMake(0, offsetY)];
            });
        }

    }
}

Hope this will help you.


问:
jquery simple modal help on window load
I'm trying to something like this  if in the html there is a div called "#super" load it in the simple modal if not do nothing.  I managed to do this with the my skill :D which is none:  to load the modal if the #super exists, but it still loads doesn't matter if it exitst or not.  PLease help  I'm absolute noob on jquery.

```<code>    if( $('super') ){    $("#super").modal({onOpen: function (dialog) {

    dialog.overlay.fadeIn('slow', function () {
        dialog.container.slideDown('slow', function () {
            dialog.data.fadeIn('slow');
        });
    });
}});
</code>```

I'm using this jquery plugin link text

答:
I'm not quite sure what it is that you want to do, in the if/else conditions, but to test for the existence of something:

```<code>if ($('#super').length) {
    // it exists, do stuff
}
else {
    // it doesn't exist, do other stuff. Or nothing
}
</code>```

I'm sorry I can't be more specific, but I've not worked with the dialog/modal plugin.

Title: jquery simple modal help on window load

Body:
I'm trying to something like this  if in the html there is a div called "#super" load it in the simple modal if not do nothing.  I managed to do this with the my skill :D which is none:  to load the modal if the #super exists, but it still loads doesn't matter if it exitst or not.  PLease help  I'm absolute noob on jquery.

    if( $('super') ){    $("#super").modal({onOpen: function (dialog) {

    dialog.overlay.fadeIn('slow', function () {
        dialog.container.slideDown('slow', function () {
            dialog.data.fadeIn('slow');
        });
    });
}});

I'm using this jquery plugin link text

Body:
I'm not quite sure what it is that you want to do, in the if/else conditions, but to test for the existence of something:

if ($('#super').length) {
    // it exists, do stuff
}
else {
    // it doesn't exist, do other stuff. Or nothing
}

I'm sorry I can't be more specific, but I've not worked with the dialog/modal plugin.


问:
Alfresco bean not recognized
I have configured new multi-select button in the document library:

When the button is clicked it should execute javascript function onActionAddToList which later calls bean function insert. Everything works except the bean function - it is not called/recognized. Am I doing something wrong? I am wondering if I should configure bean in an other place? I'm using Alfresco 5.2.0 SDK 3.0.1 Below you can find corresponding code:

```<code><!--  /alfresco/web-extension/site-data/extensions/my-extension.xml  in share-jar -->

<configurations>
  <config evaluator="string-compare" condition="DocumentLibrary">
    <multi-select>
      <action type="action-link" id="onActionAddToList" icon="document-approve" label="Add item to a list" />
    </multi-select>
  </config>
  <config evaluator="string-compare" condition="DocLibCustom" replace="true">
    <dependencies>
      <js src="/components/documentlibrary/custom-documentlibrary-actions.js" />
    </dependencies>
  </config>
</configurations>

<!--  resources/components/documentlibrary/custom-documentlibrary-actions.js in share-jar

YAHOO.Bubbling.fire("registerAction", {
  actionName: "onActionAddToList",
  fn: function custom_onActionAddToList(record)
  {
     Alfresco.util.PopupManager.displayMessage({ title: "Info", text: listManagement.insert("Hello")});
  }
});

<!-- alfresco/module/project/context/service-context.xml in platform-jar -->

<beans>
  <bean id="com.test.actions.ListManagement" class="com.test.actions.ListManagement"       parent="baseJavaScriptExtension">
    <property name="extensionName" value="listManagement"/>
  </bean>
</beans>

<!-- java/com/test/actions/ListManagement.java in platform-jar -->

public class ListManagement extends BaseProcessorExtension {
  public String insert(String text) {
    return text;
  }
}
</code>```

答: Please refer this question and refer this documentation to call javabacked actions.</p>

Title: Alfresco bean not recognized

Body:
I have configured new multi-select button in the document library:

When the button is clicked it should execute javascript function onActionAddToList which later calls bean function insert. Everything works except the bean function - it is not called/recognized. Am I doing something wrong? I am wondering if I should configure bean in an other place? I'm using Alfresco 5.2.0 SDK 3.0.1 Below you can find corresponding code:

<configurations>
  <config evaluator="string-compare" condition="DocumentLibrary">
    <multi-select>
      <action type="action-link" id="onActionAddToList" icon="document-approve" label="Add item to a list" />
    </multi-select>
  </config>
  <config evaluator="string-compare" condition="DocLibCustom" replace="true">
    <dependencies>
      <js src="/components/documentlibrary/custom-documentlibrary-actions.js" />
    </dependencies>
  </config>
</configurations>

<beans>
  <bean id="com.test.actions.ListManagement" class="com.test.actions.ListManagement"       parent="baseJavaScriptExtension">
    <property name="extensionName" value="listManagement"/>
  </bean>
</beans>

public class ListManagement extends BaseProcessorExtension {
  public String insert(String text) {
    return text;
  }
}


问:
D3DXCompileShader cannot compile shader with NORMAL in it
I noticed that the D3DXCompileShader function from the Ogre library fails in case of DirectX9 because of the following reason:

```<code>error X4502: invalid vs_2_0 output semantic 'NORMAL'
</code>```

Seems pretty strange to me because MSDN states that it should be supported starting from the DirectX 9:

The following types of semantics are supported in both Direct3D 9 and Direct3D 10 and later

Here's my hlsl file:

```<code>float4x4 worldViewProj;
float4 lightPosition;
float3 eyePosition;

struct VS_OUTPUT
{
   float4 pos: POSITION;
   float4 normal: NORMAL;
   float4 color: COLOR;
   float4 lightPosition: TEXCOORD0;
   float3 eyePosition: TEXCOORD1;
   float3 pos3d: TEXCOORD2;
};

VS_OUTPUT main(
    float4 pos: POSITION,
    float4 normal: NORMAL,
    float4 color: COLOR
)
{
   VS_OUTPUT Out;
   Out.pos = mul(worldViewProj, pos);
   Out.pos3d = pos.xyz;
   Out.normal = normal;
   Out.color = color;

   Out.lightPosition = lightPosition;
   Out.eyePosition = eyePosition;

   return Out;
}
</code>```

答:
The link you provided clearly states that NORMAL semantics is only supported as VS input.
You may try to pass the normal(s) to the pixel shader using TEXCOORD (TEXCOORD3 for instance) instead.</p>

Body:
I noticed that the D3DXCompileShader function from the Ogre library fails in case of DirectX9 because of the following reason:

error X4502: invalid vs_2_0 output semantic 'NORMAL'

Seems pretty strange to me because MSDN states that it should be supported starting from the DirectX 9:

The following types of semantics are supported in both Direct3D 9 and Direct3D 10 and later

Here's my hlsl file:

float4x4 worldViewProj;
float4 lightPosition;
float3 eyePosition;

struct VS_OUTPUT
{
   float4 pos: POSITION;
   float4 normal: NORMAL;
   float4 color: COLOR;
   float4 lightPosition: TEXCOORD0;
   float3 eyePosition: TEXCOORD1;
   float3 pos3d: TEXCOORD2;
};

VS_OUTPUT main(
    float4 pos: POSITION,
    float4 normal: NORMAL,
    float4 color: COLOR
)
{
   VS_OUTPUT Out;
   Out.pos = mul(worldViewProj, pos);
   Out.pos3d = pos.xyz;
   Out.normal = normal;
   Out.color = color;

   Out.lightPosition = lightPosition;
   Out.eyePosition = eyePosition;

   return Out;
}


问:
bash-shell output format issue for loop
```<code>cat file
panny daqiu 100
panny daqiu hundred
yunhui heshuiREF youyong=3,hejiu=5,daren=4
yunhui heshui youyong=3,hejiu=5,daren=4     #compare row 2 with row 3, we found $2 in row 2 has one more character "REF" than $2 in row 3.
</code>```

What output I expect:

```<code>panny daqiu xxx                 #When $3 of this row only contains digits, the output of $1 & $2  will not change.
panny daqiu.hundred xxx         #When $3 of this row is not a digit && $2 not caontain REF$, the output of $2 will like $2.$3
yunhui heshuiREF xxx            #when $2 of this row contains character "REF"$ ,the output of $1 & $2  will not change.
yunhui heshui.youyong xxx       #when $2 of this row has no character "REF"$ , and $3 like the format "A=23,B=22,C=34...", the output of $1 & $2 will be like "$1 $2.A\n $1 $2.B\n $1 $2.C\n..."
yunhui heshui.hejiu xxx
yunhui heshui.daren xxx
#"xxx" means don't need to care about  output format of this column.
#Only need to care about the output format for $1 $2.
</code>```

Here is my code:

```<code>awk '{ printf("%s %s%s%s\n",$1,$2,($3!~/[[:digit:]]/||$2!~/REF$/? ".":" "),$3) }' file
</code>```

Belwo is output:

```<code>panny daqiu 100
panny daqiu.hundred
yunhui heshuiREF youyong=3,hejiu=5,daren=4
yunhui heshui youyong=3,hejiu=5,daren=4     #I know the last row will not achieve my purpose, may be I need a loop and array[], but I am sorry for I am lack of the experience to achieve it.
</code>```

So, for the last row, how can I improve my code ?

答:
One way you could do it</p>

```<code>awk '$2~/REF$/{print $1,$2;next}\
    {gsub(/=[^,]*/,"",$3);split($3,a,",");\
    for(i in a)print $1,$2(a[i]~/[[:digit:]]/?" ":".")a[i]}' file

panny daqiu 100
panny daqiu.hundred
yunhui heshuiREF
yunhui heshui.youyong
yunhui heshui.hejiu
yunhui heshui.daren
</code>```

Title: bash-shell output format issue for loop

Body:
cat file
panny daqiu 100
panny daqiu hundred
yunhui heshuiREF youyong=3,hejiu=5,daren=4
yunhui heshui youyong=3,hejiu=5,daren=4     #compare row 2 with row 3, we found $2 in row 2 has one more character "REF" than $2 in row 3.

What output I expect:

panny daqiu xxx                 #When $3 of this row only contains digits, the output of $1 & $2  will not change.
panny daqiu.hundred xxx         #When $3 of this row is not a digit && $2 not caontain REF$, the output of $2 will like $2.$3
yunhui heshuiREF xxx            #when $2 of this row contains character "REF"$ ,the output of $1 & $2  will not change.
yunhui heshui.youyong xxx       #when $2 of this row has no character "REF"$ , and $3 like the format "A=23,B=22,C=34...", the output of $1 & $2 will be like "$1 $2.A\n $1 $2.B\n $1 $2.C\n..."
yunhui heshui.hejiu xxx
yunhui heshui.daren xxx
#"xxx" means don't need to care about  output format of this column.
#Only need to care about the output format for $1 $2.

Here is my code:

awk '{ printf("%s %s%s%s\n",$1,$2,($3!~/[[:digit:]]/||$2!~/REF$/? ".":" "),$3) }' file

Belwo is output:

panny daqiu 100
panny daqiu.hundred
yunhui heshuiREF youyong=3,hejiu=5,daren=4
yunhui heshui youyong=3,hejiu=5,daren=4     #I know the last row will not achieve my purpose, may be I need a loop and array[], but I am sorry for I am lack of the experience to achieve it.

So, for the last row, how can I improve my code ?

Body:
One way you could do it

awk '$2~/REF$/{print $1,$2;next}\
    {gsub(/=[^,]*/,"",$3);split($3,a,",");\
    for(i in a)print $1,$2(a[i]~/[[:digit:]]/?" ":".")a[i]}' file

panny daqiu 100
panny daqiu.hundred
yunhui heshuiREF
yunhui heshui.youyong
yunhui heshui.hejiu
yunhui heshui.daren


问:
Give firebase admin rights to xamarin application
In firebase console I can get this source code for java and some adminsdk json file to download. However I'm working in c# xamarin and it doesn't have the setCredential() function. This is java code that I can download in firebase console

```<code>FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountKey.json");

FirebaseOptions options = new FirebaseOptions.Builder()
.setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
.setDatabaseUrl("https://abc-def.firebaseio.com")
.build();

FirebaseApp.initializeApp(options);
</code>```

But in xamarin, there is no SetCredential function. I can do only things like:

```<code> FirebaseOptions options = new FirebaseOptions.Builder()
     .SetApplicationId("1:3465124113567:android:81db52b2352255cd")
     .SetDatabaseUrl("https://abc-def.firebaseio.com/")
     .SetStorageBucket("gs://abc-def.appspot.com")
     .SetApiKey("???")
     .SetGcmSenderId("???")
     .Build();
 var firebaseApp = FirebaseApp.InitializeApp(context, options);
</code>```

How can I use that file? I made couple of tries in SetApiKey, setting some lines from that file, but somehow the application is just crashing on InitializeApp line, without meaningfull explanation in output window. How is it done that my application gets admin privileges in c# - xamarin?

In this question I found that SetCredentials wasn't there always, but all my xamarin.firebase.xxx components are on version 10.2.1 so this shouldn't be problem.

答:
Refer to @Doug Stevenson 's answer, you are using the Firebase Android client library, not the Firebase Admin SDK. You could read the javadoc for FirebaseOptions.Builder in the Android client library :

Android : FirebaseOptions.Builder

Then look at the same class from the java Admin SDK (note the URL is different) :

Admin SDK :
FirebaseOptions.Builder

They are different things, in your project you  are using the Android SDK definition and not the admin SDK definition.

Body:
In firebase console I can get this source code for java and some adminsdk json file to download. However I'm working in c# xamarin and it doesn't have the setCredential() function. This is java code that I can download in firebase console

FileInputStream serviceAccount = new FileInputStream("path/to/serviceAccountKey.json");

FirebaseOptions options = new FirebaseOptions.Builder()
.setCredential(FirebaseCredentials.fromCertificate(serviceAccount))
.setDatabaseUrl("https://abc-def.firebaseio.com")
.build();

FirebaseApp.initializeApp(options);

But in xamarin, there is no SetCredential function. I can do only things like:

 FirebaseOptions options = new FirebaseOptions.Builder()
     .SetApplicationId("1:3465124113567:android:81db52b2352255cd")
     .SetDatabaseUrl("https://abc-def.firebaseio.com/")
     .SetStorageBucket("gs://abc-def.appspot.com")
     .SetApiKey("???")
     .SetGcmSenderId("???")
     .Build();
 var firebaseApp = FirebaseApp.InitializeApp(context, options);

How can I use that file? I made couple of tries in SetApiKey, setting some lines from that file, but somehow the application is just crashing on InitializeApp line, without meaningfull explanation in output window. How is it done that my application gets admin privileges in c# - xamarin?

In this question I found that SetCredentials wasn't there always, but all my xamarin.firebase.xxx components are on version 10.2.1 so this shouldn't be problem.


问:
Angular 2 correct way to get data from server
I want to get data from the database. I'm following the examples at angular.io webpage but I don't know if I'm doing right.

I have a form and when a user fills the postal code field, I call the database to get the name of the city or, if it doesn't exist, ask the user to fill it.
My problem is I don't know how to correctly do it.

In my service.

```<code>checkCp(city: City): Observable<any> {
  return this.http.get<any>(this.backendUrl + 'api/city/' + city.cp).pipe(
    tap(city => console.log("fetched"))
  );
}
</code>```

and this is in my component.js

```<code>checkCp(): void {
  this.modal.header = 'Searching city';
  this.modal.text = 'Please wait';
  this.openWaitModal();
  this.studentService.checkCp(this.city)
    .subscribe(cityFromDb => {
      if(cityFromDb ===null) {
        this.closeWaitModal();
        this.modal.header = 'Postal code not found';
        this.modal.text = 'Insert the name of the city';
        this.modal.no = 'Cancel';
        this.modal.yes = 'Insert';
        this.modal.action = 'newCity';
        this.modal.enableInput = true;
        this.openModal();
      }else{
        this.closeWaitModal();
        this.city = cityFromDb.city; // I can't access cityFromDb.name
                                     // i access via cityFromDb.city.name
     }
   }, err => {
     this.errorHandler(err);
   })
}
</code>```

答:
You would call your service as follows:

```<code>checkCp(city: City): Observable<any> {
  return this.http.get<any>(this.backendUrl + 'api/city/' + city.cp);
};
</code>```

This will return an Observable to your component.ts

The code in your component.ts should work now

Body:
I want to get data from the database. I'm following the examples at angular.io webpage but I don't know if I'm doing right.

I have a form and when a user fills the postal code field, I call the database to get the name of the city or, if it doesn't exist, ask the user to fill it.
My problem is I don't know how to correctly do it.

In my service.

checkCp(city: City): Observable<any> {
  return this.http.get<any>(this.backendUrl + 'api/city/' + city.cp).pipe(
    tap(city => console.log("fetched"))
  );
}

and this is in my component.js

checkCp(): void {
  this.modal.header = 'Searching city';
  this.modal.text = 'Please wait';
  this.openWaitModal();
  this.studentService.checkCp(this.city)
    .subscribe(cityFromDb => {
      if(cityFromDb ===null) {
        this.closeWaitModal();
        this.modal.header = 'Postal code not found';
        this.modal.text = 'Insert the name of the city';
        this.modal.no = 'Cancel';
        this.modal.yes = 'Insert';
        this.modal.action = 'newCity';
        this.modal.enableInput = true;
        this.openModal();
      }else{
        this.closeWaitModal();
        this.city = cityFromDb.city; // I can't access cityFromDb.name
                                     // i access via cityFromDb.city.name
     }
   }, err => {
     this.errorHandler(err);
   })
}

Body:
You would call your service as follows:

checkCp(city: City): Observable<any> {
  return this.http.get<any>(this.backendUrl + 'api/city/' + city.cp);
};

This will return an Observable to your component.ts

The code in your component.ts should work now


问:
React Native Post Request via Fetch throws Network Request Failed
I've came across the following error.
At the moment I developing an Android App with React Native therefore I'm planning to use fetch for doing a post request for me.

```<code>fetch("https://XXreachable-domainXX.de/api/test", {
    method: "post",

    body: JSON.stringify({
      param: 'param',
      param1: 'param',

    })
  })
  .then((response) = > response.json())
  .then((responseData) = > {
    ToastAndroid.show(
      "Response Body -> " + JSON.stringify(responseData.message), ToastAndroid.SHORT
    )
  })
  .catch((error) = > {
    console.warn(error);
  });
</code>```

The app now throws an error:

TypeError: Network request failed

When I change the code to a GET-Request it's working fine, in the browser with a window.alert() as a return it's cool and also the Chrome extension Postman returns data correctly.

答:
If you run into this problem on emulator make sure you also test it on the device. It's most probably not happening there.

Just so you know there's nothing to worry about if you can work around it.

ContentLicense: CC BY-SA 4.0

Body:
I've came across the following error.
At the moment I developing an Android App with React Native therefore I'm planning to use fetch for doing a post request for me.

fetch("https://XXreachable-domainXX.de/api/test", {
    method: "post",

    body: JSON.stringify({
      param: 'param',
      param1: 'param',

    })
  })
  .then((response) = > response.json())
  .then((responseData) = > {
    ToastAndroid.show(
      "Response Body -> " + JSON.stringify(responseData.message), ToastAndroid.SHORT
    )
  })
  .catch((error) = > {
    console.warn(error);
  });

The app now throws an error:

TypeError: Network request failed

When I change the code to a GET-Request it's working fine, in the browser with a window.alert() as a return it's cool and also the Chrome extension Postman returns data correctly.


问:
word() function returns the different results depending on gnuplot version 5.06 and 5.22
I recently updated gnuplot latest version, 5.22 and my code didn't work properly. I debugged and found the reasons.

```<code>str="1 2"
print word(str,3)+0
</code>```

In the previous version, 5.06 or older, the print shows 0 values without error.
But the latest version got error, "Non-numeric string found where a numeric expression was expected"

Without +0, both results are the same, blank (no output), but the latest version treats it as string I think.

My code has lots of routine related to word(), so how do I resolve this problem in the new version?

答:
Use words to check the index:

```<code>w2num(list, i) = (i > 0 && i <= words(list)) ? word(list, i)+0 : 0
</code>```

Example:

```<code>w2num(list, i) = (i > 0 && i <= words(list)) ? word(list, i)+0 : 0
l = "10 20"
do for [i=-1:3] { print w2num(l, i) }
</code>```

prints

```<code>0
0
10
20
0
</code>```

Body:
I recently updated gnuplot latest version, 5.22 and my code didn't work properly. I debugged and found the reasons.

str="1 2"
print word(str,3)+0

In the previous version, 5.06 or older, the print shows 0 values without error.
But the latest version got error, "Non-numeric string found where a numeric expression was expected"

Without +0, both results are the same, blank (no output), but the latest version treats it as string I think.

My code has lots of routine related to word(), so how do I resolve this problem in the new version?

Body:
Use words to check the index:

w2num(list, i) = (i > 0 && i <= words(list)) ? word(list, i)+0 : 0

Example:

w2num(list, i) = (i > 0 && i <= words(list)) ? word(list, i)+0 : 0
l = "10 20"
do for [i=-1:3] { print w2num(l, i) }

prints

0
0
10
20
0


问:
How to implement virtual GT on restcomm ussd
I make a little lab to learn about USSD, then I discover USSD Restcomm. My architecture is like that:
two USSD gateways are connected to the MSC on SS7, these two gateways have their own real GT. Each gateway have one Restcomm Connect.

All of this system works very well but what I want to do is to load balance the trafic between the MSC and the two gateways by using virtual GT. Is anyone can help?

答: This feature will only be available in our commercial version of the Restcomm USSD Gateway and SS7 Load Balancer targeted to be released in Quarter 1 of 2018. Feel free to reach out to Telestax to know more</p>


问:
Issues Serializing an ArrayList object containing other ArrayList objects
So I'm Serializing an ArrayList of ArrayLists essentially but I'm running into an issue. To be honest I'm still pretty new to Java, I've tried so many different methods to fix this as well as searched relentlessly on this site and have not been successful. I know that the way I word things may be hard to follow along or is confusing so I'll post my code here to see. Sorry in advance for all the code. SuperUsers has an arraylist of LoginInfo, PasswordKeeper has an Arraylist of SuperUsers, and the SuperUser arraylist gets serialized in PasswordKeeper. but any changes made to the LoginInfo arraylist do not save and i cannot figure out why. If anyone can help I would really Appreciate it. Thanks</p>

```<code>public class PasswordKeeper{

    private ArrayList<SuperUser> users;
    private static Scanner keyboard = new Scanner(System.in);

    public PasswordKeeper() {
        users = new ArrayList();
    }

    public void login() {
        try {
            // reads in SuperUser arraylist
            get();
        } catch (EOFException a) {
            System.out.println("You are the First User!");
        } catch (IOException b) {
            System.out.println(b);
        } catch (ClassNotFoundException c) {
            System.out.println(c);
        }
        boolean loopDisplay = true;
        while (loopDisplay) {
                existingUser = keyboard.next();
                existingPass = keyboard.next();
                SuperUser temp = new SuperUser(existingUser, existingPass);
                System.out.println();
                if (users.contains(temp)) {

                    // viewing superUser method
                    temp.display();
                    //saves after method call is over
                    try {
                        System.out.println("Saving.");
                        save(users);
                    } catch (IOException e) {
                        System.out.println(e);
                    }
                }
            }
            //This happens if there is a new user
            if(answer == 2){
            SuperUser tempNew = null;
            boolean cont = true;
            String newUser;
            String pass;
            while(cont){
                newUser = keyboard.nextLine();
                System.out.println();
                //System.out.println(users.size());

                tempNew = new SuperUser(newUser, pass);
                if(passValid(pass) == true){
                    if(makeSure(tempNew) == true){
                        System.out.println("Login Created!");
                        tempNew = new SuperUser(newUser, pass);
                        //actually being added to the arraylist
                        users.add(tempNew);
                        cont = false;
                    }
                }
            }
            //SuperUser.display method
            tempNew.display();
            try{
                System.out.println("Saving.");
                save(users);
            }catch(IOException e){
                System.out.println(e);
            }
        }
        }
    }
    //makeSure and passValid methods
    public boolean makeSure(SuperUser user){
    if(users.contains(user)){
        return false;
    }
    return true;
}

public boolean passValid(String pass){
        boolean passes = false;
        String upper = "(.*[A-Z].*)";
        String lower = "(.*[a-z].*)";
        String numbers = "(.*[0-9].*)";
        String special = "(.*[,~,!,@,#,$,%,^,&,*,(,),-,_,=,+,[,{,],},|,;,:,<,>,/,?].*$)";

        if((pass.length()>15) || (pass.length() < 8)){
            System.out.println("Entry must contain over 8 characters\n" +
            "and less than 15.");
            passes = false;
        }if(!pass.matches(upper) || !pass.matches(lower)){
            System.out.println("Entry must contain at least one uppercase and lowercase");
            passes = false;
        }if(!pass.matches(numbers)){
                    System.out.println("Password should contain atleast one number.");
                    passes = false;
        }if(!pass.matches(special)){
                    System.out.println("Password should contain atleast one special character");
                    passes = false;
        }else{
            passes = true;
        }
        return passes;
    //serializable methods
    public void save(ArrayList<SuperUser> obj) throws IOException {

        File file = new File("userInformation.dat");
        FileOutputStream fileOut = new FileOutputStream(file, false);
        BufferedOutputStream buffedOutput = new BufferedOutputStream(fileOut);
        ObjectOutputStream out = new ObjectOutputStream(buffedOutput);
        out.writeObject(obj);
        out.close();
        fileOut.close();
    }

    public ArrayList<SuperUser> get() throws IOException, ClassNotFoundException {
        FileInputStream fileIn = new FileInputStream("userInformation.dat");
        BufferedInputStream buffedInput = new BufferedInputStream(fileIn);
        ObjectInputStream in = new ObjectInputStream(buffedInput);
        users = (ArrayList<SuperUser>) in.readObject();
        in.close();
        fileIn.close();
        return users;
    }

    public class SuperUser implements Serializable {
        private String userName;
        private String password;
        private static Scanner keyboard = new Scanner(System.in);
        private ArrayList<LoginInfo> info = new ArrayList();

        public SuperUser(String name, String pass) {
            userName = name;
            password = pass;
        }

        public String getUser() {
            return userName;
        }

        public void display() {

            String next = keyboard.next();
            //want to add data to LoginInfo arraylist
            if (next.equalsIgnoreCase("add")) {
                add();
            } else if (next.equalsIgnoreCase("delete")) {
                delete();
            } else if (numberCheck(next)) {
                int choice = (int) Integer.parseInt(next) - 1;
                edit(choice);
            //!!!! this: after doing this i lose whatever data i added
            //to the LoginInfo arraylist, right after this the
            //SuperUser arraylist gets saved. but the added data to
            //loginInfo does not
            } else if (next.equalsIgnoreCase("logout")) {
                System.out.println(info.size());
            }
        }

        public boolean numberCheck(String in) {
            try {
                Integer.parseInt(in);
            } catch (NumberFormatException e) {
                return false;
            }
            return true;
        }
        //method to add to the Arraylist
        public void add() {
            System.out.println("What is the website name?:");
            String trash = keyboard.nextLine();
            String webName = keyboard.nextLine();
            System.out.println("The Username?:");
            String webUsername = keyboard.nextLine();
            System.out.println("The Password?:");
            String webPass = keyboard.nextLine();
            info.add(new LoginInfo(webUsername, webPass, webName));
            System.out.println(info.size());
            //method goes back to display
            display();
        }
    }
}
</code>```

答:
You have a list named users. Once you created new SuperUser instance (temp), you are checking that it belongs to this list (users.contains(temp), which is false of course - from where it will occur there?). If it have belonged, the method display would be called, which in turn would add LoginInfo to that SuperUser (add() call), but I bet in reality it doesn't happened.

Also, I see where you read from users (check whether new SuperUser instances belong there), I see where you overwrite it (during desealization) but I don't see adding any instance to there, which makes me think that it is always empty.

Are you sure that SuperUser contains any LoginInfo in its array list?

Body:
So I'm Serializing an ArrayList of ArrayLists essentially but I'm running into an issue. To be honest I'm still pretty new to Java, I've tried so many different methods to fix this as well as searched relentlessly on this site and have not been successful. I know that the way I word things may be hard to follow along or is confusing so I'll post my code here to see. Sorry in advance for all the code. SuperUsers has an arraylist of LoginInfo, PasswordKeeper has an Arraylist of SuperUsers, and the SuperUser arraylist gets serialized in PasswordKeeper. but any changes made to the LoginInfo arraylist do not save and i cannot figure out why. If anyone can help I would really Appreciate it. Thanks

public class PasswordKeeper{

    private ArrayList<SuperUser> users;
    private static Scanner keyboard = new Scanner(System.in);

    public PasswordKeeper() {
        users = new ArrayList();
    }

    public void login() {
        try {
            // reads in SuperUser arraylist
            get();
        } catch (EOFException a) {
            System.out.println("You are the First User!");
        } catch (IOException b) {
            System.out.println(b);
        } catch (ClassNotFoundException c) {
            System.out.println(c);
        }
        boolean loopDisplay = true;
        while (loopDisplay) {
                existingUser = keyboard.next();
                existingPass = keyboard.next();
                SuperUser temp = new SuperUser(existingUser, existingPass);
                System.out.println();
                if (users.contains(temp)) {

                    // viewing superUser method
                    temp.display();
                    //saves after method call is over
                    try {
                        System.out.println("Saving.");
                        save(users);
                    } catch (IOException e) {
                        System.out.println(e);
                    }
                }
            }
            //This happens if there is a new user
            if(answer == 2){
            SuperUser tempNew = null;
            boolean cont = true;
            String newUser;
            String pass;
            while(cont){
                newUser = keyboard.nextLine();
                System.out.println();
                //System.out.println(users.size());

                tempNew = new SuperUser(newUser, pass);
                if(passValid(pass) == true){
                    if(makeSure(tempNew) == true){
                        System.out.println("Login Created!");
                        tempNew = new SuperUser(newUser, pass);
                        //actually being added to the arraylist
                        users.add(tempNew);
                        cont = false;
                    }
                }
            }
            //SuperUser.display method
            tempNew.display();
            try{
                System.out.println("Saving.");
                save(users);
            }catch(IOException e){
                System.out.println(e);
            }
        }
        }
    }
    //makeSure and passValid methods
    public boolean makeSure(SuperUser user){
    if(users.contains(user)){
        return false;
    }
    return true;
}

public boolean passValid(String pass){
        boolean passes = false;
        String upper = "(.*[A-Z].*)";
        String lower = "(.*[a-z].*)";
        String numbers = "(.*[0-9].*)";
        String special = "(.*[,~,!,@,#,$,%,^,&,*,(,),-,_,=,+,[,{,],},|,;,:,<,>,/,?].*$)";

        if((pass.length()>15) || (pass.length() < 8)){
            System.out.println("Entry must contain over 8 characters\n" +
            "and less than 15.");
            passes = false;
        }if(!pass.matches(upper) || !pass.matches(lower)){
            System.out.println("Entry must contain at least one uppercase and lowercase");
            passes = false;
        }if(!pass.matches(numbers)){
                    System.out.println("Password should contain atleast one number.");
                    passes = false;
        }if(!pass.matches(special)){
                    System.out.println("Password should contain atleast one special character");
                    passes = false;
        }else{
            passes = true;
        }
        return passes;
    //serializable methods
    public void save(ArrayList<SuperUser> obj) throws IOException {

        File file = new File("userInformation.dat");
        FileOutputStream fileOut = new FileOutputStream(file, false);
        BufferedOutputStream buffedOutput = new BufferedOutputStream(fileOut);
        ObjectOutputStream out = new ObjectOutputStream(buffedOutput);
        out.writeObject(obj);
        out.close();
        fileOut.close();
    }

    public ArrayList<SuperUser> get() throws IOException, ClassNotFoundException {
        FileInputStream fileIn = new FileInputStream("userInformation.dat");
        BufferedInputStream buffedInput = new BufferedInputStream(fileIn);
        ObjectInputStream in = new ObjectInputStream(buffedInput);
        users = (ArrayList<SuperUser>) in.readObject();
        in.close();
        fileIn.close();
        return users;
    }

    public class SuperUser implements Serializable {
        private String userName;
        private String password;
        private static Scanner keyboard = new Scanner(System.in);
        private ArrayList<LoginInfo> info = new ArrayList();

        public SuperUser(String name, String pass) {
            userName = name;
            password = pass;
        }

        public String getUser() {
            return userName;
        }

        public void display() {

            String next = keyboard.next();
            //want to add data to LoginInfo arraylist
            if (next.equalsIgnoreCase("add")) {
                add();
            } else if (next.equalsIgnoreCase("delete")) {
                delete();
            } else if (numberCheck(next)) {
                int choice = (int) Integer.parseInt(next) - 1;
                edit(choice);
            //!!!! this: after doing this i lose whatever data i added
            //to the LoginInfo arraylist, right after this the
            //SuperUser arraylist gets saved. but the added data to
            //loginInfo does not
            } else if (next.equalsIgnoreCase("logout")) {
                System.out.println(info.size());
            }
        }

        public boolean numberCheck(String in) {
            try {
                Integer.parseInt(in);
            } catch (NumberFormatException e) {
                return false;
            }
            return true;
        }
        //method to add to the Arraylist
        public void add() {
            System.out.println("What is the website name?:");
            String trash = keyboard.nextLine();
            String webName = keyboard.nextLine();
            System.out.println("The Username?:");
            String webUsername = keyboard.nextLine();
            System.out.println("The Password?:");
            String webPass = keyboard.nextLine();
            info.add(new LoginInfo(webUsername, webPass, webName));
            System.out.println(info.size());
            //method goes back to display
            display();
        }
    }
}


问:
Camera Intent - how to?
Sorry to bother you guys, but I am not able to get a solution where In we take picture using intents. I know the default behavior of native camera is to save the picture at default directory/place of O.S. The thing is I have some requirements where I do not want to save the picture when clicked using camera app. There has to be a solution of this issue, be it like once we take a picture we could delete it right away, or there should be an alternate by which we won't allow O.S to save Image, please help.

Here is a piece of code I tried, tried several ways by creating a directory and then deleting file, nothing works.

```<code> public void takeImageFromCamera() {

        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, CAMERA_REQUEST);
    }

  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

// Check for the integer request code originally supplied to startResolutionForResult().
        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {

            if (isCameraPermissionGranted()) {
                bitmap= (Bitmap) data.getExtras().get("data");
              //  bitmap = processReuiredImage(picUri);
                getProfileDetailViaFace(encodeImageBitmapToString(bitmap));
                Log.d("path",String.valueOf(Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES)));

              //  getApplicationContext().getContentResolver().delete(, "/storage/emulated/0/Pictures", null);
            //     mediaStorageDir.getPath().delete();

            } else {
                requestCameraPermission();
            }
        }

public void takeImageFromCamera() {

    File file = getOutputMediaFile(CAMERA_FILE_TYPE);

    if (Build.VERSION.SDK_INT >= 24) {
        try {

            Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
            m.invoke(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    picUri = Uri.fromFile(file);

    Intent takePictureIntent = new
   Intent(MediaStore.ACTION_IMAGE_CAPTURE_SECURE);
    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takePictureIntent, CAMERA_REQUEST);
    }
    }

   private File getOutputMediaFile(int type) {
    mediaStorageDir  = new
     File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), "peppercard");

    /**Create the storage directory if it does not exist*/
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            return null;
        }
    }

    /**Create a media file name*/
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

    if (type == CAMERA_FILE_TYPE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                "IMG_" + timeStamp + ".jpeg");
    } else {
        return null;
    }
</code>```

}
        return mediaFile;

}

答:
Final I have found the answer after waiting from past 2 days, yay..It will not save the file as I am just deleting the file after returning from  the activity.

String[] projection = { MediaStore.Images.Media.DATA };

Cursor cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,                                projection, null, null, null)

int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
 cursor.moveToLast();

```<code>                    String imagePath = cursor.getString(column_index_data);
                    Bitmap bitmapImage = BitmapFactory.decodeFile(imagePath );
                    Log.d("bitmapImage", bitmapImage.toString());                       /*delete file after taking picture*/
                    Log.d("imagePath", imagePath.toString());
                    File f = new File(imagePath);
                    if (f.exists()){
                        f.delete();

                    }
</code>```

sendBroadcast(newIntent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.fromFile(f)));

Title: Camera Intent - how to?

Body:
Sorry to bother you guys, but I am not able to get a solution where In we take picture using intents. I know the default behavior of native camera is to save the picture at default directory/place of O.S. The thing is I have some requirements where I do not want to save the picture when clicked using camera app. There has to be a solution of this issue, be it like once we take a picture we could delete it right away, or there should be an alternate by which we won't allow O.S to save Image, please help.

Here is a piece of code I tried, tried several ways by creating a directory and then deleting file, nothing works.

 public void takeImageFromCamera() {

        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, CAMERA_REQUEST);
    }

  @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {

// Check for the integer request code originally supplied to startResolutionForResult().
        if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {

            if (isCameraPermissionGranted()) {
                bitmap= (Bitmap) data.getExtras().get("data");
              //  bitmap = processReuiredImage(picUri);
                getProfileDetailViaFace(encodeImageBitmapToString(bitmap));
                Log.d("path",String.valueOf(Environment.getExternalStoragePublicDirectory(
                        Environment.DIRECTORY_PICTURES)));

              //  getApplicationContext().getContentResolver().delete(, "/storage/emulated/0/Pictures", null);
            //     mediaStorageDir.getPath().delete();

            } else {
                requestCameraPermission();
            }
        }

public void takeImageFromCamera() {

    File file = getOutputMediaFile(CAMERA_FILE_TYPE);

    if (Build.VERSION.SDK_INT >= 24) {
        try {

            Method m = StrictMode.class.getMethod("disableDeathOnFileUriExposure");
            m.invoke(null);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    picUri = Uri.fromFile(file);

    Intent takePictureIntent = new
   Intent(MediaStore.ACTION_IMAGE_CAPTURE_SECURE);
    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, picUri);
    if (takePictureIntent.resolveActivity(getPackageManager()) != null) {
        startActivityForResult(takePictureIntent, CAMERA_REQUEST);
    }
    }

   private File getOutputMediaFile(int type) {
    mediaStorageDir  = new
     File(Environment.getExternalStoragePublicDirectory(
            Environment.DIRECTORY_PICTURES), "peppercard");

    /**Create the storage directory if it does not exist*/
    if (!mediaStorageDir.exists()) {
        if (!mediaStorageDir.mkdirs()) {
            return null;
        }
    }

    /**Create a media file name*/
    String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());

    if (type == CAMERA_FILE_TYPE) {
        mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                "IMG_" + timeStamp + ".jpeg");
    } else {
        return null;
    }

}
        return mediaFile;

}

Body:
Final I have found the answer after waiting from past 2 days, yay..It will not save the file as I am just deleting the file after returning from  the activity.

String[] projection = { MediaStore.Images.Media.DATA };

Cursor cursor = managedQuery(MediaStore.Images.Media.EXTERNAL_CONTENT_URI,                                projection, null, null, null)

int column_index_data = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
 cursor.moveToLast();

                    String imagePath = cursor.getString(column_index_data);
                    Bitmap bitmapImage = BitmapFactory.decodeFile(imagePath );
                    Log.d("bitmapImage", bitmapImage.toString());                       /*delete file after taking picture*/
                    Log.d("imagePath", imagePath.toString());
                    File f = new File(imagePath);
                    if (f.exists()){
                        f.delete();

                    }

sendBroadcast(newIntent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE,Uri.fromFile(f)));