问:
Sidebar with Affix not working
I'm not really a developer but I'm ok with HTML and CSS. I'm trying to build a site with Bootstrap 3.3.7 and I've taken some code from an example I found at Codeply to have a sidebar stick when the user scrolls down.

However, when I paste their code into my page, the sidebar doesn't stick. It just scrolls past the sidebar. Since I'm not very experienced, I've probably made a silly mistake somewhere but I'm stumped.

Here's my HTML:

```<code><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-
 to-fit=no">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/sidebar.css">
<link rel="stylesheet" href="css/style2.css" />
<title>Title</title>
</head>
<title>

</title>
<nav class="navbar navbar-default navbar-fixed-top" role="banner">
<div class="container">
  <div class="navbar-header">
  <button class="navbar-toggle" type="button" data-toggle="collapse" data-
  target=".navbar-collapse">
    <span class="sr-only">Toggle navigation</span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
    <span class="icon-bar"></span>
  </button>
  <a href="/" class="navbar-brand">Explorify</a>
  </div>
</div>
</nav>

<div id="masthead">
<div class="container">
  <div class="row">
    <div class="col-md-7">
      <h1>Tongues
      </h1>
    </div>
  </div>
</div><!--/container-->
</div><!--/masthead-->

<!--main-->
<div class="container">
<div class="row">
  <!--left-->
  <div class="col-md-3" id="leftCol">
    <ul class="nav nav-stacked" id="sidebar">
      <li><a href="#sec0">Section 0</a></li>
      <li><a href="#sec1">Section 1</a></li>
      <li><a href="#sec2">Section 2</a></li>
      <li><a href="#sec3">Section 3</a></li>
      <li><a href="#sec4">Section 4</a></li>
    </ul>
  </div><!--/left-->

  <!--right-->
  <div class="col-md-9">
    <h2 id="sec0">Content</h2>
    <p>
      At Bootply we like to build simple Bootstrap templates that utilize
      the code Bootstap CSS without a lot of customization. Sure you can
      find a lot of Bootstrap themes and inspiration, but these templates
      tend to be heavy on customization.</p>

    <hr>
    <p>
      Rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi
      architecto beatae vitae
      </p>

    <h2 id="sec1">Content</h2>
    <p>
      Rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi
      architecto beatae vitae
      dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit
      aspernatur aut odit aut.
    </p>
    <div class="row">
      <div class="col-md-12">
        <div class="panel panel-default">
          <div class="panel-heading"><h3>Hello.</h3></div>
          <div class="panel-body">Lorem ipsum dolor sit amet, consectetur
            adipiscing elit. Duis pharetra varius quam sit amet vulputate.
            Quisque mauris augue
          </div>
        </div>
      </div>

    </div>
    <hr>
    <h2 id="sec2">Section 2</h2>
    <p>
      Rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi
      architecto beatae vitae
    </p>
    <div class="row">
      <div class="col-md-4"><img src="//placehold.it/300x300" class="img-
      responsive"></div>
      <div class="col-md-4"><img src="//placehold.it/300x300" class="img-
      responsive"></div>
      <div class="col-md-4"><img src="//placehold.it/300x300" class="img-
      responsive"></div>
    </div>
    <hr>
    <h2 id="sec3">Section 3</h2>
    <p>
      Images are responsive sed @mdo but sum are more fun peratis unde omnis
    </p>
    <p>
      Fos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est,
      qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit,
    </p>
    <h2 id="sec4">Section 4</h2>
    <p>
      Sed ut perspiciatis unde omnis iste natus error sit voluptatem </p>

    <hr>
    <h4><a href="http://www.bootply.com/Gygh9swISB">Edit on Bootply</a></h4>
    <hr>

    </div><!--/right-->
</div><!--/row-->
</div><!--/container-->
<script src="js/scripts.js"></script>
<script src="js/bootstrap.js"></script>
<script src="js/jquery.slim.min.js"></script>
<script src="js/tether.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
</code>```

Apologies for posting the entire index.html but I'm wondering if it has something to do with how I've linked the javascript. I pasted the js code from the example into scripts.js and the CSS into style2.css.

I appreciate any help the community could give me!

答:
I dont know exactly what your mistake is but I guess you referenced different js and css files than the codeply or referenced them in the wrong order.

Click here for a working version. (Make sure to increase the width of the result page though..)

```<code><link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" />
<script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</code>```

Title: Sidebar with Affix not working

Body:
I'm not really a developer but I'm ok with HTML and CSS. I'm trying to build a site with Bootstrap 3.3.7 and I've taken some code from an example I found at Codeply to have a sidebar stick when the user scrolls down.

However, when I paste their code into my page, the sidebar doesn't stick. It just scrolls past the sidebar. Since I'm not very experienced, I've probably made a silly mistake somewhere but I'm stumped.

Here's my HTML:

<!DOCTYPE html>

<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-
 to-fit=no">
<link rel="stylesheet" href="css/bootstrap.min.css">
<link rel="stylesheet" href="css/bootstrap-theme.min.css">
<link rel="stylesheet" href="css/sidebar.css">
<link rel="stylesheet" href="css/style2.css" />
<title>Title</title>

<title>

</title>

  <button class="navbar-toggle" type="button" data-toggle="collapse" data-
  target=".navbar-collapse">
    Toggle navigation

  </button>
  Explorify

Tongues

Section 0

Section 1

Section 2

Section 3

Section 4

Content

      At Bootply we like to build simple Bootstrap templates that utilize
      the code Bootstap CSS without a lot of customization. Sure you can
      find a lot of Bootstrap themes and inspiration, but these templates
      tend to be heavy on customization.

      Rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi
      architecto beatae vitae

Content

      Rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi
      architecto beatae vitae
      dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit
      aspernatur aut odit aut.

Hello.

Lorem ipsum dolor sit amet, consectetur
            adipiscing elit. Duis pharetra varius quam sit amet vulputate.
            Quisque mauris augue

Section 2

      Rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi
      architecto beatae vitae

Section 3

      Images are responsive sed @mdo but sum are more fun peratis unde omnis

      Fos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est,
      qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit,

Section 4

      Sed ut perspiciatis unde omnis iste natus error sit voluptatem

Edit on Bootply

Apologies for posting the entire index.html but I'm wondering if it has something to do with how I've linked the javascript. I pasted the js code from the example into scripts.js and the CSS into style2.css.

I appreciate any help the community could give me!

Body:
I dont know exactly what your mistake is but I guess you referenced different js and css files than the codeply or referenced them in the wrong order.

Click here for a working version. (Make sure to increase the width of the result page though..)

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.css" />
<script src="https://code.jquery.com/jquery-3.1.1.js" integrity="sha256-16cdPddA6VdVInumRGo6IbivbERE8p7CQR3HzTBuELA=" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>


来源: stackexchange

问:
VS SetupProject registry entry for custom file-extensions
Within my project I create backup-files with a custom extension ".tp"

The software will be distributed with a Setup Project as an installer.

Which steps do I have to follow in order to add a registry entry via Setup project to let the OS show my custom icon? Is that possible?

I found a few solutions on how to do it manually, but I would like to have the installer (Setup project) to do it for me...
Could not find anything on that...

info:
I use Visual Studio Express 2017
Software is written in C#

EDIT:
In the meantime I was able to add a registry entry into the right directory, but I am not sure how to point to the .ico file, and on how to call SHChangeNotify...

答:
Visual Studio setup projects have a File Types on Target Machine editor, so there's no need for registry manipulation. If you add a new file type (your .tp) the IDE's property window on the .tp (hit F4) will show a window where you add your icon. The %Open properties window is where you add the program to open the extension. It's not overly complicated. This seems to cover it in extra detail:

http://www.dreamincode.net/forums/topic/58005-file-associations-in-visual-studio/

ContentLicense: CC BY-SA 3.0


问:
Using MagicMock to test the inner components of a method
I'm new to using the mock library and unit testing in general.  I think I understand how the mock library works, but I think there is something wrong with my approach.

Lets say I have a class Foo that has a method addFoo(bar1, bar2) and addFoo calls other 'private' methods within foo, but can also raise exceptions at various parts in the code... i.e.

```<code>class Foo:
    def __init__(self):
         # This creates lots of dependencies

    def _inner1(self, bar):
        if this_doesnt_work:
           return None
        return modified_bar1

    def _inner2(self, bar2):
        if this_doesnt_work:
           return None
        return modified_bar2

    def addFoo(bar1, bar2):
        if self._inner1(bar1) and self._inner2(bar2):
           #do something
        else:
           raise SomeException
</code>```

When I unit test, what I currently do is mock out Foo.__init__ in my unit test setup and set return_value to None.  This works and allows me to run tests against my methods in the class without all the external dependencies and just mock any class attributes with my mocked Foo.__init__ instance.

After that is done if I wanted to unit test addFoo I would do the following (skipping a bunch of steps):

```<code>@patch.object(Foo, '_inner2')
@patch.object(Foo, '_inner1')
def test_inner1_exception(self, mock_inner1, mock_inner2):
    mock_inner1.side_effect = Exception
    # then do some asserts to make sure it worked
</code>```

QUESTION
How do I test an exception in addFoo if the code looks like this:

```<code>def addFoo(bar1, bar2):
    bars = self._getBars() #something that returns a list
    my_modified_bar_list = []
    for bar in bars:
        my_modified_bar_list.append(self._inner1(bar))

    if len(my_modified_bar_list) == 0:
        raise SomeException
</code>```

In this instance how do I test SomeException when it is dependent upon the values produced by some array within my method?

答:
If you are making use of pytest you can assert about expected exceptions as follows:

```<code>@patch('Foo._getBars', return_value=[])
def test_addFoo_exception(self):
    foo = Foo()
    with pytest.raises(SomeException):
        foo.addFoo(Mock(), Mock())
</code>```

As snippet above shows, by mocking _getBars you are in control of what it is returned and can therefore force the condition that triggers the exception in your code, in this case an empty list.

I have written a short post with common unit testing pitfalls in Python that you might find useful.

Body:
I'm new to using the mock library and unit testing in general.  I think I understand how the mock library works, but I think there is something wrong with my approach.

Lets say I have a class Foo that has a method addFoo(bar1, bar2) and addFoo calls other 'private' methods within foo, but can also raise exceptions at various parts in the code... i.e.

class Foo:
    def __init__(self):
         # This creates lots of dependencies

    def _inner1(self, bar):
        if this_doesnt_work:
           return None
        return modified_bar1

    def _inner2(self, bar2):
        if this_doesnt_work:
           return None
        return modified_bar2

    def addFoo(bar1, bar2):
        if self._inner1(bar1) and self._inner2(bar2):
           #do something
        else:
           raise SomeException

When I unit test, what I currently do is mock out Foo.__init__ in my unit test setup and set return_value to None.  This works and allows me to run tests against my methods in the class without all the external dependencies and just mock any class attributes with my mocked Foo.__init__ instance.

After that is done if I wanted to unit test addFoo I would do the following (skipping a bunch of steps):

@patch.object(Foo, '_inner2')
@patch.object(Foo, '_inner1')
def test_inner1_exception(self, mock_inner1, mock_inner2):
    mock_inner1.side_effect = Exception
    # then do some asserts to make sure it worked

QUESTION
How do I test an exception in addFoo if the code looks like this:

def addFoo(bar1, bar2):
    bars = self._getBars() #something that returns a list
    my_modified_bar_list = []
    for bar in bars:
        my_modified_bar_list.append(self._inner1(bar))

    if len(my_modified_bar_list) == 0:
        raise SomeException

In this instance how do I test SomeException when it is dependent upon the values produced by some array within my method?

Body:
If you are making use of pytest you can assert about expected exceptions as follows:

@patch('Foo._getBars', return_value=[])
def test_addFoo_exception(self):
    foo = Foo()
    with pytest.raises(SomeException):
        foo.addFoo(Mock(), Mock())

As snippet above shows, by mocking _getBars you are in control of what it is returned and can therefore force the condition that triggers the exception in your code, in this case an empty list.

I have written a short post with common unit testing pitfalls in Python that you might find useful.


问:
Python - Unexpected break in for-loop while using Popen
I need to call one script multiple times but with different arguments. Arguments are stored in argument_list and its list of strings.

```<code>for argument in argument_list:
    python_command = "python another_script.py --server " + argument
    p = Popen(python_command,shell=True, stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate()
</code>```

The problem is that after one iteration, the script breaks from for loop, even though there are still items in argument_list and there is  no break in loop.

Anyone know why does it happend and how can i solve it? Thanks for any advice.

答:
```<code>python_command = "python another_script.py --server " + argument
</code>```

The parameters for Popen have to be put in a sequence:

```<code>python_command = ["python", "another_script.py", "--server", argument]
</code>```

Also, a suggestion: Try to put the Popen statement in a try ... except, so that if there is an error, you will get a more detailed explanation about the cause.

Body:
I need to call one script multiple times but with different arguments. Arguments are stored in argument_list and its list of strings.

for argument in argument_list:
    python_command = "python another_script.py --server " + argument
    p = Popen(python_command,shell=True, stdout=PIPE, stderr=PIPE)
    stdout, stderr = p.communicate()

The problem is that after one iteration, the script breaks from for loop, even though there are still items in argument_list and there is  no break in loop.

Anyone know why does it happend and how can i solve it? Thanks for any advice.

Body:
python_command = "python another_script.py --server " + argument

The parameters for Popen have to be put in a sequence:

python_command = ["python", "another_script.py", "--server", argument]

Also, a suggestion: Try to put the Popen statement in a try ... except, so that if there is an error, you will get a more detailed explanation about the cause.


问:
How can i remove the commas between words and make them go under each subheading
my python code so far is:

```<code>list=("Member ID, Surname, Year joined, Nights booked, Membership status, Points balance")
f = open("SampleData2017.txt")
print(list)
for surname in f.readlines():
   print(surname)
</code>```

however when i run it the items are only seperated by commas and not under each subheading

i want it to look like:

```<code>MemberID  Surname  Year  joined Membershipstatus  Nightsbooked  Points balance
Gri33415 Griffiths    2015         Gold               35          40000

Smi22316  Smith       2016        Silver              3            7500
</code>```

how would i fix this? as simple as possible please

答:
Sounds like you have a list of headers, and a table full of data you're pulling from SampleData2017.txt. There's a third-party module called tabulate that I use a lot for this because it keeps me from having to write a bunch of code for a simple task.

Install it from pypi using pip on your command line.

```<code>$ pip install tabulate
</code>```

or on Python3

```<code>$ pip3 install tabulate
</code>```

Then write code:

```<code>import tabulate

headers = map(str.strip, "Member ID, Surname, Year joined, Nights booked, Membership status, Points balance".split(","))
# or just format it yourself:
headers = ("Member ID", "Surname", "Year joined", "Nights booked",
           "Membership status", "Points balance")

with open("SampleData2017.txt") as f:
    # you never say how each row is split into fields, so I'm assuming here
    # that it's comma-separated and calling str.split(",") on each
    table = tabulate.tabulate((line.split(",") for line in f), headers=headers)
</code>```

With my sample data here, the output is:

```<code>>>> headers = ("one", "two", "three")
>>> data = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]

>>> print(tabulate.tabulate(data, headers=headers))
  one    two    three
-----  -----  -------
    1      2        3
    4      5        6
    7      8        9
</code>```

Body:
my python code so far is:

list=("Member ID, Surname, Year joined, Nights booked, Membership status, Points balance")
f = open("SampleData2017.txt")
print(list)
for surname in f.readlines():
   print(surname)

however when i run it the items are only seperated by commas and not under each subheading

i want it to look like:

MemberID  Surname  Year  joined Membershipstatus  Nightsbooked  Points balance
Gri33415 Griffiths    2015         Gold               35          40000

Smi22316  Smith       2016        Silver              3            7500

how would i fix this? as simple as possible please

Body:
Sounds like you have a list of headers, and a table full of data you're pulling from SampleData2017.txt. There's a third-party module called tabulate that I use a lot for this because it keeps me from having to write a bunch of code for a simple task.

Install it from pypi using pip on your command line.

$ pip install tabulate

or on Python3

$ pip3 install tabulate

Then write code:

import tabulate

headers = map(str.strip, "Member ID, Surname, Year joined, Nights booked, Membership status, Points balance".split(","))
# or just format it yourself:
headers = ("Member ID", "Surname", "Year joined", "Nights booked",
           "Membership status", "Points balance")

with open("SampleData2017.txt") as f:
    # you never say how each row is split into fields, so I'm assuming here
    # that it's comma-separated and calling str.split(",") on each
    table = tabulate.tabulate((line.split(",") for line in f), headers=headers)

With my sample data here, the output is:

>>> headers = ("one", "two", "three")
>>> data = [(1, 2, 3), (4, 5, 6), (7, 8, 9)]

>>> print(tabulate.tabulate(data, headers=headers))
  one    two    three
-----  -----  -------
    1      2        3
    4      5        6
    7      8        9


问:
Flink Socket Source - words encoded in UTF cannot be read by Flink
I am trying to let Flink read some streaming text input from a socket connection.

In my input socket's code, I used the following to publish the text for Flink to receive:

```<code>outputStream.writeUTF(new String(message.getPayload()));
</code>```

However, in Flink, I couldn't read the incoming text even though the connections are working. I Google-d and found that I might need to read the text using readUTF(). In other word it's mainly due to encoding. However, these are done on InputStream; Flink doesn't have that as my inputs are in the form of DataStream<String>:

```<code>DataStream<String> text = env.socketTextStream("localhost", port, "\n");
</code>```

Can anyone advise me on this? Thank you!

答:
What is your program trying to accomplish?
These are the use cases for Flink, and if you are not trying to achieve one of these, I would recommend using Java sockets if you are just doing low-level network communication

If using Java, it is quite simple.  You need to get the data input stream from the socket, then convert the incoming bytes back into a string.  For example, here is what has worked for me

```<code>Socket socket = new Socket(HOST_IP, PORT);

DataInputStream in = new DataInputStream(socket.getInputStream());
byte[] buffer = new byte[256];
while ((i = in.read(buffer, 0, buffer.length)) != -1)
{
    String input = new String(buffer, "UTF-8");
}
</code>```

Body:
I am trying to let Flink read some streaming text input from a socket connection.

In my input socket's code, I used the following to publish the text for Flink to receive:

outputStream.writeUTF(new String(message.getPayload()));

However, in Flink, I couldn't read the incoming text even though the connections are working. I Google-d and found that I might need to read the text using readUTF(). In other word it's mainly due to encoding. However, these are done on InputStream; Flink doesn't have that as my inputs are in the form of DataStream<String>:

DataStream<String> text = env.socketTextStream("localhost", port, "\n");

Can anyone advise me on this? Thank you!

Body:
What is your program trying to accomplish?
These are the use cases for Flink, and if you are not trying to achieve one of these, I would recommend using Java sockets if you are just doing low-level network communication

If using Java, it is quite simple.  You need to get the data input stream from the socket, then convert the incoming bytes back into a string.  For example, here is what has worked for me

Socket socket = new Socket(HOST_IP, PORT);

DataInputStream in = new DataInputStream(socket.getInputStream());
byte[] buffer = new byte[256];
while ((i = in.read(buffer, 0, buffer.length)) != -1)
{
    String input = new String(buffer, "UTF-8");
}


问:
How to debug unit tests written in Typescript with Mocha from Visual Studio Code
I write a Typescript library. The unit tests are also written in Typescript using Mocha framework. I'd like to execute the unit tests directly without compiling into javascript.
This works with this command:

```<code>./node_modules/mocha/bin/mocha  ./test/*.test.ts  --require ts-node/register
</code>```

I try to debug the unit test from Visual Studio Code with the following launch settings:

```<code>{
    "type": "node",
    "request": "launch",
    "name": "Mocha Tests",
    "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
    "args": [
        "--require",
        "ts-node/register",
        "${workspaceRoot}/test/*.test.ts"
    ],
    "internalConsoleOptions": "openOnSessionStart"
}
</code>```

This way I can debug Mocha itself from VS Code, but not the unit tests. Mocha spawns separate processes for the tests and the debugger can not automatically attach to the child processes.

What is the right way to debug Typescript unit tests from Visual Studio Code?

答:
If anybody finds it useful, the following launch.json configuration snippet is working for me without any workaround:

```<code>    {
    "name": "mocha tests",
    "type": "node",
    "protocol" : "inspector",
    "request": "launch",
    "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
    "stopOnEntry": false,
    "args": [ "--compilers", "ts:ts-node/register", "--no-timeouts", "${relativeFile}"],
    "cwd": "${workspaceRoot}"
    }
</code>```

Works fine for me with node v7.10.0, typescript 2.4.0 and Visual Studio Code 1.13.1 . Both mocha and typescript are installed locally under node_modules.

Body:
I write a Typescript library. The unit tests are also written in Typescript using Mocha framework. I'd like to execute the unit tests directly without compiling into javascript.
This works with this command:

./node_modules/mocha/bin/mocha  ./test/*.test.ts  --require ts-node/register

I try to debug the unit test from Visual Studio Code with the following launch settings:

{
    "type": "node",
    "request": "launch",
    "name": "Mocha Tests",
    "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
    "args": [
        "--require",
        "ts-node/register",
        "${workspaceRoot}/test/*.test.ts"
    ],
    "internalConsoleOptions": "openOnSessionStart"
}

This way I can debug Mocha itself from VS Code, but not the unit tests. Mocha spawns separate processes for the tests and the debugger can not automatically attach to the child processes.

What is the right way to debug Typescript unit tests from Visual Studio Code?

Body:
If anybody finds it useful, the following launch.json configuration snippet is working for me without any workaround:

    {
    "name": "mocha tests",
    "type": "node",
    "protocol" : "inspector",
    "request": "launch",
    "program": "${workspaceRoot}/node_modules/mocha/bin/_mocha",
    "stopOnEntry": false,
    "args": [ "--compilers", "ts:ts-node/register", "--no-timeouts", "${relativeFile}"],
    "cwd": "${workspaceRoot}"
    }

Works fine for me with node v7.10.0, typescript 2.4.0 and Visual Studio Code 1.13.1 . Both mocha and typescript are installed locally under node_modules.

ContentLicense: CC BY-SA 4.0


问:
How to get remote ip in Django forms.py
I have customized forms.py in virtual environment on path "lib/python3.5/site-packages/django/contrib/auth" and it works great!

However I need now to grab remote ip from user in  def confirm_login_allowed

I know that I need to grab from request but in the class AuthenticationForm where this model is located, the request is overwritten in __init_.

Do you know what should I do to get self.request.META['REMOTE_ADDR']

```<code>class AuthenticationForm(forms.Form):
    """
    Base class for authenticating users. Extend this to get a form that accepts
    username/password logins.
    """
    username = UsernameField(
        max_length=254,
        widget=forms.TextInput(attrs={'autofocus': True}),
    )
    password = forms.CharField(
        label=_("Password"),
        strip=False,
        widget=forms.PasswordInput,
    )

    error_messages = {
        'invalid_login': _(
            "Please enter a correct %(username)s and password. Note that both "
            "fields may be case-sensitive."
        ),
        'inactive': _("This account is inactive."),
        'IP': _("You tried to login from to much different IP address in last 24 hours. Contact administrator.")
    }

    def __init__(self, request=None, *args, **kwargs):
        """
        The 'request' parameter is set for custom auth use by subclasses.
        The form data comes in via the standard 'data' kwarg.
        """
        self.request = request
        self.user_cache = None
        super(AuthenticationForm, self).__init__(*args, **kwargs)

        # Set the label for the "username" field.
        self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD)
        if self.fields['username'].label is None:
            self.fields['username'].label = capfirst(self.username_field.verbose_name)

    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username is not None and password:

            self.user_cache = authenticate(self.request, username=username, password=password)

            # self.ip_remote= self.request.META['REMOTE_ADDR']
            if self.user_cache is None:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'],
                    code='invalid_login',
                    params={'username': self.username_field.verbose_name},
                )
            else:
                self.confirm_login_allowed(self.user_cache)

        return self.cleaned_data

    def confirm_login_allowed(self, user):
        """
        Controls whether the given User may log in. This is a policy setting,
        independent of end-user authentication. This default behavior is to
        allow login by active users, and reject login by inactive users.

        If the given user cannot log in, this method should raise a
        ``forms.ValidationError``.

        If the given user may log in, this method should return None.
        """

        from mysql_queries import user_ips
        #check user status, how many ip's he had over last 24 hours
        user_status = user_ips(user)

        if user_status == 400:
            raise forms.ValidationError(
                self.error_messages['IP'],
                code='IP',
            )

        if not user.is_active:
            raise forms.ValidationError(
                self.error_messages['inactive'],
                code='inactive',
            )

    def get_user_id(self):
        if self.user_cache:
            return self.user_cache.id
        return None

    def get_user(self):
        return self.user_cache
</code>```

答:
This should work. If it doesn't work, check what is current ip address of the user and then check do you have that ip in your table where you record them. You should place this code right after you import module.</p>

```<code>        remote_status = self.request.META['REMOTE_ADDR']
        rstat = ip_remote(remote_status)
        if rstat == 500:
           raise forms.ValidationError(
                self.error_messages['Remote'],
                code='Remote',
           )
</code>```

Title: How to get remote ip in Django forms.py

Body:
I have customized forms.py in virtual environment on path "lib/python3.5/site-packages/django/contrib/auth" and it works great!

However I need now to grab remote ip from user in  def confirm_login_allowed

I know that I need to grab from request but in the class AuthenticationForm where this model is located, the request is overwritten in __init_.

Do you know what should I do to get self.request.META['REMOTE_ADDR']

class AuthenticationForm(forms.Form):
    """
    Base class for authenticating users. Extend this to get a form that accepts
    username/password logins.
    """
    username = UsernameField(
        max_length=254,
        widget=forms.TextInput(attrs={'autofocus': True}),
    )
    password = forms.CharField(
        label=_("Password"),
        strip=False,
        widget=forms.PasswordInput,
    )

    error_messages = {
        'invalid_login': _(
            "Please enter a correct %(username)s and password. Note that both "
            "fields may be case-sensitive."
        ),
        'inactive': _("This account is inactive."),
        'IP': _("You tried to login from to much different IP address in last 24 hours. Contact administrator.")
    }

    def __init__(self, request=None, *args, **kwargs):
        """
        The 'request' parameter is set for custom auth use by subclasses.
        The form data comes in via the standard 'data' kwarg.
        """
        self.request = request
        self.user_cache = None
        super(AuthenticationForm, self).__init__(*args, **kwargs)

        # Set the label for the "username" field.
        self.username_field = UserModel._meta.get_field(UserModel.USERNAME_FIELD)
        if self.fields['username'].label is None:
            self.fields['username'].label = capfirst(self.username_field.verbose_name)

    def clean(self):
        username = self.cleaned_data.get('username')
        password = self.cleaned_data.get('password')

        if username is not None and password:

            self.user_cache = authenticate(self.request, username=username, password=password)

            # self.ip_remote= self.request.META['REMOTE_ADDR']
            if self.user_cache is None:
                raise forms.ValidationError(
                    self.error_messages['invalid_login'],
                    code='invalid_login',
                    params={'username': self.username_field.verbose_name},
                )
            else:
                self.confirm_login_allowed(self.user_cache)

        return self.cleaned_data

    def confirm_login_allowed(self, user):
        """
        Controls whether the given User may log in. This is a policy setting,
        independent of end-user authentication. This default behavior is to
        allow login by active users, and reject login by inactive users.

        If the given user cannot log in, this method should raise a
        ``forms.ValidationError``.

        If the given user may log in, this method should return None.
        """

        from mysql_queries import user_ips
        #check user status, how many ip's he had over last 24 hours
        user_status = user_ips(user)

        if user_status == 400:
            raise forms.ValidationError(
                self.error_messages['IP'],
                code='IP',
            )

        if not user.is_active:
            raise forms.ValidationError(
                self.error_messages['inactive'],
                code='inactive',
            )

    def get_user_id(self):
        if self.user_cache:
            return self.user_cache.id
        return None

    def get_user(self):
        return self.user_cache

Body:
This should work. If it doesn't work, check what is current ip address of the user and then check do you have that ip in your table where you record them. You should place this code right after you import module.

        remote_status = self.request.META['REMOTE_ADDR']
        rstat = ip_remote(remote_status)
        if rstat == 500:
           raise forms.ValidationError(
                self.error_messages['Remote'],
                code='Remote',
           )


问:
Input mouse position not captured accurately?
I am getting the Mouse-Input to draw a line onto a Texture from point A to point B. I've realized that I am not hitting every pixel, so moving my Mouse from the very left to the very right of the screen, it will skip some values, leading to gaps. When I move my mouse slowly it get's better.

I am getting the mouse position using:

```<code>var viewPortPosition = Camera.main.ScreenToViewportPoint (Input.mousePosition);
</code>```

答:
If you want to draw a line I suggest you using the line renderer. Assuming you implemented the code in the Update() function - this is called every frame rendered. So even though your movement is quite slow, obviously it is already sufficient enough to leave gaps in your drawn lines.

Below is some code from this link which should work fine for you:

```<code>using System.Collections.Generic;
 using UnityEngine;

 [RequireComponent(typeof(LineRenderer))]
 public class LineRendererTest : MonoBehaviour
 {
     List<Vector3> linePoints = new List<Vector3>();
     LineRenderer lineRenderer;
     public float startWidth = 1.0f;
     public float endWidth = 1.0f;
     public float threshold = 0.001f;
     Camera thisCamera;
     int lineCount = 0;

     Vector3 lastPos = Vector3.one * float.MaxValue;

     void Awake()
     {
         thisCamera = Camera.main;
         lineRenderer = GetComponent<LineRenderer>();
     }

     void Update()
     {
         Vector3 mousePos = Input.mousePosition;
         mousePos.z = thisCamera.nearClipPlane;
         Vector3 mouseWorld = thisCamera.ScreenToWorldPoint(mousePos);

         float dist = Vector3.Distance(lastPos, mouseWorld);
         if(dist <= threshold)
             return;

         lastPos = mouseWorld;
         if(linePoints == null)
             linePoints = new List<Vector3>();
         linePoints.Add(mouseWorld);

         UpdateLine();
     }

     void UpdateLine()
     {
         lineRenderer.SetWidth(startWidth, endWidth);
         lineRenderer.SetVertexCount(linePoints.Count);

         for(int i = lineCount; i < linePoints.Count; i++)
         {
             lineRenderer.SetPosition(i, linePoints[i]);
         }
         lineCount = linePoints.Count;
     }
</code>```

Body:
I am getting the Mouse-Input to draw a line onto a Texture from point A to point B. I've realized that I am not hitting every pixel, so moving my Mouse from the very left to the very right of the screen, it will skip some values, leading to gaps. When I move my mouse slowly it get's better.

I am getting the mouse position using:

var viewPortPosition = Camera.main.ScreenToViewportPoint (Input.mousePosition);

Body:
If you want to draw a line I suggest you using the line renderer. Assuming you implemented the code in the Update() function - this is called every frame rendered. So even though your movement is quite slow, obviously it is already sufficient enough to leave gaps in your drawn lines.

Below is some code from this link which should work fine for you:

using System.Collections.Generic;
 using UnityEngine;

 [RequireComponent(typeof(LineRenderer))]
 public class LineRendererTest : MonoBehaviour
 {
     List<Vector3> linePoints = new List<Vector3>();
     LineRenderer lineRenderer;
     public float startWidth = 1.0f;
     public float endWidth = 1.0f;
     public float threshold = 0.001f;
     Camera thisCamera;
     int lineCount = 0;

     Vector3 lastPos = Vector3.one * float.MaxValue;

     void Awake()
     {
         thisCamera = Camera.main;
         lineRenderer = GetComponent<LineRenderer>();
     }

     void Update()
     {
         Vector3 mousePos = Input.mousePosition;
         mousePos.z = thisCamera.nearClipPlane;
         Vector3 mouseWorld = thisCamera.ScreenToWorldPoint(mousePos);

         float dist = Vector3.Distance(lastPos, mouseWorld);
         if(dist <= threshold)
             return;

         lastPos = mouseWorld;
         if(linePoints == null)
             linePoints = new List<Vector3>();
         linePoints.Add(mouseWorld);

         UpdateLine();
     }

     void UpdateLine()
     {
         lineRenderer.SetWidth(startWidth, endWidth);
         lineRenderer.SetVertexCount(linePoints.Count);

         for(int i = lineCount; i < linePoints.Count; i++)
         {
             lineRenderer.SetPosition(i, linePoints[i]);
         }
         lineCount = linePoints.Count;
     }


问:
rails will_paginate with JQuery UI Tabs
I would like to know if it is possible to add pagination with will_paginate for each of the tabs in a JQuery UI Tabs.

For exemple, I have two tabs, one with ten element and one with thirty. Is it possible to add pagination for each ten elements in order to have the first tab without pagination and the second with three pages?

Thank you

答: Yes that is possible. All will_paginate do is generate the correct URLs for each set of resources. </p>

ContentLicense: CC BY-SA 2.5

Title: rails will_paginate with JQuery UI Tabs


问:
Render Datatables Boolean Column
I have datatables returning the data using server side processing. I have not modified the basic example given from data tables.

I have some boolean columns that I want to render as icons e.g. 1 = Green tick 0 = red cross or something similar. It currently looks like this.
How would I go about rendering just 3 columns?

here's the code, i've tried, however this results in the whole table being blank...

```<code>    $(document).ready(function() {
    $('#log').dataTable( {
        "bProcessing": true,
        "bServerSide": true,
        "sAjaxSource": "assetlog.php"
    "columns": [
          { "data": "id" },
           { "data": "assetcode" },
           { "data": "name"},
           { "data": "shift" }
           { "data": "datetime" },
           { "data": "stop_production" },
           { "data": "furtheractions" }
           { "data": "jobcomplete" },
           { "data": "duration" },
           ],
           "columnDefs": [
                      {
                          "render": function (data, type, row) {
                              return (data === true) ? '<span class="glyphicon glyphicon-ok"></span>' : '<span class="glyphicon glyphicon-remove"></span>';
                          },
                          "targets": 6
                      }
                  ]

    } );
} );
</code>```

Thanks

答:
It may be a little late but I actually had the same problem. Here is a short code to replace the values "1" and "0" by a green Bootstrap tick or a red Bootstrap cross:

```<code>function remplacerBool(tableauID, boolClass) {
  $(tableauID + ' tr').each(function (i, row) {
    $('td', this).each(function (j, cell) {
      if ($(tableauID + ' th').eq(j).hasClass( boolClass )) {
        if (cell.innerHTML == '1') {cell.innerHTML = '<div class="text-center text-success"><span class="glyphicon glyphicon-ok-circle"></span></div>';}
        if (cell.innerHTML == '0') {cell.innerHTML = '<div class="text-center text-danger"><span class="glyphicon glyphicon-remove-circle"></span></div>';}
      }
    });
  });
};
</code>```

All you have to do is:

precise in the th of the table head which columns should get a particular class if they contain boolean values. For example, I use

call the function with these two arguments:

the table ID

the name of the class the function should recognize as boolean

Title: Render Datatables Boolean Column

Body:
I have datatables returning the data using server side processing. I have not modified the basic example given from data tables.

I have some boolean columns that I want to render as icons e.g. 1 = Green tick 0 = red cross or something similar. It currently looks like this.
How would I go about rendering just 3 columns?

here's the code, i've tried, however this results in the whole table being blank...

    $(document).ready(function() {
    $('#log').dataTable( {
        "bProcessing": true,
        "bServerSide": true,
        "sAjaxSource": "assetlog.php"
    "columns": [
          { "data": "id" },
           { "data": "assetcode" },
           { "data": "name"},
           { "data": "shift" }
           { "data": "datetime" },
           { "data": "stop_production" },
           { "data": "furtheractions" }
           { "data": "jobcomplete" },
           { "data": "duration" },
           ],
           "columnDefs": [
                      {
                          "render": function (data, type, row) {
                              return (data === true) ? '' : '';
                          },
                          "targets": 6
                      }
                  ]

    } );
} );

Thanks

Body:
It may be a little late but I actually had the same problem. Here is a short code to replace the values "1" and "0" by a green Bootstrap tick or a red Bootstrap cross:

function remplacerBool(tableauID, boolClass) {
  $(tableauID + ' tr').each(function (i, row) {
    $('td', this).each(function (j, cell) {
      if ($(tableauID + ' th').eq(j).hasClass( boolClass )) {
        if (cell.innerHTML == '1') {cell.innerHTML = '<div class="text-center text-success"><span class="glyphicon glyphicon-ok-circle"></span></div>';}
        if (cell.innerHTML == '0') {cell.innerHTML = '<div class="text-center text-danger"><span class="glyphicon glyphicon-remove-circle"></span></div>';}
      }
    });
  });
};

All you have to do is:

precise in the th of the table head which columns should get a particular class if they contain boolean values. For example, I use <th class='bool'>

call the function with these two arguments:

the table ID

the name of the class the function should recognize as boolean


问:
Error Coming in Autowiring in Spring
I had put Package name in component scan and @component also , but still error is coming . The code is below.

Here is the SpringConfig file:-

```<code>@Configuration
@ComponentScan(basePackages={"com.cagataygurturk.example.lambda","com.cagataygurturk.example.services"})
public class SpringConfig {

}
</code>```

Here is the Service Class:-

```<code>@Component
public class Service {

    /**
     * Autowiring another Spring Bean
     */
    @Autowired
    AnotherService anotherService;

    public String getText(String text) {
        //return anotherService.getText(text);
        return "hello";
    }
}
</code>```

Here is the AnotherService class which is autowired in service class:-

```<code>@Component
public class AnotherService {
    @Autowired
    IFileStoreService file;
    public String getText(String text) {
        String t;
        t=(String)text;
        if(t.equals("get"))
        {
            file.get("1");
            return "You are in Get Controller and database is not connected\n";
        }
        else
        if(t=="post")
        {
            return "You are in post Controller and databse is not connecte\n";
        }
        else
        if(t=="delete")
        {
            return "You are int delete Controller and mongo database in not connected\n";
        }
        else
        {
            return "hii\n"+text+"hey";
        }
    }
}
</code>```

Here is the IFileStoreService class autowired in AnotherService class:

```<code>public interface IFileStoreService {
Resource get(String id) throws StorageException, StorageFileNotFoundException;
}
</code>```

Here is the IFileStoreImpl class:-

```<code>@Component
public class FileStoreServiceImpl implements IFileStoreService {
    private static final Logger logger = LoggerFactory.getLogger(FileStoreServiceImpl.class);

    @Autowired
    private IFileStoreDAO fileStoreDAO;

    @Autowired
    private StorageProperties storageProperties;

    @Override
    public Resource get(String id) throws StorageException, StorageFileNotFoundException {
        Resource resource = null;
        File file = null;
        try {
            FileDetails fileDetails = fileStoreDAO.get(id);
            if(fileDetails != null) {
                String tempDir = storageProperties.getLocation();
                file = new File(tempDir + File.separator + fileDetails.getName());
                file.mkdirs();
                if(file.exists()) {
                    // p1: delete any file if existent in the directory;
                    file.delete();
                }
                file.createNewFile();
                FileCopyUtils.copy(fileDetails.getFileBytes(), file);
                resource = new UrlResource(Paths.get(tempDir).resolve(fileDetails.getName()).toUri());
            } else {
                throw new  StorageFileNotFoundException("No document found with id: " + id);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            if (e instanceof StorageFileNotFoundException) {
                throw (StorageFileNotFoundException) e;
            } else {
                throw new StorageException("", e);
            }
        }
        return resource;
    }
}
</code>```

And last MainHandler function:-

```<code>@SuppressWarnings("unused")
public class MainHandler
        extends AbstractHandler<SpringConfig>
        implements RequestHandler<Map<String,Object>, String> {

    static final Logger log = Logger.getLogger(MainHandler.class);
    @Override
    public String handleRequest(Map<String, Object> input, Context context)throws RuntimeException {
        // TODO Auto-generated method stub
        Service businessService = getApplicationContext().getBean(Service.class);
        return businessService.getText("hii");

    }
}
</code>```

and the Error is :-

```<code>{"errorMessage":"Error creating bean with name 'service': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.cagataygurturk.example.services.AnotherService com.cagataygurturk.example.services.Service.anotherService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'anotherService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.cagataygurturk.example.services.IFileStoreService com.cagataygurturk.example.services.AnotherService.file; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileStoreServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.cagataygurturk.example.services.IFileStoreDAO com.cagataygurturk.example.services.FileStoreServiceImpl.fileStoreDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.cagataygurturk.example.services.IFileStoreDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}","errorType":"org.springframework.beans.factory.BeanCreationException"}
</code>```

答:
As the exception stacktrace suggests:

No qualifying bean of type [com.cagataygurturk.example.services.IFileStoreDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency.

That means that the class IFileStoreDAO does not have an implementation (I'm not 100% sure on this, might get different exception), or missing @Component annotation, or not being scanned by Spring as a component by being in packages not declared under @ComponentScan(basePackages={"com.cagataygurturk.example.lambda","com.cagataygurturk.example.services"}).

For more information regarding Spring Boot component scanning, see this answer: https://stackoverflow.com/a/33619632/5229041

Title: Error Coming in Autowiring in Spring

Body:
I had put Package name in component scan and @component also , but still error is coming . The code is below.

Here is the SpringConfig file:-

@Configuration
@ComponentScan(basePackages={"com.cagataygurturk.example.lambda","com.cagataygurturk.example.services"})
public class SpringConfig {

}

Here is the Service Class:-

@Component
public class Service {

    /**
     * Autowiring another Spring Bean
     */
    @Autowired
    AnotherService anotherService;

    public String getText(String text) {
        //return anotherService.getText(text);
        return "hello";
    }
}

Here is the AnotherService class which is autowired in service class:-

@Component
public class AnotherService {
    @Autowired
    IFileStoreService file;
    public String getText(String text) {
        String t;
        t=(String)text;
        if(t.equals("get"))
        {
            file.get("1");
            return "You are in Get Controller and database is not connected\n";
        }
        else
        if(t=="post")
        {
            return "You are in post Controller and databse is not connecte\n";
        }
        else
        if(t=="delete")
        {
            return "You are int delete Controller and mongo database in not connected\n";
        }
        else
        {
            return "hii\n"+text+"hey";
        }
    }
}

Here is the IFileStoreService class autowired in AnotherService class:

public interface IFileStoreService {
Resource get(String id) throws StorageException, StorageFileNotFoundException;
}

Here is the IFileStoreImpl class:-

@Component
public class FileStoreServiceImpl implements IFileStoreService {
    private static final Logger logger = LoggerFactory.getLogger(FileStoreServiceImpl.class);

    @Autowired
    private IFileStoreDAO fileStoreDAO;

    @Autowired
    private StorageProperties storageProperties;

    @Override
    public Resource get(String id) throws StorageException, StorageFileNotFoundException {
        Resource resource = null;
        File file = null;
        try {
            FileDetails fileDetails = fileStoreDAO.get(id);
            if(fileDetails != null) {
                String tempDir = storageProperties.getLocation();
                file = new File(tempDir + File.separator + fileDetails.getName());
                file.mkdirs();
                if(file.exists()) {
                    // p1: delete any file if existent in the directory;
                    file.delete();
                }
                file.createNewFile();
                FileCopyUtils.copy(fileDetails.getFileBytes(), file);
                resource = new UrlResource(Paths.get(tempDir).resolve(fileDetails.getName()).toUri());
            } else {
                throw new  StorageFileNotFoundException("No document found with id: " + id);
            }
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            if (e instanceof StorageFileNotFoundException) {
                throw (StorageFileNotFoundException) e;
            } else {
                throw new StorageException("", e);
            }
        }
        return resource;
    }
}

And last MainHandler function:-

@SuppressWarnings("unused")
public class MainHandler
        extends AbstractHandler<SpringConfig>
        implements RequestHandler<Map<String,Object>, String> {

    static final Logger log = Logger.getLogger(MainHandler.class);
    @Override
    public String handleRequest(Map<String, Object> input, Context context)throws RuntimeException {
        // TODO Auto-generated method stub
        Service businessService = getApplicationContext().getBean(Service.class);
        return businessService.getText("hii");

    }
}

and the Error is :-

{"errorMessage":"Error creating bean with name 'service': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.cagataygurturk.example.services.AnotherService com.cagataygurturk.example.services.Service.anotherService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'anotherService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: com.cagataygurturk.example.services.IFileStoreService com.cagataygurturk.example.services.AnotherService.file; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'fileStoreServiceImpl': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.cagataygurturk.example.services.IFileStoreDAO com.cagataygurturk.example.services.FileStoreServiceImpl.fileStoreDAO; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type [com.cagataygurturk.example.services.IFileStoreDAO] found for dependency: expected at least 1 bean which qualifies as autowire candidate for this dependency. Dependency annotations: {@org.springframework.beans.factory.annotation.Autowired(required=true)}","errorType":"org.springframework.beans.factory.BeanCreationException"}


问:
Javascript-function lets parent-div disappear with a-tag, but not as button
I wanted to work on a form which, when clicking on a button, let the parent-form disappear. I tried several things with Javascript and after I while I got a working function that works with a click on an a-tag, but not when trying the same with the button. I don't understand why, but assume it has something to do with the button-element.

Then I have the whole form and div which contains the form (shortened, just to show the structure, the form / construction works).
The following is my function:

function hideFunction() {
$("#submit").closest("#fullbody").css({"display":"none"});}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="fullbody" style="display:block" class="w3-content w3-white r_siu r_centered_div">

 <div id="register" role="form" class="r_form_elements">
    <form  method="post" class="form" action="profile_corp.php" enctype="multipart/form-data" autocomplete="off" >

   <div class="w3-row">
    <button type="submit" id="submit" name="login" class="w3-button w3-black w3-half w3-hover-yellow" onclick="hideFunction();">Add</button>
    <button class="w3-button w3-black w3-half w3-hover-pale-yellow" id="forgot">Forgot Password</button>
    CLICK
   </div>
  </form>
 </div>
</div></code>```

So as I said, the function works when clicking on the a-tag, but not when clicking on the button. Does anybody have an idea?

Thanks in advance.

答:
you can use event.preventDefault() like this:

function hideFunction(event) {
event.preventDefault();
$("#submit").closest("#fullbody").css({"display":"none"});}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="fullbody" style="display:block" class="w3-content w3-white r_siu r_centered_div">

 <div id="register" role="form" class="r_form_elements">
    <form  method="post" class="form" action="profile_corp.php" enctype="multipart/form-data" autocomplete="off" >

   <div class="w3-row">
    <button type="submit" id="submit" name="login" class="w3-button w3-black w3-half w3-hover-yellow" onclick="hideFunction(event)">Add</button>
    <button class="w3-button w3-black w3-half w3-hover-pale-yellow" id="forgot">Forgot Password</button>
    CLICK
   </div>
  </form>
 </div>
</div></code>```

Body:
I wanted to work on a form which, when clicking on a button, let the parent-form disappear. I tried several things with Javascript and after I while I got a working function that works with a click on an a-tag, but not when trying the same with the button. I don't understand why, but assume it has something to do with the button-element.

Then I have the whole form and div which contains the form (shortened, just to show the structure, the form / construction works).
The following is my function:

function hideFunction() {
$("#submit").closest("#fullbody").css({"display":"none"});}

    <form  method="post" class="form" action="profile_corp.php" enctype="multipart/form-data" autocomplete="off" >

    <button type="submit" id="submit" name="login" class="w3-button w3-black w3-half w3-hover-yellow" onclick="hideFunction();">Add</button>
    <button class="w3-button w3-black w3-half w3-hover-pale-yellow" id="forgot">Forgot Password</button>
    CLICK

  </form>

So as I said, the function works when clicking on the a-tag, but not when clicking on the button. Does anybody have an idea?

Thanks in advance.

Body:
you can use event.preventDefault() like this:

function hideFunction(event) {
event.preventDefault();
$("#submit").closest("#fullbody").css({"display":"none"});}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="fullbody" style="display:block" class="w3-content w3-white r_siu r_centered_div">

 <div id="register" role="form" class="r_form_elements">
    <form  method="post" class="form" action="profile_corp.php" enctype="multipart/form-data" autocomplete="off" >

   <div class="w3-row">
    <button type="submit" id="submit" name="login" class="w3-button w3-black w3-half w3-hover-yellow" onclick="hideFunction(event)">Add</button>
    <button class="w3-button w3-black w3-half w3-hover-pale-yellow" id="forgot">Forgot Password</button>
    <a id="submit" onclick="hideFunction(event)">CLICK</a>
   </div>
  </form>
 </div>
</div>


问:
Is function prototype compulsory in C++?
By this I mean that even though I define the function before the function call,is it required to have a function prototype?
I tried a program with definition b4 call,it worked.but in C++ by Herbert schildt it says C++ requires full function prototyping.so am confused.
So,does C++ really require full function prototyping?</p>

答:
A function prototype or function interface is a declaration of a
  function that specifies the function's name and type signature (arity,
  data types of parameters, and return type), but omits the function
  body

a function prototype merely specifies its(the function) interface(I/O).

Prototype of a function is also called signature of the function.

If a call or reference has to be made to a function in a code section before the actual function definition, then the function prototype is compulsory.

A function prototype can be "discerned" or gotten from its definition, hence if a call is not made to the function before its actual definition, declaring the function prototype is not compulsory.


问:
Switching through different versions of GHC included 7.0.4
I need to compile some code starting from the GHC version 7.0.4 until the most recent 8.0.2.
I know that using stack I can do something like:

stack init --resolver lts ...

on the local project but the lts versions don't go further than GHC 7.8.3.

How can I switch back to older version of GHC without using stack?

答:
No, you cannot have stack use ghc 7.0.4 because it's not in their snapshot. The oldest compiler stack supports is 7.8.3.

Theoretically, stack can provide support for older compilers, but the Stackage server was announced at August, 2014 and GHC 7.0.4 was released on June, 2011. That's my educated guess of why 7.0.4 is not present.

If you want your code to have support for older compilers, I would recommend you to use a CI system like Travis. Another alternative if you are using a Ubuntu machine is to use Herber's PPA for installing the older compilers.


问:
How to redirect to Index from another controller?
I have been looking through trying to find some way to redirect to an Index view from another controller.

```<code>public ActionResult Index()
{
     ApplicationController viewModel = new ApplicationController();
     return RedirectToAction("Index", viewModel);
}
</code>```

This is what I tried right now. Now the code I was given to has a ActionLink that links to the page I need to Redirect too.

```<code>@Html.ActionLink("Bally Applications","../Application")
</code>```

答:
You can use the overloads method RedirectToAction(string actionName, string controllerName);

Example:

```<code>RedirectToAction(nameof(HomeController.Index), "Home");
</code>```

Body:
I have been looking through trying to find some way to redirect to an Index view from another controller.

public ActionResult Index()
{
     ApplicationController viewModel = new ApplicationController();
     return RedirectToAction("Index", viewModel);
}

This is what I tried right now. Now the code I was given to has a ActionLink that links to the page I need to Redirect too.

@Html.ActionLink("Bally Applications","../Application")

Body:
You can use the overloads method RedirectToAction(string actionName, string controllerName);

Example:

RedirectToAction(nameof(HomeController.Index), "Home");


问:
typescript: tsc is not recognized as an internal or external command, operable program or batch file
I am a beginner with type script. I am unable to compile the type script file.

As I hit Ctrl+Shift+B in the VS Code, i get the error "tsc is not recognised"

I used npm while downloading transcript.

```<code>C:\Users\sramesh>npm install -g typescript
C:\Users\sramesh\AppData\Roaming\npm\tsserver -> C:\Users\sramesh\AppData\Roaming\npm\node_modules\typescript\bin\tsserver
C:\Users\sramesh\AppData\Roaming\npm\tsc -> C:\Users\sramesh\AppData\Roaming\npm\node_modules\typescript\bin\tsc
C:\Users\sramesh\AppData\Roaming\npm
`-- typescript@2.1.5
</code>```

Here is my tasks.json file

```<code>{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "0.1.0",
    "command": "C:\\Users\\sramesh\\AppData\\Roaming\\npm\\node_modules\\typescript\\bin\\tsc",
    "isShellCommand": true,
    "args": [],
    "showOutput": "silent",
    "problemMatcher": "$tsc"
}
</code>```

Can anyone help?

答:
I had a similar issue and didn't even showed the version of Typescript after typing  tsc -v.  Even i had to scratch my head for few days and couldn't solve it.

At last i did 4 things.

installed latest version of nodejs which is i.e. 8.1.3

installed npm which is 5.1.0 ( npm install npm@latest -g)

installed typescript 2.4.1   ( npm install -g typescript)

as suggested by @Uzair Sajid above. (tsc --init)

Now, I can see the TS version, and also compile the TS code.

Body:
I am a beginner with type script. I am unable to compile the type script file.

As I hit Ctrl+Shift+B in the VS Code, i get the error "tsc is not recognised"

I used npm while downloading transcript.

C:\Users\sramesh>npm install -g typescript
C:\Users\sramesh\AppData\Roaming\npm\tsserver -> C:\Users\sramesh\AppData\Roaming\npm\node_modules\typescript\bin\tsserver
C:\Users\sramesh\AppData\Roaming\npm\tsc -> C:\Users\sramesh\AppData\Roaming\npm\node_modules\typescript\bin\tsc
C:\Users\sramesh\AppData\Roaming\npm
`-- typescript@2.1.5

Here is my tasks.json file

{
    // See https://go.microsoft.com/fwlink/?LinkId=733558
    // for the documentation about the tasks.json format
    "version": "0.1.0",
    "command": "C:\\Users\\sramesh\\AppData\\Roaming\\npm\\node_modules\\typescript\\bin\\tsc",
    "isShellCommand": true,
    "args": [],
    "showOutput": "silent",
    "problemMatcher": "$tsc"
}

Can anyone help?


问:
jquery-3.1.1.js:3855 Uncaught TypeError: $(...).loadingModal is not a function
I am working on MVC 5 asp.net, i have a view registration which uses layout, What i want is when user click on add button a loader loads and destroy after ajax response, i can achieve this by not using layout, but when i use layout it gives this error
Uncaught TypeError: $(...).loadingModal is not a function
    at showModal (registration.js:7)

my script sequence is

答:
It happened to me my problem was i had two scripts of  jquery one on the current page and one on the layout page.

Make sure you have only single version of scripts.


问:
Are scripts "open source" by definition?
The other day, I tweaked a script for a friend's World of Warcraft addon. He was surprised that you could edit the addons—that they were "open source." (Word of Warcraft addons are written in the Lua scripting language) I found myself wanting to say "Sure you can—all scripts are 'open source'."

Is that true? Sure, some scripts can be compiled to bytecode, but aren't almost all scripts interpreted? That is to say, doesn't the device interpreting the script need the "source," by definition?

答: I seem to remember reading something in the game terms and conditions that requires addons to be licensed as open source but I can't seem to find it now so I may have been imagining it. In all practical cases they are though. </p>

OwnerDisplayName: AquaMethod

LastEditorDisplayName: Doug Currie

OwnerDisplayName: John Burton


问:
Making a char function parameter const?
Consider this function declaration:

```<code>int IndexOf(const char *, char);
</code>```

where char * is a string and char the character to find within the string (returns -1 if the char is not found, otherwise its position). Does it make sense to make the char also const? I always try to use const on pointer parameters but when something is called by value, I normally leave the const away.

What are your thoughts?

答:
It doesn't make sense because the caller won't be affected if you modify the second parameter's value.

Further, if you need to modify this argument inside the function it may help you save a few bytes on the stack rather than having to declare a separate local variable.

The below code is a good example of modifying an argument instead of having a local variable:

```<code>void foo (int count) {
  while (count--) {
    do_something();
  }
}
</code>```

However, if your function is longer and you don't intend to modify its arguments, it may be rewarding in terms of maintenance to mark the corresponding arguments as const, but only in its definition, not in the declaration that resides in a header file. If you later decide that an argument shouldn't be const, you only have to change it in the definition.

Title: Making a char function parameter const?

Body:
Consider this function declaration:

int IndexOf(const char *, char);

where char * is a string and char the character to find within the string (returns -1 if the char is not found, otherwise its position). Does it make sense to make the char also const? I always try to use const on pointer parameters but when something is called by value, I normally leave the const away.

What are your thoughts?

Body:
It doesn't make sense because the caller won't be affected if you modify the second parameter's value.

Further, if you need to modify this argument inside the function it may help you save a few bytes on the stack rather than having to declare a separate local variable.

The below code is a good example of modifying an argument instead of having a local variable:

void foo (int count) {
  while (count--) {
    do_something();
  }
}

However, if your function is longer and you don't intend to modify its arguments, it may be rewarding in terms of maintenance to mark the corresponding arguments as const, but only in its definition, not in the declaration that resides in a header file. If you later decide that an argument shouldn't be const, you only have to change it in the definition.


问:
Insert multiple rows in sqlite using content values
I am returning multiple rows from mysql with JSON , but only one row is being accepted to sqlite , how can i insert all of it :

MainActivity.java :

```<code>            .....
        if (!error) {

                        // user successfully exist in database
                        JSONObject user = jObj.getJSONObject("user");
                        String id = user.getString("id");
                        String sutdentId = user.getString("sutdentId");
                        String full_name = user.getString("full_name");
                        String year = user.getString("year");
                        String school = user.getString("school");
                        String level = user.getString("level");

                        // pass id ,fullname ,year ,school and level to
        sqlite
                       db.addUser(id, sutdentId, full_name, year, school,
 level);

      .....
</code>```

SqliteHandle.java which is used to hold method of inserting and table creation:

```<code>     public void addUser( String id, String sutdentId, String full_name
   ,String
      year, String school, String level) {
      SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_userId, id);
    values.put(KEY_Student, sutdentId);
    values.put(KEY_Names, full_name);
    values.put(KEY_Year, year);
    values.put(KEY_School, school);
    values.put(KEY_Level, level);
long Id = db.insert(TABLE_USER, null, values);
        Log.d(TAG, "New user inserted into sqlite: " + Id);
        if (Id > 0 ) {
            Log.d(TAG, "New user inserted into database: " + Id);
        }
        else{
            Log.d(TAG, "OOps! No data inserted in mysql ");
        }
    db.close(); // Closing database connection
    }
</code>```

答:
You need to loop over your jsonArray to insert all rows.

You can use a compiled statement to make the execution much faster.

The code will look roughly like this:

```<code>//a field that holds the compiled statement
private SQLiteStatement insStmt = null;

//assuming you have "JSONArray users" loaded;
for (int i = 0 ; i < users.length(); i++) {
    JSONObject obj = users.getJSONObject(i);
    String id = obj.getString("id");
    String studentId = obj.getString("studentId");
    String full_name = obj.getString("full_name");
    String year = obj.getString("year");
    String school = obj.getString("school");
    String level = obj.getString("level");
    addUser(id, sutdentId, full_name, year, school, level);
}
</code>```

Now the addUser function will look like this (with compiled statement).

```<code>function addUser(String id, String sutdentId, String full_name
   ,String year, String school, String level) {

    if (insStmt == null) { //compile it once
        String query = "INSERT into "+TABLE_NAME+"(id, studentId, full_name, year, school, level) VALUES (?,?,?,?,?,?)";
        insStmt = myDataBase.compileStatement(query);
    }

    //bind the arguments
    insStmt.bindAllArgsAsStrings(String[]{id, studentId, full_name, year, school, level});
    //execute
    insStmt.execute();
}
</code>```

Body:
I am returning multiple rows from mysql with JSON , but only one row is being accepted to sqlite , how can i insert all of it :

MainActivity.java :

            .....
        if (!error) {

                        // user successfully exist in database
                        JSONObject user = jObj.getJSONObject("user");
                        String id = user.getString("id");
                        String sutdentId = user.getString("sutdentId");
                        String full_name = user.getString("full_name");
                        String year = user.getString("year");
                        String school = user.getString("school");
                        String level = user.getString("level");

                        // pass id ,fullname ,year ,school and level to
        sqlite
                       db.addUser(id, sutdentId, full_name, year, school,
 level);

      .....

SqliteHandle.java which is used to hold method of inserting and table creation:

     public void addUser( String id, String sutdentId, String full_name
   ,String
      year, String school, String level) {
      SQLiteDatabase db = this.getWritableDatabase();
    ContentValues values = new ContentValues();
    values.put(KEY_userId, id);
    values.put(KEY_Student, sutdentId);
    values.put(KEY_Names, full_name);
    values.put(KEY_Year, year);
    values.put(KEY_School, school);
    values.put(KEY_Level, level);
long Id = db.insert(TABLE_USER, null, values);
        Log.d(TAG, "New user inserted into sqlite: " + Id);
        if (Id > 0 ) {
            Log.d(TAG, "New user inserted into database: " + Id);
        }
        else{
            Log.d(TAG, "OOps! No data inserted in mysql ");
        }
    db.close(); // Closing database connection
    }

Body:
You need to loop over your jsonArray to insert all rows.

You can use a compiled statement to make the execution much faster.

The code will look roughly like this:

//a field that holds the compiled statement
private SQLiteStatement insStmt = null;

//assuming you have "JSONArray users" loaded;
for (int i = 0 ; i < users.length(); i++) {
    JSONObject obj = users.getJSONObject(i);
    String id = obj.getString("id");
    String studentId = obj.getString("studentId");
    String full_name = obj.getString("full_name");
    String year = obj.getString("year");
    String school = obj.getString("school");
    String level = obj.getString("level");
    addUser(id, sutdentId, full_name, year, school, level);
}

Now the addUser function will look like this (with compiled statement).

function addUser(String id, String sutdentId, String full_name
   ,String year, String school, String level) {

    if (insStmt == null) { //compile it once
        String query = "INSERT into "+TABLE_NAME+"(id, studentId, full_name, year, school, level) VALUES (?,?,?,?,?,?)";
        insStmt = myDataBase.compileStatement(query);
    }

    //bind the arguments
    insStmt.bindAllArgsAsStrings(String[]{id, studentId, full_name, year, school, level});
    //execute
    insStmt.execute();
}


问:
Twig table get id outside for loop
I'm trying to access to the user id outside my for loop in twig

Table

```<code>        {% set userid = '' %}
        <table class="display dataTable" id="manageusertable"  cellspacing="0" width="100%">

         <thead>
           <tr>
             <th>Image</th>
             <th>Login</th>
             <th>Nom / Prenom</th>
             <th>Email</th>
             <th>Activé</th>
             <th>Actions</th>
           </tr>
         </thead>
            <tfoot>
            </tfoot>
               <tbody>

                 {% for user in users %}

                 {% set userid = user.id %}
                 <tr class="getid">

                   <td>{{ user.UserImage }}</td>
                   <td>{{ user.username }}</td>
                   <td>{{ user.UserLastname  }} / {{ user.UserFirstName  }}
                   </td>
                   <td>{{ user.email }}</td>
                   {% if user.enabled == 1 %}
                   <td><i class="fa fa-check" aria-hidden="true"></i></td>
                   {% else %}
                   <td><i class="fa fa-times" aria-hidden="true"></i></td>
                   {% endif %}
                   <td>
                   <i class="fa fa-search" aria-hidden="true"></i>
                   <button type="button" class="btn btn-add btn-sm" data-
                   toggle="modal" data-target="#update"><i class="fa fa-
                  pencil"></i></button>
                   <button type="button" class="deleteuser btn btn-danger
                  btn-sm" data-toggle="modal" data-target="#deleteuser"><i
                  class="fa fa-trash-o"></i> </button>
                   </td>
                 </tr>

                       {% endfor %}
               </tbody>

              </table>
</code>```

Modal div when button data-model=#delete is clicked (outside loop)

```<code>         <div class="modal fade" id="deleteuser" tabindex="-1" role="dialog" aria-hidden="true">
              <div class="modal-dialog">
                 <div class="modal-content">
                    <div class="modal-header modal-header-primary">
                       <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                       <h3><i class="fa fa-user m-r-5"></i> Delete User</h3>
                    </div>
                    <div class="modal-body">
                       <div class="row">
                          <div class="col-md-12">
                             <form class="form-horizontal">
                                <fieldset>

                                   <div class="col-md-12 form-group user-form-group">
                                      <label class="control-label">Delete User</label>
                                      <div class="pull-right">
                                         <button type="button" class="btn btn-danger btn-sm">NO</button>
                                        <button " class="btn btn-add btn-sm"><a style="color:#fff;" href="{{ path('lemon_user_deleteuser', {'id': userid}) }}">YES</a></button>
                                      </div>
                                   </div>
                                </fieldset>
                             </form>
                          </div>
                       </div>
                    </div>
                    <div class="modal-footer">
                       <button type="button" class="btn btn-danger pull-left" data-dismiss="modal">Close</button>
                    </div>
                 </div>
                 <!-- /.modal-content -->
              </div>
              <!-- /.modal-dialog -->
           </div>
</code>```

The line
<button " class="btn btn-add btn-sm">YES</button>

always returns the last id (15 if i have 15users in my DB) no matter on which line the button is clicked

i know how to do this with jquery/ajax and from scratch php but since im new to symfony/twig im kinda lost

答:
In your case you have to make an array with the whole of ids e.g.

```<code>             {{ set userIds = {} }}
             {% for user in users %}
             ...
               {% set userIds = userIds|merge({id : user.id} %}
             ...
             {% endfor %}
</code>```

And then redo the "for loop" for each delete button and paths setup

Title: Twig table get id outside for loop

Body:
I'm trying to access to the user id outside my for loop in twig

Table

        {% set userid = '' %}

             Image
             Login
             Nom / Prenom
             Email
             Activé
             Actions

                 {% for user in users %}

                 {% set userid = user.id %}

                   {{ user.UserImage }}
                   {{ user.username }}
                   {{ user.UserLastname  }} / {{ user.UserFirstName  }}

                   {{ user.email }}
                   {% if user.enabled == 1 %}

                   {% else %}

                   {% endif %}

                   <button type="button" class="btn btn-add btn-sm" data-
                   toggle="modal" data-target="#update"></button>
                   <button type="button" class="deleteuser btn btn-danger
                  btn-sm" data-toggle="modal" data-target="#deleteuser"> </button>

                       {% endfor %}

Modal div when button data-model=#delete is clicked (outside loop)

                       <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

 Delete User

                             <form class="form-horizontal">
                                <fieldset>

                                      Delete User

                                         <button type="button" class="btn btn-danger btn-sm">NO</button>
                                        <button " class="btn btn-add btn-sm">YES</button>

                                </fieldset>
                             </form>

                       <button type="button" class="btn btn-danger pull-left" data-dismiss="modal">Close</button>

The line
<button " class="btn btn-add btn-sm">YES</button>

always returns the last id (15 if i have 15users in my DB) no matter on which line the button is clicked

i know how to do this with jquery/ajax and from scratch php but since im new to symfony/twig im kinda lost

Body:
In your case you have to make an array with the whole of ids e.g.

             {{ set userIds = {} }}
             {% for user in users %}
             ...
               {% set userIds = userIds|merge({id : user.id} %}
             ...
             {% endfor %}

And then redo the "for loop" for each delete button and paths setup


问:
How to render ₹ symbol in PDF in C# using PDFsharp
I want to render ₹ in PDF using C#.
Instead of this I am getting ?.

In form am able to print how to render ₹ but I am facing this issue only with PDF.

Attached image

答:
Make sure Unicode is enabled in PDFsharp and also make sure the font use are using contains that symbol.

Since you get "?" instead of the symbol, you most likely just have to set the PdfFontEncoding.Unicode option as shown in the sample.

See this sample:

http://pdfsharp.net/wiki/Unicode-sample.ashx


问:
Save and set the "not-maximized" window size?
As a user is closing a program, I would like to save some information about the primary window, so the next time the user opens the program, the window has the same properties.

This is easy to do for whether the window is maximized:

Get: stage.isMaximized()

Set: stage.setMaximized ( boolean maximized );

This is also easy to do if the window is not maximized:

Get: stage.getX() / stage.getY() / stage.getWidth() / stage.getHeight();

Set: stage.setX() / stage.setY() / stage.setWidth() / stage.setHeight();

However, if the window is maximized, these get functions give us the maximized window's dimensions and locations. If I set those values and the user restores the window to a non-maximized state, the window stays similar to its maximized size, rather than shrinking down as the user expect.

How can I save the "windowed" stage dimensions and location for a currently maximized window that is being closed, and then restore this information when the program is re-opened?

答:
You can use this app to solve your problem.

First, create a text file named properties.txt. Second, Add some default values to this text file. Now, save the Stage's properties when the stage closes using setOnCloseRequest. Next, if you have a Button that closes the stage, save the Stage's properties when the button is pressed using the Button's onAction handler. Don't forget to always load these settings when the app starts.

properties.txt:

```<code>sceneHeight=300.0
sceneWidth=450.0
fullScreen=false
</code>```

Main:

```<code>import java.io.*;
import java.util.*;
import java.util.logging.*;
import javafx.application.*;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;

/**
 *
 * @author Sedrick
 */
public class JavaFXApplication56 extends Application {

    @Override
    public void start(Stage primaryStage)
    {
        Map<String, String> properties = loadProperties();

        Button btn = new Button();
        btn.setText("Toggle fullScreen");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event)
            {
                if (properties.get("fullScreen").endsWith("true")) {
                    properties.put("fullScreen", "false");
                    primaryStage.setFullScreen(false);
                }
                else {
                    properties.put("fullScreen", "true");
                    primaryStage.setFullScreen(true);
                }
            }
        });

        Button btnExit = new Button();
        btnExit.setText("Exit");
        btnExit.setOnAction((event) -> {
            properties.put("fullScreen", Boolean.toString(primaryStage.isFullScreen()));
            if (!primaryStage.isFullScreen()) {
                properties.put("sceneHeight", Double.toString(primaryStage.getHeight()));
                properties.put("sceneWidth", Double.toString(primaryStage.getWidth()));
            }

            System.out.println("Closing properties:");
            properties.forEach((key, value)
                    -> System.out.println("\t" + key + ":" + value));
            System.out.println();
            saveProperties(properties);
            primaryStage.close();
        });

        HBox hBox = new HBox();
        hBox.getChildren().addAll(btn, btnExit);

        BorderPane root = new BorderPane();
        root.setBottom(hBox);

        if (properties.get("fullScreen").equals("true")) {
            primaryStage.setFullScreen(true);
        }
        else {
            primaryStage.setFullScreen(false);
        }

        double sceneWidth = Double.parseDouble(properties.get("sceneWidth"));
        double sceneHeight = Double.parseDouble(properties.get("sceneHeight"));
        Scene scene = new Scene(root, sceneWidth, sceneHeight);

        primaryStage.setOnCloseRequest((event) -> {
            properties.put("fullScreen", Boolean.toString(primaryStage.isFullScreen()));
            if (!primaryStage.isFullScreen()) {
                properties.put("sceneHeight", Double.toString(primaryStage.getHeight()));
                properties.put("sceneWidth", Double.toString(primaryStage.getWidth()));
            }

            System.out.println("Closing properties:");
            properties.forEach((key, value)
                    -> System.out.println("\t" + key + ":" + value));
            System.out.println();
            saveProperties(properties);
        });
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        launch(args);
    }

    public Map loadProperties()
    {

        File file = new File("properties.txt");
        Map<String, String> properties = new HashMap();
        try {
            Scanner input = new Scanner(file);
            while (input.hasNext()) {
                String[] parts = input.nextLine().split("=");
                properties.put(parts[0], parts[1]);
            }
        }
        catch (FileNotFoundException ex) {
            System.out.println(ex.toString());
        }

        System.out.println("Loading properties:");
        properties.forEach((key, value)
                -> System.out.println("\t" + key + ":" + value));
        System.out.println();
        return properties;
    }

    public void saveProperties(Map<String, String> properties)
    {
        StringBuilder stringBuilder = new StringBuilder();

        for (String key : properties.keySet()) {
            stringBuilder.append(key).append("=").append(properties.get(key)).append("\n");
        }

        try (BufferedWriter bw = new BufferedWriter(new FileWriter("properties.txt"))) {
            bw.write(stringBuilder.toString());
        }
        catch (IOException ex) {
            Logger.getLogger(JavaFXApplication56.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}
</code>```

Body:
You can use this app to solve your problem.

First, create a text file named properties.txt. Second, Add some default values to this text file. Now, save the Stage's properties when the stage closes using setOnCloseRequest. Next, if you have a Button that closes the stage, save the Stage's properties when the button is pressed using the Button's onAction handler. Don't forget to always load these settings when the app starts.

properties.txt:

sceneHeight=300.0
sceneWidth=450.0
fullScreen=false

Main:

import java.io.*;
import java.util.*;
import java.util.logging.*;
import javafx.application.*;
import javafx.event.*;
import javafx.scene.*;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.*;

/**
 *
 * @author Sedrick
 */
public class JavaFXApplication56 extends Application {

    @Override
    public void start(Stage primaryStage)
    {
        Map<String, String> properties = loadProperties();

        Button btn = new Button();
        btn.setText("Toggle fullScreen");
        btn.setOnAction(new EventHandler<ActionEvent>() {
            @Override
            public void handle(ActionEvent event)
            {
                if (properties.get("fullScreen").endsWith("true")) {
                    properties.put("fullScreen", "false");
                    primaryStage.setFullScreen(false);
                }
                else {
                    properties.put("fullScreen", "true");
                    primaryStage.setFullScreen(true);
                }
            }
        });

        Button btnExit = new Button();
        btnExit.setText("Exit");
        btnExit.setOnAction((event) -> {
            properties.put("fullScreen", Boolean.toString(primaryStage.isFullScreen()));
            if (!primaryStage.isFullScreen()) {
                properties.put("sceneHeight", Double.toString(primaryStage.getHeight()));
                properties.put("sceneWidth", Double.toString(primaryStage.getWidth()));
            }

            System.out.println("Closing properties:");
            properties.forEach((key, value)
                    -> System.out.println("\t" + key + ":" + value));
            System.out.println();
            saveProperties(properties);
            primaryStage.close();
        });

        HBox hBox = new HBox();
        hBox.getChildren().addAll(btn, btnExit);

        BorderPane root = new BorderPane();
        root.setBottom(hBox);

        if (properties.get("fullScreen").equals("true")) {
            primaryStage.setFullScreen(true);
        }
        else {
            primaryStage.setFullScreen(false);
        }

        double sceneWidth = Double.parseDouble(properties.get("sceneWidth"));
        double sceneHeight = Double.parseDouble(properties.get("sceneHeight"));
        Scene scene = new Scene(root, sceneWidth, sceneHeight);

        primaryStage.setOnCloseRequest((event) -> {
            properties.put("fullScreen", Boolean.toString(primaryStage.isFullScreen()));
            if (!primaryStage.isFullScreen()) {
                properties.put("sceneHeight", Double.toString(primaryStage.getHeight()));
                properties.put("sceneWidth", Double.toString(primaryStage.getWidth()));
            }

            System.out.println("Closing properties:");
            properties.forEach((key, value)
                    -> System.out.println("\t" + key + ":" + value));
            System.out.println();
            saveProperties(properties);
        });
        primaryStage.setTitle("Hello World!");
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        launch(args);
    }

    public Map loadProperties()
    {

        File file = new File("properties.txt");
        Map<String, String> properties = new HashMap();
        try {
            Scanner input = new Scanner(file);
            while (input.hasNext()) {
                String[] parts = input.nextLine().split("=");
                properties.put(parts[0], parts[1]);
            }
        }
        catch (FileNotFoundException ex) {
            System.out.println(ex.toString());
        }

        System.out.println("Loading properties:");
        properties.forEach((key, value)
                -> System.out.println("\t" + key + ":" + value));
        System.out.println();
        return properties;
    }

    public void saveProperties(Map<String, String> properties)
    {
        StringBuilder stringBuilder = new StringBuilder();

        for (String key : properties.keySet()) {
            stringBuilder.append(key).append("=").append(properties.get(key)).append("\n");
        }

        try (BufferedWriter bw = new BufferedWriter(new FileWriter("properties.txt"))) {
            bw.write(stringBuilder.toString());
        }
        catch (IOException ex) {
            Logger.getLogger(JavaFXApplication56.class.getName()).log(Level.SEVERE, null, ex);
        }
    }
}