问:
jQuery UI Range Slider - Tooltips for each handle
I'm using a jQuery Range slider to let users select a time range in a day (i.e. 10:00 - 18:00).

At the moment it's all working fine and I have the output being displayed in a text box but this isn't ideal. I would prefer to have an individual tooltip for each handle that display the 2 values seperately and that follow the handle when you drag it. Failing that I could put the time in the slide handle itself.

My problem is - how do I target an specific handle? They dynamically created by jQuery and are defined only by classes so I don't know how I'd go about linking a div to a specific handle.

I had a search on here and found some similar questions but nothing that really answered this.

Also, I don't want to use a plugin. I know one or two exist but as this is only happening on one place on the site I'd rather not have to include a file for something  that should be fairly simple (even if it has beaten me :P)

答:
If you just need to access each value independently, you can attach the slide function to update each target seperately. Additionally, if you want to be able to change the slider from each of those 2 targets seperately, that works just as easily with the values method.

EDIT

Guess I misunderstood your question a bit. You can get the handlers and their positions with some selectors, such as:

```<code>var offset1 = $(this).children('.ui-slider-handle').first().offset();
var offset2 = $(this).children('.ui-slider-handle').last().offset();
</code>```

Below is an example how you could use that information to display tooltips over those items when dragged.

Example: http://jsfiddle.net/niklasvh/vW7vy/

Body:
If you just need to access each value independently, you can attach the slide function to update each target seperately. Additionally, if you want to be able to change the slider from each of those 2 targets seperately, that works just as easily with the values method.

EDIT

Guess I misunderstood your question a bit. You can get the handlers and their positions with some selectors, such as:

var offset1 = $(this).children('.ui-slider-handle').first().offset();
var offset2 = $(this).children('.ui-slider-handle').last().offset();

Below is an example how you could use that information to display tooltips over those items when dragged.

Example: http://jsfiddle.net/niklasvh/vW7vy/


来源: stackexchange

问:
Angular | NgRx Check for null field in an object before putting it in a list of dropdown
I have a html dropdown which is sourcing data from an api, the api returns an array of objects [in the component].
The Dropdown uses a field value which is in most objects, but not all.

So it causes, some fields entries to show blank in the dropdown.

```<code><div class="col-sm-5">
                    <label>DropDown<label class="field-importance" style="padding-left: 14rem">Required</label></label>
                    <select formControlName="Entry" placeholder="Select Entry" required>
                        <option value="null" disabled="true" [selected]="true" [hidden]="true">Select Entry</option>
                        <option *ngFor="let e of entry" [value]="e.val">{{e.val}}</option>
                    </select>
</div>
</code>```

Thank you soo much

答:
I would recommend filtering out null values from your array in the ts code. So when you are initializing data to the entry variable, do something like this:</p>

```<code>this.entry = data.filter(x => x.val);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have a html dropdown which is sourcing data from an api, the api returns an array of objects [in the component].
The Dropdown uses a field value which is in most objects, but not all.

So it causes, some fields entries to show blank in the dropdown.

                    DropDownRequired
                    <select formControlName="Entry" placeholder="Select Entry" required>
                        <option value="null" disabled="true" [selected]="true" [hidden]="true">Select Entry</option>
                        <option *ngFor="let e of entry" [value]="e.val">{{e.val}}</option>
                    </select>

Thank you soo much

Body:
I would recommend filtering out null values from your array in the ts code. So when you are initializing data to the entry variable, do something like this:

this.entry = data.filter(x => x.val);


问:
What is ._.bash_profile file
When I was figuring out how my terminal (Cygwin 64bit on Windows 10 laptop) works, I found a ._.bash_profile file (emphasis on the extra ._). That was after I tried the command ls -a on the home directory.

Terminal displaying all of the files and folders in my home directory.

When I typed nano ._.bash_profile into the terminal, I got what I think is just garbled text:
Click here for the text of the ._.bash_profile

So my question is what on earth is ._.bash_profile?

答:
Can you open the file with an IDE like Visual Studio Code?
It looks like a file with some sort of Mac Os file</p>

Title: What is ._.bash_profile file


问:
Split css grid 2 columns into 3 for specific row
I have a 2 column layout and wish to split one row to a 3 column layout is that possible without specifying the 3 column layout initially?

Example

all 7s should be split to 3 parts in that row (see code output)

1 to 1.5 obviously doesn't work.

.grid-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
}

.grid-item {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.8);
  padding: 20px;
  font-size: 30px;
  text-align: center;
}

.custom {
  grid-column: 1/1.5
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-container">
  <div class="grid-item">1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">3</div>
  <div class="grid-item">4</div>
  <div class="grid-item custom">7</div>
  <div class="grid-item custom">7</div>
  <div class="grid-item custom">7</div>
</div></code>```

答:
A hack that should be used with caution (or not used at all)

.grid-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
}

.grid-item {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.8);
  padding: 20px;
  font-size: 30px;
  text-align: center;
  box-sizing: border-box;
}

.custom {
  width: 66.66%
}

.custom+.custom {
  margin-left: -33.33%;
  grid-column: 2;
  grid-row:3;
}

.custom+.custom+.custom {
  margin-left: 33.33%;
  grid-column: 2;
  grid-row:3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-container">
  <div class="grid-item">1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">3</div>
  <div class="grid-item">4</div>
  <div class="grid-item custom">7</div>
  <div class="grid-item custom">7</div>
  <div class="grid-item custom">7</div>
</div></code>```

And the logical solution is to move to 6 columns:

.grid-container {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
}

.grid-item {
  grid-column:span 3;
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.8);
  padding: 20px;
  font-size: 30px;
  text-align: center;
  box-sizing: border-box;
}

.custom {
 grid-column:span 2;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="grid-container">
  <div class="grid-item">1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">3</div>
  <div class="grid-item">4</div>
  <div class="grid-item custom">7</div>
  <div class="grid-item custom">7</div>
  <div class="grid-item custom">7</div>
</div></code>```

Body:
I have a 2 column layout and wish to split one row to a 3 column layout is that possible without specifying the 3 column layout initially?

Example

all 7s should be split to 3 parts in that row (see code output)

1 to 1.5 obviously doesn't work.

.grid-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
}

.grid-item {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.8);
  padding: 20px;
  font-size: 30px;
  text-align: center;
}

.custom {
  grid-column: 1/1.5
}

1

2

3

4

7

7

7

Body:
A hack that should be used with caution (or not used at all)

.grid-container {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
}

.grid-item {
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.8);
  padding: 20px;
  font-size: 30px;
  text-align: center;
  box-sizing: border-box;
}

.custom {
  width: 66.66%
}

.custom+.custom {
  margin-left: -33.33%;
  grid-column: 2;
  grid-row:3;
}

.custom+.custom+.custom {
  margin-left: 33.33%;
  grid-column: 2;
  grid-row:3;
}

<div class="grid-container">
  <div class="grid-item">1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">3</div>
  <div class="grid-item">4</div>
  <div class="grid-item custom">7</div>
  <div class="grid-item custom">7</div>
  <div class="grid-item custom">7</div>
</div>

And the logical solution is to move to 6 columns:

.grid-container {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
}

.grid-item {
  grid-column:span 3;
  background-color: rgba(255, 255, 255, 0.8);
  border: 1px solid rgba(0, 0, 0, 0.8);
  padding: 20px;
  font-size: 30px;
  text-align: center;
  box-sizing: border-box;
}

.custom {
 grid-column:span 2;
}

<div class="grid-container">
  <div class="grid-item">1</div>
  <div class="grid-item">2</div>
  <div class="grid-item">3</div>
  <div class="grid-item">4</div>
  <div class="grid-item custom">7</div>
  <div class="grid-item custom">7</div>
  <div class="grid-item custom">7</div>
</div>


问:
AXIOS Post stay on PENDING in my REACT application

Below is the Redux Action code that will be dispatched whenever onSubmit of Create
  / Updating a profile:

I am using AXIOS lib for making the below POST calls to the backend - MongoDB.

```<code>const res = await axios.post(
      '/api/profile',
      formData,                 // Body
      config                    // Headers
    );
</code>```

On my React application, the above lines of code works fine for Create but for the Update, it isn't returning anything and in the Networks Tab on Chrome Dev Tools, the status is Pending. Can someone help me understand where I would have made a mistake?

Both the Create/Update calls worked fine when I did the POST request using
  Postman with the same Headers and Payload data.

Below is the Full code:

```<code>// Create/Update Profile
export const createProfile = (formData, history, edit = false) => async (
  dispatch
) => {
  try {
    const config = {
      headers: {
        'Content-Type': 'application/json',
      },
    };
    debugger;
    const res = await axios.post(
      '/api/profile',
      formData,
      config
    );
    dispatch({
      type: GET_PROFILE,
      payload: res.data,
    });

    dispatch(setAlert(edit ? 'Profile Updated' : 'Profile Created'), 'success');

    if (!edit) {
      history.push('/dashboard');
    }
  } catch (error) {
    const errors = error.response.data.errors;
    if (errors) {
      errors.forEach((error) => dispatch(setAlert(error.msg, 'danger')));
    }

    dispatch({
      type: PROFILE_ERROR,
      payload: {
        msg: error.response.statusText,
        status: error.response.status,
      },
    });
  }
};
</code>```

答:
You have a problem in your data sending way.

You are selecting content-type: application/json in headers whereas you are sending data in string.

Solution:

If your formData variable is an instance of class FormData then change your headers content-type to x-www-form-urlencoded.

If your formData is a simple object then do not use JSON.stringify in axios.post method.

Also update your axios request:

```<code>const res = await axios.post(
      'http://localhost:5000/api/profile',
      formData,
      config
    );
</code>```

I hope it helps

Body:
Below is the Redux Action code that will be dispatched whenever onSubmit of Create
  / Updating a profile:

I am using AXIOS lib for making the below POST calls to the backend - MongoDB.

const res = await axios.post(
      '/api/profile',
      formData,                 // Body
      config                    // Headers
    );

On my React application, the above lines of code works fine for Create but for the Update, it isn't returning anything and in the Networks Tab on Chrome Dev Tools, the status is Pending. Can someone help me understand where I would have made a mistake?

Both the Create/Update calls worked fine when I did the POST request using
  Postman with the same Headers and Payload data.

Below is the Full code:

// Create/Update Profile
export const createProfile = (formData, history, edit = false) => async (
  dispatch
) => {
  try {
    const config = {
      headers: {
        'Content-Type': 'application/json',
      },
    };
    debugger;
    const res = await axios.post(
      '/api/profile',
      formData,
      config
    );
    dispatch({
      type: GET_PROFILE,
      payload: res.data,
    });

    dispatch(setAlert(edit ? 'Profile Updated' : 'Profile Created'), 'success');

    if (!edit) {
      history.push('/dashboard');
    }
  } catch (error) {
    const errors = error.response.data.errors;
    if (errors) {
      errors.forEach((error) => dispatch(setAlert(error.msg, 'danger')));
    }

    dispatch({
      type: PROFILE_ERROR,
      payload: {
        msg: error.response.statusText,
        status: error.response.status,
      },
    });
  }
};

Body:
You have a problem in your data sending way.

You are selecting content-type: application/json in headers whereas you are sending data in string.

Solution:

If your formData variable is an instance of class FormData then change your headers content-type to x-www-form-urlencoded.

If your formData is a simple object then do not use JSON.stringify in axios.post method.

Also update your axios request:

const res = await axios.post(
      'http://localhost:5000/api/profile',
      formData,
      config
    );

I hope it helps


问:
Slow webservice problem
I create a Python webservice on Linux machine (ubuntu):

```<code>import soaplib
import os

from soaplib.core.service import rpc, DefinitionBase, soap
from soaplib.core.model.primitive import String, Integer
from soaplib.core.server import wsgi
from soaplib.core.model.clazz import Array

def runcmd(cmd):
    fout = os.popen(cmd)
    out = fout.read()
    return out

class LinuxServices(DefinitionBase):
@soap(String, String,_returns=Array(String))
def df(self,server, user):
    L = []
    cmd = 'df -hP | grep "/"'
    output = runcmd(cmd).split('\n')
    for n in xrange(len(output)-1):
        out = output[n].split()
        L.append('%s;%s' % (out[5], out[4]))
    return L

if __name__=='__main__':
try:
    from wsgiref.simple_server import make_server
    soap_application = soaplib.core.Application([LinuxServices], 'tns')
    wsgi_application = wsgi.Application(soap_application)
    server = make_server('0.0.0.0', 7789, wsgi_application)
    server.serve_forever()
except ImportError:
    print "Error: example server code requires Python >= 2.5"
</code>```

I created it based on this example: soaplib helloworld

Then (on Windows 7) I created a Silverlight project, where I use this ws to get disk status on my linux server:

Service in Silverlight project:

```<code>public class LinuxService
{
    [OperationContract]
    public List<dfItem> df()
    {
        List<dfItem> dfItems = new List<dfItem>();

        WebReference.Application app = new WebReference.Application();

        var result = app.df(new WebReference.df()/*...*/);

        foreach (var item in result.dfResult)
        {
            string[] info = item.Split(';');

            dfItem dfItem = new dfItem()
            {
                MountPoint = info[0].ToString(),
                Usage = info[1].ToString()
            };
            dfItems.Add(dfItem);
        }
        return dfItems;
    }
    //...
}
</code>```

Calling service on page:

```<code>protected override void OnNavigatedTo(NavigationEventArgs e)
{
    LinuxServiceClient client = new LinuxServiceClient();

    client.dfCompleted += new EventHandler<dfCompletedEventArgs>(client_dfCompleted);

    client.dfAsync();
}

void client_dfCompleted(object sender, dfCompletedEventArgs e)
{
    DG.ItemsSource = e.Result;
    DG.Visibility = System.Windows.Visibility.Visible;
}
</code>```

My problem is that when I navigate to this page, it takes 4-8 seconds to get data from ws (ws in LAN).

I really doubt that line bandwidth can create this wait time...

My question:
Do you have any suggestions what can I do to speed up this?

System Info:

UbuntuServer 11.04

Python: Python 2.7

Soaplib: soaplib 2.0.0-beta2

Windows: Windows 7 sp1

Silverlight: Silverlight 4

答:
Just a cursory benchmark using the suds client and the soaplib hello world example:

```<code>>>> def bench_soap(num):
...:     start = time.time()
...:     for i in range(num):
...:         hello_client.service.say_hello("Dave", 5)
...:     elapsed = time.time() - start
...:     print "Completed %s: ops in %.2f seconds : %.1f ops/sec" % (num, elapsed, num / elapsed)
...:
...:

>>> bench_soap(100)
Completed 100: ops in 0.40 seconds : 247.5 ops/sec

>>> bench_soap(1000)
Completed 1000: ops in 3.81 seconds : 262.5 ops/sec
</code>```

I've not seen any "lag" or anything like that on my end. Soaplib, seems fast and responsive, so perhaps a Silverlight issue? Or some sort of incompatibility between the two?

ContentLicense: CC BY-SA 3.0

Title: Slow webservice problem

Body:
I create a Python webservice on Linux machine (ubuntu):

import soaplib
import os

from soaplib.core.service import rpc, DefinitionBase, soap
from soaplib.core.model.primitive import String, Integer
from soaplib.core.server import wsgi
from soaplib.core.model.clazz import Array

def runcmd(cmd):
    fout = os.popen(cmd)
    out = fout.read()
    return out

class LinuxServices(DefinitionBase):
@soap(String, String,_returns=Array(String))
def df(self,server, user):
    L = []
    cmd = 'df -hP | grep "/"'
    output = runcmd(cmd).split('\n')
    for n in xrange(len(output)-1):
        out = output[n].split()
        L.append('%s;%s' % (out[5], out[4]))
    return L

if __name__=='__main__':
try:
    from wsgiref.simple_server import make_server
    soap_application = soaplib.core.Application([LinuxServices], 'tns')
    wsgi_application = wsgi.Application(soap_application)
    server = make_server('0.0.0.0', 7789, wsgi_application)
    server.serve_forever()
except ImportError:
    print "Error: example server code requires Python >= 2.5"

I created it based on this example: soaplib helloworld

Then (on Windows 7) I created a Silverlight project, where I use this ws to get disk status on my linux server:

Service in Silverlight project:

public class LinuxService
{
    [OperationContract]
    public List<dfItem> df()
    {
        List<dfItem> dfItems = new List<dfItem>();

        WebReference.Application app = new WebReference.Application();

        var result = app.df(new WebReference.df()/*...*/);

        foreach (var item in result.dfResult)
        {
            string[] info = item.Split(';');

            dfItem dfItem = new dfItem()
            {
                MountPoint = info[0].ToString(),
                Usage = info[1].ToString()
            };
            dfItems.Add(dfItem);
        }
        return dfItems;
    }
    //...
}

Calling service on page:

protected override void OnNavigatedTo(NavigationEventArgs e)
{
    LinuxServiceClient client = new LinuxServiceClient();

    client.dfCompleted += new EventHandler<dfCompletedEventArgs>(client_dfCompleted);

    client.dfAsync();
}

void client_dfCompleted(object sender, dfCompletedEventArgs e)
{
    DG.ItemsSource = e.Result;
    DG.Visibility = System.Windows.Visibility.Visible;
}

My problem is that when I navigate to this page, it takes 4-8 seconds to get data from ws (ws in LAN).

I really doubt that line bandwidth can create this wait time...

My question:
Do you have any suggestions what can I do to speed up this?

System Info:

UbuntuServer 11.04

Python: Python 2.7

Soaplib: soaplib 2.0.0-beta2

Windows: Windows 7 sp1

Silverlight: Silverlight 4

Body:
Just a cursory benchmark using the suds client and the soaplib hello world example:

>>> def bench_soap(num):
...:     start = time.time()
...:     for i in range(num):
...:         hello_client.service.say_hello("Dave", 5)
...:     elapsed = time.time() - start
...:     print "Completed %s: ops in %.2f seconds : %.1f ops/sec" % (num, elapsed, num / elapsed)
...:
...:

>>> bench_soap(100)
Completed 100: ops in 0.40 seconds : 247.5 ops/sec

>>> bench_soap(1000)
Completed 1000: ops in 3.81 seconds : 262.5 ops/sec

I've not seen any "lag" or anything like that on my end. Soaplib, seems fast and responsive, so perhaps a Silverlight issue? Or some sort of incompatibility between the two?


问:
Roblox - Argument 1 missing or nil
I'm trying to make a script where when you touch a characters hitbox, a certain chat will come up, but the output window says "Argument 1 missing or nil".

Code:

```<code>local debounce = false

game.Workspace.RowanAsleep.RowanAsleepHitbox.Touched:Connect(function(hit)

    if not debounce then
        debounce = true
        if game.Players:GetPlayerFromCharacter(hit.Parent)then
            game.ReplicatedStorage.RowanTalking.RowanSleeping:FireClient()
        end
        wait(2)
        debounce = false
    end
end)
</code>```

答:
At line 8, FireClient() requires a player instance to be passed. Try making a variable with the result of GetPlayerFromCharacter and pass that into FireClient.</p>

```<code>local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if player then --GetPlayerFromCharacter will only return nil or a player instance
    game.ReplicatedStorage.RowanTalking.RowanSleeping:FireClient(player)
end
</code>```

Title: Roblox - Argument 1 missing or nil

Body:
I'm trying to make a script where when you touch a characters hitbox, a certain chat will come up, but the output window says "Argument 1 missing or nil".

Code:

local debounce = false

game.Workspace.RowanAsleep.RowanAsleepHitbox.Touched:Connect(function(hit)

    if not debounce then
        debounce = true
        if game.Players:GetPlayerFromCharacter(hit.Parent)then
            game.ReplicatedStorage.RowanTalking.RowanSleeping:FireClient()
        end
        wait(2)
        debounce = false
    end
end)

Body:
At line 8, FireClient() requires a player instance to be passed. Try making a variable with the result of GetPlayerFromCharacter and pass that into FireClient.

local player = game.Players:GetPlayerFromCharacter(hit.Parent)
if player then --GetPlayerFromCharacter will only return nil or a player instance
    game.ReplicatedStorage.RowanTalking.RowanSleeping:FireClient(player)
end


问:
Powershell Putty Connection and Automating Tasks
I want to use PowerShell to connect to a PuTTY "saved session" and then specify a file that contains some batch commands.  Using CMD this would look like

```<code>d:\putty\psftp 'Saved Session Name' -b d:\location.txt.
</code>```

I think that the PS equivalent should look like

```<code>Start-Process d:\putty\psftp.exe 'Saved Session Name'
(and then a call to pass a 'get' script) i.e. cd Outgoing get <date>.txt
</code>```

However, I get the following error:

```<code>a positional parameter cannot be found that accepts the argument
</code>```

How can I accomplish this using PowerShell?

答:
All you need is plink:

```<code>plink 'Saved Session Name'
</code>```

Body:
I want to use PowerShell to connect to a PuTTY "saved session" and then specify a file that contains some batch commands.  Using CMD this would look like

d:\putty\psftp 'Saved Session Name' -b d:\location.txt.

I think that the PS equivalent should look like

Start-Process d:\putty\psftp.exe 'Saved Session Name'
(and then a call to pass a 'get' script) i.e. cd Outgoing get <date>.txt

However, I get the following error:

a positional parameter cannot be found that accepts the argument

How can I accomplish this using PowerShell?

Body:
All you need is plink:

plink 'Saved Session Name'


问:
Why doesn't this program end? The game goes on forever if i don't input the correct number
I am new to code and I was trying to create a guessing game as one of my first projects. I think i'm nearly done but this program doesn't end. Instead of ending when the there are 0 tries left it just continues the game even with the minus, Ps.(I made the number fixed for now, but will generate a random number when this issue is resolved)

I am new to code and I was trying to create a guessing game as one of my first projects. I think i'm nearly done but this program doesn't end. Instead of ending when the there are 0 tries left it just continues the game even with the minus, Ps.(I made the number fixed for now, but will generate a random number when this issue is resolved)

```<code>print("Welcome to my guessing game can you get the magic number hint, it's between 1 and 100 ")

Magic_number = 7
guess = int(input("Enter your guess:"))
guess_limit = 5
guess_counter = 1
out_of_guesses = False
print("You have", str(guess_limit - guess_counter), "tries left")

while guess != Magic_number and not out_of_guesses:
    while guess < Magic_number:
        print("That number is too small, try again")
        guess = int(input("Enter guess: "))
        guess_counter += 1
        print("You have", str(guess_limit - guess_counter), "tries left")

    while guess > Magic_number:
        print("That number is too high try again")
        guess = int(input("Enter guess: "))
        guess_counter += 1
        print("You have", str(guess_limit - guess_counter), "tries left")

    if guess == Magic_number:
        print("Well done you got it!!")

if out_of_guesses:
    print("Game over, sorry")
</code>```

答:
You are not updating out_of_guesses wich means that your loop exit clause while not out_of_guesses is never triggered.

You are looping too much as well; your program is getting stuck in the inner while loops.

Try something like this:

```<code>print("Welcome to my guessing game can you get the magic number hint, it's between 1 and 100 ")

Magic_number = 7

guess_limit = 5
guess_counter = 0
out_of_guesses = False

print("You have", str(guess_limit - guess_counter), "tries left")

while not out_of_guesses:
    guess = int(input("Enter guess: "))

    if guess == Magic_number:
        print("Well done you got it!!")
        break

    elif guess < Magic_number:
        print("That number is too small, try again")

    elif guess > Magic_number:
        print("That number is too high try again")

    guess_counter += 1
    print("You have", str(guess_limit - guess_counter), "tries left")

    # exit clause
    if guess_limit == guess_counter:
        out_of_guesses = True
        print("Game over, sorry")
</code>```

Body:
I am new to code and I was trying to create a guessing game as one of my first projects. I think i'm nearly done but this program doesn't end. Instead of ending when the there are 0 tries left it just continues the game even with the minus, Ps.(I made the number fixed for now, but will generate a random number when this issue is resolved)

I am new to code and I was trying to create a guessing game as one of my first projects. I think i'm nearly done but this program doesn't end. Instead of ending when the there are 0 tries left it just continues the game even with the minus, Ps.(I made the number fixed for now, but will generate a random number when this issue is resolved)

print("Welcome to my guessing game can you get the magic number hint, it's between 1 and 100 ")

Magic_number = 7
guess = int(input("Enter your guess:"))
guess_limit = 5
guess_counter = 1
out_of_guesses = False
print("You have", str(guess_limit - guess_counter), "tries left")

while guess != Magic_number and not out_of_guesses:
    while guess < Magic_number:
        print("That number is too small, try again")
        guess = int(input("Enter guess: "))
        guess_counter += 1
        print("You have", str(guess_limit - guess_counter), "tries left")

    while guess > Magic_number:
        print("That number is too high try again")
        guess = int(input("Enter guess: "))
        guess_counter += 1
        print("You have", str(guess_limit - guess_counter), "tries left")

    if guess == Magic_number:
        print("Well done you got it!!")

if out_of_guesses:
    print("Game over, sorry")

Body:
You are not updating out_of_guesses wich means that your loop exit clause while not out_of_guesses is never triggered.

You are looping too much as well; your program is getting stuck in the inner while loops.

Try something like this:

print("Welcome to my guessing game can you get the magic number hint, it's between 1 and 100 ")

Magic_number = 7

guess_limit = 5
guess_counter = 0
out_of_guesses = False

print("You have", str(guess_limit - guess_counter), "tries left")

while not out_of_guesses:
    guess = int(input("Enter guess: "))

    if guess == Magic_number:
        print("Well done you got it!!")
        break

    elif guess < Magic_number:
        print("That number is too small, try again")

    elif guess > Magic_number:
        print("That number is too high try again")

    guess_counter += 1
    print("You have", str(guess_limit - guess_counter), "tries left")

    # exit clause
    if guess_limit == guess_counter:
        out_of_guesses = True
        print("Game over, sorry")


问:
What are the advantages of LePUS3 over UML?
When searching online for object oriented concepts such as the composite design pattern I often found them represented in the LePUS3 notation. I am not really familiar with this
modeling language.

Is it something I should prefer over UML?

答:
I would say that apart from other good features of LePus3, mentioned by the other answers, there is one more, extremely important from my point of view:

In UML you can make a plan of SW
In LePus3 you can make a plan, or a plan of the plan, or a plan of the plan of the plan, or even the common plan for several levels of abstraction.

The LePus3 is the only diagram language that is formalized and simultaneously adapted for metathinking.

On the other hand, using of LePus3 requires very much greater intellect. The level difference between them is great. If you are a good user of UML, that does mean you can use LePus3. It is pity that there are no instruments between them.

And yes, I love LePus3!

ContentLicense: CC BY-SA 2.5


问:
How to manage multiple currencies in the database
If I have different multiple payroll disbursements based on the company location, the employee contract type and other criteria:
So

Some have their salaries divided into parts the first in USD and the second in Local cur.

```<code>Ex: Employee 343 receive his salary as following: 200 USD & 3000 EGP (The local currency).
EX: Employee 672 receive his salary as following: 200 USD & 200 EUR (The local currency).
</code>```

Some have their salaries just in one currency (the local).

```<code>Ex: Employee 532 receive his salary as following: 5000 EGP.
</code>```

So We have multiple currencies for the salaries of the company based on the location and other business rules.

What 's the most proper way to save the salaries of the employees with these variations in DB so that It's easy to retrieve, process and scale.

If I use one table so I will have many columns and I have to add new columns every time a new branch for the company is initiated.
Like this:

```<code>Sal_USD  | Sal_EGP | Sal_Eur
</code>```

Is there an elegant way to handle this?

答:
The correct way is always to support an infinite numbers of connections. So create a table with salary an another with currency.

I think 3tables would do the jobb

```<code>Employee (the one you have now)
- EmployeeID

Salary
 - SalaryID
 - EmployeeID
 - CurrencyID
 - Wage
 - Exchangerate ?

CurrencyID
 - CurrencyID
 - Name (USD/GDP/EUR....)
</code>```

Then you simply join them in.

Body:
If I have different multiple payroll disbursements based on the company location, the employee contract type and other criteria:
So

Some have their salaries divided into parts the first in USD and the second in Local cur.

Ex: Employee 343 receive his salary as following: 200 USD & 3000 EGP (The local currency).
EX: Employee 672 receive his salary as following: 200 USD & 200 EUR (The local currency).

Some have their salaries just in one currency (the local).

Ex: Employee 532 receive his salary as following: 5000 EGP.

So We have multiple currencies for the salaries of the company based on the location and other business rules.

What 's the most proper way to save the salaries of the employees with these variations in DB so that It's easy to retrieve, process and scale.

If I use one table so I will have many columns and I have to add new columns every time a new branch for the company is initiated.
Like this:

Sal_USD  | Sal_EGP | Sal_Eur

Is there an elegant way to handle this?

Body:
The correct way is always to support an infinite numbers of connections. So create a table with salary an another with currency.

I think 3tables would do the jobb

Employee (the one you have now)
- EmployeeID

Salary
 - SalaryID
 - EmployeeID
 - CurrencyID
 - Wage
 - Exchangerate ?

CurrencyID
 - CurrencyID
 - Name (USD/GDP/EUR....)

Then you simply join them in.


问:
Check if a file exists in azure blob container
I have an azure blob container name "x" and I want to check if a file name "a.jpg" exists in that blob or not and return true or false based on that. It seems easy but there isn't a clear answer when I google it.</p>

答:
It is clearly mentioned in the document, if you are using c# you can use ExistsAsync method

```<code>public async Task<bool> FileExists(string fileName)
{
    return  await directory.GetBlockBlobReference(fileName).ExistsAsync();
}
</code>```

Body:
It is clearly mentioned in the document, if you are using c# you can use ExistsAsync method

public async Task<bool> FileExists(string fileName)
{
    return  await directory.GetBlockBlobReference(fileName).ExistsAsync();
}


问:
Flutter: Changing the current tab in tab bar view using a button
I am creating an app that contains a tab bar on its homepage. I want to be able to navigate to one of the tabs using my FloatingActionButton. In addition, I want to keep the default methods of navigating to that tab, i.e. by swiping on screen or by clicking the tab.

I also want to know how to link that tab to some other button.

Here is a screenshot of my homepage.

答:
You can use TabController:

```<code>TabController _controller = TabController(
  vsync: this,
  length: 3,
  initialIndex: 0,
);

_controller.animateTo(_currentTabIndex);

return Scaffold(
  appBar: AppBar(
    bottom: TabBar(
      controller: _controller,
      tabs: [
        ...
      ],
    ),
  ),
  body: TabBarView(
    controller: _controller,
    children: [
      ...
    ],
  ),
);
</code>```

And than, setState to update screen:

```<code>int _currentTabIndex = 0;

setState(() {
  _currentTabIndex = 1;
});
</code>```

Body:
You can use TabController:

TabController _controller = TabController(
  vsync: this,
  length: 3,
  initialIndex: 0,
);

_controller.animateTo(_currentTabIndex);

return Scaffold(
  appBar: AppBar(
    bottom: TabBar(
      controller: _controller,
      tabs: [
        ...
      ],
    ),
  ),
  body: TabBarView(
    controller: _controller,
    children: [
      ...
    ],
  ),
);

And than, setState to update screen:

int _currentTabIndex = 0;

setState(() {
  _currentTabIndex = 1;
});


问:
how to do Monitor fit application in winform?
In my winform application want to cover full computer monitor. But, windows 7 task bar visible.

how to code Monitor fit application in winform?

thanks in advance!.

答:
In the Shown event handler add the following code:</p>

```<code>WindowState = FormWindowState.Normal;
FormBorderStyle = FormBorderStyle.None;
Bounds = Screen.GetBounds(this);
</code>```

Body:
In the Shown event handler add the following code:

WindowState = FormWindowState.Normal;
FormBorderStyle = FormBorderStyle.None;
Bounds = Screen.GetBounds(this);


问:
How to save output in python to .txt file
So basically i bought a book that teaches the basics of python and how to create a random number generator so I decided to go one step further and make a random password generator I found a tutorial online that gave me a good example of why and what is used to make a password generator but i want the output to be saved to a .txt file I do not know what i need to implement to get the result i want this is what i have i'm using python3.

```<code>import random

chars = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!, @,#$%^&*.'

number = input('Number of passwords - ')
number = int(number)

length = input('password length? - ')
length = int(length)

answer = input

for P in range(number):
    password = ''
for C in range(length):
    password += random.choice(chars)
    print(password)

password = open("passlist.txt", "a")
password.write(password)
password.close()

file = open('passlist', 'w')
file.write(password)
file.close()
</code>```

this is what i get in shell

```<code> Traceback (most recent call last):
      File "C:\User\Desktop\passgen.py", line 21, in <module>
        password.write(password)
    TypeError: write() argument must be str, not _io.TextIOWrapper
</code>```

答:
```<code>filename = 'passlist.txt'
with open (filename, 'a') as file_object:
    file_object.write(password)
</code>```

Using with will close the file once access is no longer needed.

You also need a list to append your passwords ;)

Body:
So basically i bought a book that teaches the basics of python and how to create a random number generator so I decided to go one step further and make a random password generator I found a tutorial online that gave me a good example of why and what is used to make a password generator but i want the output to be saved to a .txt file I do not know what i need to implement to get the result i want this is what i have i'm using python3.

import random

chars = 'abcdefghijklmnopqrstuvwxyz1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZ!, @,#$%^&*.'

number = input('Number of passwords - ')
number = int(number)

length = input('password length? - ')
length = int(length)

answer = input

for P in range(number):
    password = ''
for C in range(length):
    password += random.choice(chars)
    print(password)

password = open("passlist.txt", "a")
password.write(password)
password.close()

file = open('passlist', 'w')
file.write(password)
file.close()

this is what i get in shell

 Traceback (most recent call last):
      File "C:\User\Desktop\passgen.py", line 21, in <module>
        password.write(password)
    TypeError: write() argument must be str, not _io.TextIOWrapper

Body:
filename = 'passlist.txt'
with open (filename, 'a') as file_object:
    file_object.write(password)

Using with will close the file once access is no longer needed.

You also need a list to append your passwords ;)


问:
error when reshaping array with prime dimension
I want to reshape an array with 1501 (waveform) to (3,500) , but it complains as follow. please, help me to solve this problem.

```<code>x = np.array(x_train[2])
print(x.shape)
y = np.reshape(x, (int(len(x) / 500), 500))
print(y.shape)
</code>```

Here is the output:

```<code>(1501,)

ValueError: cannot reshape array of size 1501 into shape (3,500)
</code>```

答:
If you want to view your data in chunks of 500, but it does not have a multiple of 500 elements, you need to truncate or pad it first. Let's say you are going with truncation here, since you have a wave-form and that last element is probably a repeat that will throw off your FFT anyway.

In that case, you can view less of the data in the buffer, then reshape however you want:

```<code>y = x[:(x.size // 500) * 500].reshape(-1, 500)
</code>```

The nice thing here is that if your data is arranged somewhat sanely in memory, it will not make a copy, but return a contiguous view into the original buffer.

Body:
I want to reshape an array with 1501 (waveform) to (3,500) , but it complains as follow. please, help me to solve this problem.

x = np.array(x_train[2])
print(x.shape)
y = np.reshape(x, (int(len(x) / 500), 500))
print(y.shape)

Here is the output:

(1501,)

ValueError: cannot reshape array of size 1501 into shape (3,500)

Body:
If you want to view your data in chunks of 500, but it does not have a multiple of 500 elements, you need to truncate or pad it first. Let's say you are going with truncation here, since you have a wave-form and that last element is probably a repeat that will throw off your FFT anyway.

In that case, you can view less of the data in the buffer, then reshape however you want:

y = x[:(x.size // 500) * 500].reshape(-1, 500)

The nice thing here is that if your data is arranged somewhat sanely in memory, it will not make a copy, but return a contiguous view into the original buffer.


问:
Invoice Ninja with docker compose - Error 500
I have setup Invoice ninja with docker-compose behind a nginx reverse proxy, which also manages the TLS certificate.

As far as I can see from the logs, everything initializes correct, but when I navigate to the site, I can only see a 500 Server error.

I provided my docker-compose and the logs until the first 500 error below.

Thanks in advance!

docker-compose.yml

```<code>version: '3.7'

services:
  server:
    image: caddy:alpine
    restart: always
    environment:
      - APP_URL=http://ninja.example.de
    volumes:
      # Vhost configuration
      - ./config/caddy/Caddyfile:/etc/caddy/Caddyfile
      - ./public:/var/www/app/public
      - ./storage:/var/www/app/storage
    depends_on:
      - app
    # Run webserver nginx on port 80
    # Feel free to modify depending what port is already occupied
    ports:
      - "127.0.0.1:4301:80"
    #  - "443:443"
    networks:
      - invoiceninja

  app:
    image: invoiceninja/invoiceninja:5
    restart: always
    environment:
      - APP_URL=ninja.example.de
      - APP_KEY=base64:mykeyxzy
      - MULTI_DB_ENABLED=false
      - DB_HOST1=db
    volumes:
      - ./public:/var/www/app/public
      - ./storage:/var/www/app/storage
    depends_on:
      - db
    networks:
      - invoiceninja

  db:
    image: mysql:5
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=mypassword
      - MYSQL_USER=ninja
      - MYSQL_PASSWORD=ninja
      - MYSQL_DATABASE=db-ninja-01
    volumes:
      - ./mysql/data:/var/lib/mysql
    networks:
      - invoiceninja

 # cron:
 # cron is commented out by me

volumes:
  mysql-data:
  public:
  storage:

networks:
  invoiceninja:

</code>```

docker log

```<code>server_1  | {"level":"info","ts":1590774949.786359,"msg":"using provided configuration","config_file":"/etc/caddy/Caddyfile","config_adapter":"caddyfile"}
server_1  | {"level":"info","ts":1590774949.7946017,"logger":"admin","msg":"admin endpoint started","address":"tcp/localhost:2019","enforce_origin":false,"origins":["localhost:2019","[::1]:2019","127.0.0.1:2019"]}
server_1  | {"level":"info","ts":1590774949.7968726,"logger":"http","msg":"server is listening only on the HTTP port, so no automatic HTTPS will be applied to this server","server_name":"srv0","http_port":80}
server_1  | 2020/05/29 17:55:49 [INFO][cache:0xc00075e0a0] Started certificate maintenance routine
server_1  | {"level":"info","ts":1590774949.7995124,"logger":"tls","msg":"cleaned up storage units"}
server_1  | {"level":"info","ts":1590774949.799886,"msg":"autosaved config","file":"/config/caddy/autosave.json"}
server_1  | {"level":"info","ts":1590774949.799923,"msg":"serving initial configuration"}
app_1     | Configuration cache cleared!
app_1     | Configuration cached successfully!
app_1     | Route cache cleared!
app_1     | Routes cached successfully!
app_1     | Files cached successfully!
app_1     | [29-May-2020 17:55:49] NOTICE: [pool www] 'user' directive is ignored when FPM is not running as root
app_1     | [29-May-2020 17:55:49] NOTICE: [pool www] 'user' directive is ignored when FPM is not running as root
app_1     | [29-May-2020 17:55:49] NOTICE: [pool www] 'group' directive is ignored when FPM is not running as root
app_1     | [29-May-2020 17:55:49] NOTICE: [pool www] 'group' directive is ignored when FPM is not running as root
app_1     | [29-May-2020 17:55:49] NOTICE: fpm is running, pid 1
app_1     | [29-May-2020 17:55:49] NOTICE: ready to handle connections
db_1      | 2020-05-29 17:55:48+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.30-1debian10 started.
db_1      | 2020-05-29 17:55:48+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
db_1      | 2020-05-29 17:55:48+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.30-1debian10 started.
db_1      | 2020-05-29T17:55:48.703457Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
db_1      | 2020-05-29T17:55:48.708189Z 0 [Note] mysqld (mysqld 5.7.30) starting as process 1 ...
db_1      | 2020-05-29T17:55:48.714931Z 0 [Note] InnoDB: PUNCH HOLE support available
db_1      | 2020-05-29T17:55:48.714988Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
db_1      | 2020-05-29T17:55:48.714995Z 0 [Note] InnoDB: Uses event mutexes
db_1      | 2020-05-29T17:55:48.714999Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
db_1      | 2020-05-29T17:55:48.715002Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
db_1      | 2020-05-29T17:55:48.715011Z 0 [Note] InnoDB: Using Linux native AIO
db_1      | 2020-05-29T17:55:48.715701Z 0 [Note] InnoDB: Number of pools: 1
db_1      | 2020-05-29T17:55:48.716017Z 0 [Note] InnoDB: Using CPU crc32 instructions
db_1      | 2020-05-29T17:55:48.722484Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
db_1      | 2020-05-29T17:55:48.741778Z 0 [Note] InnoDB: Completed initialization of buffer pool
db_1      | 2020-05-29T17:55:48.747111Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
db_1      | 2020-05-29T17:55:48.763090Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
db_1      | 2020-05-29T17:55:48.798980Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
db_1      | 2020-05-29T17:55:48.799233Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
db_1      | 2020-05-29T17:55:48.832312Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
db_1      | 2020-05-29T17:55:48.834307Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
db_1      | 2020-05-29T17:55:48.834434Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
db_1      | 2020-05-29T17:55:48.835099Z 0 [Note] InnoDB: Waiting for purge to start
db_1      | 2020-05-29T17:55:48.885461Z 0 [Note] InnoDB: 5.7.30 started; log sequence number 12488420
db_1      | 2020-05-29T17:55:48.886497Z 0 [Note] Plugin 'FEDERATED' is disabled.
db_1      | 2020-05-29T17:55:48.897039Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
db_1      | 2020-05-29T17:55:48.906339Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.
db_1      | 2020-05-29T17:55:48.906387Z 0 [Note] Skipping generation of SSL certificates as certificate files are present in data directory.
db_1      | 2020-05-29T17:55:48.907291Z 0 [Warning] CA certificate ca.pem is self signed.
db_1      | 2020-05-29T17:55:48.907356Z 0 [Note] Skipping generation of RSA key pair as key files are present in data directory.
db_1      | 2020-05-29T17:55:48.908141Z 0 [Note] InnoDB: Buffer pool(s) load completed at 200529 17:55:48
db_1      | 2020-05-29T17:55:48.909168Z 0 [Note] Server hostname (bind-address): '*'; port: 3306
db_1      | 2020-05-29T17:55:48.909863Z 0 [Note] IPv6 is available.
db_1      | 2020-05-29T17:55:48.909911Z 0 [Note]   - '::' resolves to '::';
db_1      | 2020-05-29T17:55:48.909952Z 0 [Note] Server socket created on IP: '::'.
db_1      | 2020-05-29T17:55:48.914971Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
db_1      | 2020-05-29T17:55:48.932266Z 0 [Note] Event Scheduler: Loaded 0 events
db_1      | 2020-05-29T17:55:48.932616Z 0 [Note] mysqld: ready for connections.
db_1      | Version: '5.7.30'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)
app_1     | 192.168.48.5 -  29/May/2020:17:59:07 +0000 "GET /index.php" 500
</code>```

答:
This errors occurs dues to the facts that the application cannot correctly determine the passed application key APP_KEY. It seems the application cache is a bit reluctant to be refreshed - this is only a problem in the docker containers and not for the self-host option w/o docker.

I pushed an update to the for the latest and 5 tags. So first, please update your images. This fixes some permission to get proper write permissions to some cache folders.

Then after your docker-compose setup started please run

docker-compose exec app php artisan config:cache
```

a couple of times and refresh your page. It takes some time and a couple of calls till the cache is refreshed. The error message then changes to SQLSTATE[42S02]: Base table or view not found: this is a know problem but can be fixed (for now) by navigation to /setup which then will run the proper migrations.

Body:
I have setup Invoice ninja with docker-compose behind a nginx reverse proxy, which also manages the TLS certificate.

As far as I can see from the logs, everything initializes correct, but when I navigate to the site, I can only see a 500 Server error.

I provided my docker-compose and the logs until the first 500 error below.

Thanks in advance!

docker-compose.yml

version: '3.7'

services:
  server:
    image: caddy:alpine
    restart: always
    environment:
      - APP_URL=http://ninja.example.de
    volumes:
      # Vhost configuration
      - ./config/caddy/Caddyfile:/etc/caddy/Caddyfile
      - ./public:/var/www/app/public
      - ./storage:/var/www/app/storage
    depends_on:
      - app
    # Run webserver nginx on port 80
    # Feel free to modify depending what port is already occupied
    ports:
      - "127.0.0.1:4301:80"
    #  - "443:443"
    networks:
      - invoiceninja

  app:
    image: invoiceninja/invoiceninja:5
    restart: always
    environment:
      - APP_URL=ninja.example.de
      - APP_KEY=base64:mykeyxzy
      - MULTI_DB_ENABLED=false
      - DB_HOST1=db
    volumes:
      - ./public:/var/www/app/public
      - ./storage:/var/www/app/storage
    depends_on:
      - db
    networks:
      - invoiceninja

  db:
    image: mysql:5
    restart: always
    environment:
      - MYSQL_ROOT_PASSWORD=mypassword
      - MYSQL_USER=ninja
      - MYSQL_PASSWORD=ninja
      - MYSQL_DATABASE=db-ninja-01
    volumes:
      - ./mysql/data:/var/lib/mysql
    networks:
      - invoiceninja

 # cron:
 # cron is commented out by me

volumes:
  mysql-data:
  public:
  storage:

networks:
  invoiceninja:

docker log

server_1  | {"level":"info","ts":1590774949.786359,"msg":"using provided configuration","config_file":"/etc/caddy/Caddyfile","config_adapter":"caddyfile"}
server_1  | {"level":"info","ts":1590774949.7946017,"logger":"admin","msg":"admin endpoint started","address":"tcp/localhost:2019","enforce_origin":false,"origins":["localhost:2019","[::1]:2019","127.0.0.1:2019"]}
server_1  | {"level":"info","ts":1590774949.7968726,"logger":"http","msg":"server is listening only on the HTTP port, so no automatic HTTPS will be applied to this server","server_name":"srv0","http_port":80}
server_1  | 2020/05/29 17:55:49 [INFO][cache:0xc00075e0a0] Started certificate maintenance routine
server_1  | {"level":"info","ts":1590774949.7995124,"logger":"tls","msg":"cleaned up storage units"}
server_1  | {"level":"info","ts":1590774949.799886,"msg":"autosaved config","file":"/config/caddy/autosave.json"}
server_1  | {"level":"info","ts":1590774949.799923,"msg":"serving initial configuration"}
app_1     | Configuration cache cleared!
app_1     | Configuration cached successfully!
app_1     | Route cache cleared!
app_1     | Routes cached successfully!
app_1     | Files cached successfully!
app_1     | [29-May-2020 17:55:49] NOTICE: [pool www] 'user' directive is ignored when FPM is not running as root
app_1     | [29-May-2020 17:55:49] NOTICE: [pool www] 'user' directive is ignored when FPM is not running as root
app_1     | [29-May-2020 17:55:49] NOTICE: [pool www] 'group' directive is ignored when FPM is not running as root
app_1     | [29-May-2020 17:55:49] NOTICE: [pool www] 'group' directive is ignored when FPM is not running as root
app_1     | [29-May-2020 17:55:49] NOTICE: fpm is running, pid 1
app_1     | [29-May-2020 17:55:49] NOTICE: ready to handle connections
db_1      | 2020-05-29 17:55:48+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.30-1debian10 started.
db_1      | 2020-05-29 17:55:48+00:00 [Note] [Entrypoint]: Switching to dedicated user 'mysql'
db_1      | 2020-05-29 17:55:48+00:00 [Note] [Entrypoint]: Entrypoint script for MySQL Server 5.7.30-1debian10 started.
db_1      | 2020-05-29T17:55:48.703457Z 0 [Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).
db_1      | 2020-05-29T17:55:48.708189Z 0 [Note] mysqld (mysqld 5.7.30) starting as process 1 ...
db_1      | 2020-05-29T17:55:48.714931Z 0 [Note] InnoDB: PUNCH HOLE support available
db_1      | 2020-05-29T17:55:48.714988Z 0 [Note] InnoDB: Mutexes and rw_locks use GCC atomic builtins
db_1      | 2020-05-29T17:55:48.714995Z 0 [Note] InnoDB: Uses event mutexes
db_1      | 2020-05-29T17:55:48.714999Z 0 [Note] InnoDB: GCC builtin __atomic_thread_fence() is used for memory barrier
db_1      | 2020-05-29T17:55:48.715002Z 0 [Note] InnoDB: Compressed tables use zlib 1.2.11
db_1      | 2020-05-29T17:55:48.715011Z 0 [Note] InnoDB: Using Linux native AIO
db_1      | 2020-05-29T17:55:48.715701Z 0 [Note] InnoDB: Number of pools: 1
db_1      | 2020-05-29T17:55:48.716017Z 0 [Note] InnoDB: Using CPU crc32 instructions
db_1      | 2020-05-29T17:55:48.722484Z 0 [Note] InnoDB: Initializing buffer pool, total size = 128M, instances = 1, chunk size = 128M
db_1      | 2020-05-29T17:55:48.741778Z 0 [Note] InnoDB: Completed initialization of buffer pool
db_1      | 2020-05-29T17:55:48.747111Z 0 [Note] InnoDB: If the mysqld execution user is authorized, page cleaner thread priority can be changed. See the man page of setpriority().
db_1      | 2020-05-29T17:55:48.763090Z 0 [Note] InnoDB: Highest supported file format is Barracuda.
db_1      | 2020-05-29T17:55:48.798980Z 0 [Note] InnoDB: Creating shared tablespace for temporary tables
db_1      | 2020-05-29T17:55:48.799233Z 0 [Note] InnoDB: Setting file './ibtmp1' size to 12 MB. Physically writing the file full; Please wait ...
db_1      | 2020-05-29T17:55:48.832312Z 0 [Note] InnoDB: File './ibtmp1' size is now 12 MB.
db_1      | 2020-05-29T17:55:48.834307Z 0 [Note] InnoDB: 96 redo rollback segment(s) found. 96 redo rollback segment(s) are active.
db_1      | 2020-05-29T17:55:48.834434Z 0 [Note] InnoDB: 32 non-redo rollback segment(s) are active.
db_1      | 2020-05-29T17:55:48.835099Z 0 [Note] InnoDB: Waiting for purge to start
db_1      | 2020-05-29T17:55:48.885461Z 0 [Note] InnoDB: 5.7.30 started; log sequence number 12488420
db_1      | 2020-05-29T17:55:48.886497Z 0 [Note] Plugin 'FEDERATED' is disabled.
db_1      | 2020-05-29T17:55:48.897039Z 0 [Note] InnoDB: Loading buffer pool(s) from /var/lib/mysql/ib_buffer_pool
db_1      | 2020-05-29T17:55:48.906339Z 0 [Note] Found ca.pem, server-cert.pem and server-key.pem in data directory. Trying to enable SSL support using them.
db_1      | 2020-05-29T17:55:48.906387Z 0 [Note] Skipping generation of SSL certificates as certificate files are present in data directory.
db_1      | 2020-05-29T17:55:48.907291Z 0 [Warning] CA certificate ca.pem is self signed.
db_1      | 2020-05-29T17:55:48.907356Z 0 [Note] Skipping generation of RSA key pair as key files are present in data directory.
db_1      | 2020-05-29T17:55:48.908141Z 0 [Note] InnoDB: Buffer pool(s) load completed at 200529 17:55:48
db_1      | 2020-05-29T17:55:48.909168Z 0 [Note] Server hostname (bind-address): '*'; port: 3306
db_1      | 2020-05-29T17:55:48.909863Z 0 [Note] IPv6 is available.
db_1      | 2020-05-29T17:55:48.909911Z 0 [Note]   - '::' resolves to '::';
db_1      | 2020-05-29T17:55:48.909952Z 0 [Note] Server socket created on IP: '::'.
db_1      | 2020-05-29T17:55:48.914971Z 0 [Warning] Insecure configuration for --pid-file: Location '/var/run/mysqld' in the path is accessible to all OS users. Consider choosing a different directory.
db_1      | 2020-05-29T17:55:48.932266Z 0 [Note] Event Scheduler: Loaded 0 events
db_1      | 2020-05-29T17:55:48.932616Z 0 [Note] mysqld: ready for connections.
db_1      | Version: '5.7.30'  socket: '/var/run/mysqld/mysqld.sock'  port: 3306  MySQL Community Server (GPL)
app_1     | 192.168.48.5 -  29/May/2020:17:59:07 +0000 "GET /index.php" 500

Body:
This errors occurs dues to the facts that the application cannot correctly determine the passed application key APP_KEY. It seems the application cache is a bit reluctant to be refreshed - this is only a problem in the docker containers and not for the self-host option w/o docker.

I pushed an update to the for the latest and 5 tags. So first, please update your images. This fixes some permission to get proper write permissions to some cache folders.

Then after your docker-compose setup started please run

docker-compose exec app php artisan config:cache

a couple of times and refresh your page. It takes some time and a couple of calls till the cache is refreshed. The error message then changes to SQLSTATE[42S02]: Base table or view not found: this is a know problem but can be fixed (for now) by navigation to /setup which then will run the proper migrations.


问:
How to change the most significant bit to a 1 after shifting an int to the right using '>>'?
For example, when I have a number such as 0x54 in binary that would be 01010100. After using the bit-wise operator '>>' this number will turn into 00101010. Instead of the most significant bit being a 0, I need it to be a one. How can i accomplish this?</p>

答:
Is your number always 8 bits wide? If thats the case you can simply have the decimal representation of 10000000 which is 128 and do a bitwise or
so let's take your example</p>

```<code>int val = 84; /// 01010100
int newVal = val >> 1; // 00101010
int mostSig = newVal | 128; // 10101010
</code>```

Body:
Is your number always 8 bits wide? If thats the case you can simply have the decimal representation of 10000000 which is 128 and do a bitwise or
so let's take your example

int val = 84; /// 01010100
int newVal = val >> 1; // 00101010
int mostSig = newVal | 128; // 10101010


问:
Redux: Alternative way of clearing Object of Array
I have a state that could look like this:

```<code> [
  0: {
    "id": "8e9x23x2wto",
    "name": "test-player",
    "currentFrame": 1,
    "rolls": {
      "1": [1,3],
      "2": [1,6],
      "3": [1,6],
      "4": [3,8],
      "5": [4,5],
      "6": [7,6],
      "7": [8,1],
      "8": [5,2],
      "9": [2,1],
      "10": [1,1]
    },
    "totalWins": 0
  }
]
</code>```

I am clearing the rolls Object and resetting currentFrame like so:

```<code>case RESET_GAME:
  return {
    ...state,
    players: state.players.map((player) => {
      return {
        ...player,
        currentFrame: 1,
        rolls: Object.assign(player.rolls, Object.values(player.rolls).map(() => []))
      }
    }),
  }
</code>```

However, sometimes random Arrays within rolls don't get cleared - could be the second one, could be the last one...I have no idea way.

Is there any alternative way to clear rolls so that it only consists of empty Arrays or does someone have an explanation why that might happen?
Any input is much appreciated!

答:
You can use Object.fromEntries

```<code>players: state.players.map((player) => {
      return {
        ...player,
        currentFrame: 1,
        rolls: Object.fromEntries( Object.keys(player.rolls).map((key)=>[key,[]]))
      }
    }
</code>```

let player = {
  rolls: {
    "1": [1, 3],
    "2": [1, 6],
    "3": [1, 6],
    "4": [3, 8],
    "5": [4, 5],
    "6": [7, 6],
    "7": [8, 1],
    "8": [5, 2],
    "9": [2, 1],
    "10": [1, 1]
  }
}
console.log(Object.fromEntries( Object.keys(player.rolls).map((key)=>[key,[]])))```

Body:
I have a state that could look like this:

 [
  0: {
    "id": "8e9x23x2wto",
    "name": "test-player",
    "currentFrame": 1,
    "rolls": {
      "1": [1,3],
      "2": [1,6],
      "3": [1,6],
      "4": [3,8],
      "5": [4,5],
      "6": [7,6],
      "7": [8,1],
      "8": [5,2],
      "9": [2,1],
      "10": [1,1]
    },
    "totalWins": 0
  }
]

I am clearing the rolls Object and resetting currentFrame like so:

case RESET_GAME:
  return {
    ...state,
    players: state.players.map((player) => {
      return {
        ...player,
        currentFrame: 1,
        rolls: Object.assign(player.rolls, Object.values(player.rolls).map(() => []))
      }
    }),
  }

However, sometimes random Arrays within rolls don't get cleared - could be the second one, could be the last one...I have no idea way.

Is there any alternative way to clear rolls so that it only consists of empty Arrays or does someone have an explanation why that might happen?
Any input is much appreciated!

Body:
You can use Object.fromEntries

players: state.players.map((player) => {
      return {
        ...player,
        currentFrame: 1,
        rolls: Object.fromEntries( Object.keys(player.rolls).map((key)=>[key,[]]))
      }
    }

let player = {
  rolls: {
    "1": [1, 3],
    "2": [1, 6],
    "3": [1, 6],
    "4": [3, 8],
    "5": [4, 5],
    "6": [7, 6],
    "7": [8, 1],
    "8": [5, 2],
    "9": [2, 1],
    "10": [1, 1]
  }
}
console.log(Object.fromEntries( Object.keys(player.rolls).map((key)=>[key,[]])))


问:
Iterating over founded objects with indexes
I get an error : obj.attr is not a function.

```<code>  clone.find(".blockBase").each(function(i, obj) {
     obj.attr("id",newid+"b"+i);
     console.log("Base",i);
  });
</code>```

I can't figure out why ? obj should be a jquery element.

答:
The each method returns the dom object, not a jquery object, so to use attr() you need to convert it to a jQuery object.

```<code>$(obj).attr("id",newid + "b" + i);
</code>```

If you are just changing the id, I would use attr with a function.

const clone = $("ul")
const newid = "foo"
clone.find(".blockBase").attr("id", function (i) {
  return newid + "b" + i;
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>li::after {
  content: attr(id);
  color: green;
}</code>```

1

2

3

4

5

```

Body:
I get an error : obj.attr is not a function.

  clone.find(".blockBase").each(function(i, obj) {
     obj.attr("id",newid+"b"+i);
     console.log("Base",i);
  });

I can't figure out why ? obj should be a jquery element.

Body:
The each method returns the dom object, not a jquery object, so to use attr() you need to convert it to a jQuery object.

$(obj).attr("id",newid + "b" + i);

If you are just changing the id, I would use attr with a function.

const clone = $("ul")
const newid = "foo"
clone.find(".blockBase").attr("id", function (i) {
  return newid + "b" + i;
})

li::after {
  content: attr(id);
  color: green;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul>
  <li class="blockBase">1</li>
  <li class="blockBase">2</li>
  <li class="blockBase">3</li>
  <li class="blockBase">4</li>
  <li class="blockBase">5</li>
</ul>


问:
Plotly: best way to define the Z argument in the create_annotated_heatmap() function
I'm brand new to Plotly and Dash.  I'm trying to create a heat map that displays the underyling numerical values.

The docs at https://plotly.com/python/heatmaps/ say that it's possible to use the ff.create_annotated_heatmap()  function, as follows:

```<code>import plotly.figure_factory as ff

z = [[.1, .3, .5],
     [1.0, .8, .6],
     [.6, .4, .2]]

x = ['Team A', 'Team B', 'Team C']
y = ['Game Three', 'Game Two', 'Game One']

z_text = [['Win', 'Lose', 'Win'],
          ['Lose', 'Lose', 'Win'],
          ['Win', 'Win', 'Lose']]

fig = ff.create_annotated_heatmap(z, x=x, y=y, annotation_text=z_text, colorscale='Viridis')
fig.show()
</code>```

The first argument, data, seems to be a list of lists.

My data looks as follows:

```<code>df = pd.DataFrame({'Make':['Ford', 'Ford', 'Ford', 'Buick', 'Buick', 'Buick', 'Mercedes', 'Mercedes', 'Mercedes'],
                          'Score':['88.6', '76.6', '86.2', '79.1', '86.8', '96.4', '97.3', '98.7', '98.5'],
                          'Dimension':['Speed', 'MPG', 'Styling', 'Speed', 'MPG', 'Styling', 'Speed', 'MPG', 'Styling'],
                          'Month':['Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19']})
</code>```

And, my code is as follows:

```<code>ford_scores = df[(df['Make'].isin(['Ford']))]['Score'].astype(float).tolist()
buick_scores = df[(df['Make'].isin(['Buick']))]['Score'].astype(float).tolist()
mercedes_scores = df[(df['Make'].isin(['Mercedes']))]['Score'].astype(float).tolist()

import plotly.figure_factory as ff
fig = ff.create_annotated_heatmap(
            z=[ford_scores, buick_scores, mercedes_scores],
            x=df['Dimension'].unique().tolist(),
            y=df['Make'].unique().tolist(),
            colorscale=['red', 'orange', 'yellow', 'green'],
            hoverongaps=False
            )

fig.show()

</code>```

This code works, but it breaks down spectacularly when the values in the Make column are something other than "Ford", "Buick" or "Mercedes" (or if the number of elements increases or decreases).

As you can see, I'm manually defining the ford_scores, buick_scores and mercedes_scores before passing them to the Z argument in the create_annotated_heatmap() function.

This is hacky.  There has to be a better way!

Is there a way to pass in the 'df' data frame to the Z argument such that the function "understands" that the Z argument consists of the values in the 'Score' column?  If not, is there another way to pass in the Z argument such that doing so doesn't require advance knowledge of the data and pre-processing the lists? (i.e. so that it's agnostic and flexible as to what's being passed in)

Thanks!

答:
It turns out that there is a much better (and less hacky) way!  Courtesy of our friends at Plotly, the solution is as follows:

```<code>df = pd.DataFrame({'Make':['Ford', 'Ford', 'Ford', 'Buick', 'Buick', 'Buick', 'Mercedes', 'Mercedes', 'Mercedes'],
                          'Score':['88.6', '76.6', '86.2', '79.1', '86.8', '96.4', '97.3', '98.7', '98.5'],
                          'Dimension':['Speed', 'MPG', 'Styling', 'Speed', 'MPG', 'Styling', 'Speed', 'MPG', 'Styling'],
                          'Month':['Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19']})

df['Score'] = pd.to_numeric(df['Score'])
df = pd.pivot_table(df, values='Score', index='Make', columns=['Dimension'])

import plotly.figure_factory as ff

fig = ff.create_annotated_heatmap(
            z=df.to_numpy(),
            x=df.columns.tolist(),
            y=df.index.tolist(),
            colorscale=['red', 'orange', 'yellow', 'green'],
            hoverongaps=False
            )

fig.show()
</code>```

Hope this helps someone in the future!

Body:
I'm brand new to Plotly and Dash.  I'm trying to create a heat map that displays the underyling numerical values.

The docs at https://plotly.com/python/heatmaps/ say that it's possible to use the ff.create_annotated_heatmap()  function, as follows:

import plotly.figure_factory as ff

z = [[.1, .3, .5],
     [1.0, .8, .6],
     [.6, .4, .2]]

x = ['Team A', 'Team B', 'Team C']
y = ['Game Three', 'Game Two', 'Game One']

z_text = [['Win', 'Lose', 'Win'],
          ['Lose', 'Lose', 'Win'],
          ['Win', 'Win', 'Lose']]

fig = ff.create_annotated_heatmap(z, x=x, y=y, annotation_text=z_text, colorscale='Viridis')
fig.show()

The first argument, data, seems to be a list of lists.

My data looks as follows:

df = pd.DataFrame({'Make':['Ford', 'Ford', 'Ford', 'Buick', 'Buick', 'Buick', 'Mercedes', 'Mercedes', 'Mercedes'],
                          'Score':['88.6', '76.6', '86.2', '79.1', '86.8', '96.4', '97.3', '98.7', '98.5'],
                          'Dimension':['Speed', 'MPG', 'Styling', 'Speed', 'MPG', 'Styling', 'Speed', 'MPG', 'Styling'],
                          'Month':['Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19']})

And, my code is as follows:

ford_scores = df[(df['Make'].isin(['Ford']))]['Score'].astype(float).tolist()
buick_scores = df[(df['Make'].isin(['Buick']))]['Score'].astype(float).tolist()
mercedes_scores = df[(df['Make'].isin(['Mercedes']))]['Score'].astype(float).tolist()

import plotly.figure_factory as ff
fig = ff.create_annotated_heatmap(
            z=[ford_scores, buick_scores, mercedes_scores],
            x=df['Dimension'].unique().tolist(),
            y=df['Make'].unique().tolist(),
            colorscale=['red', 'orange', 'yellow', 'green'],
            hoverongaps=False
            )

fig.show()

This code works, but it breaks down spectacularly when the values in the Make column are something other than "Ford", "Buick" or "Mercedes" (or if the number of elements increases or decreases).

As you can see, I'm manually defining the ford_scores, buick_scores and mercedes_scores before passing them to the Z argument in the create_annotated_heatmap() function.

This is hacky.  There has to be a better way!

Is there a way to pass in the 'df' data frame to the Z argument such that the function "understands" that the Z argument consists of the values in the 'Score' column?  If not, is there another way to pass in the Z argument such that doing so doesn't require advance knowledge of the data and pre-processing the lists? (i.e. so that it's agnostic and flexible as to what's being passed in)

Thanks!

Body:
It turns out that there is a much better (and less hacky) way!  Courtesy of our friends at Plotly, the solution is as follows:

df = pd.DataFrame({'Make':['Ford', 'Ford', 'Ford', 'Buick', 'Buick', 'Buick', 'Mercedes', 'Mercedes', 'Mercedes'],
                          'Score':['88.6', '76.6', '86.2', '79.1', '86.8', '96.4', '97.3', '98.7', '98.5'],
                          'Dimension':['Speed', 'MPG', 'Styling', 'Speed', 'MPG', 'Styling', 'Speed', 'MPG', 'Styling'],
                          'Month':['Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19', 'Apr-19']})

df['Score'] = pd.to_numeric(df['Score'])
df = pd.pivot_table(df, values='Score', index='Make', columns=['Dimension'])

import plotly.figure_factory as ff

fig = ff.create_annotated_heatmap(
            z=df.to_numpy(),
            x=df.columns.tolist(),
            y=df.index.tolist(),
            colorscale=['red', 'orange', 'yellow', 'green'],
            hoverongaps=False
            )

fig.show()

Hope this helps someone in the future!


问:
Flutter widget not running initState and passing it into a Widget correctly
I have the below code, and the idea is that when the user logs in, they are pushed to this page ('dashboard'). I am trying to use initState to make the app run the function takenSurvey2(), which then creates a value for the bool takenSurvey. This comes from querying Cloud Firestore.

The value for the bool takenSurvey would then be used in the Stack's Positioned widget to determine which icon to show the user (if the user hasn't taken the survey (i.e. takenSurvey  = false) they would be shown a 'new' icon.

However what happens at the moment is that when the user logs in and the page loads, and the error icon shows, so the widget thinks that takenSurvey does not have a value of true or false. However, when I create an arbitrary button and use OnPressed to print the value of takenSurvey, it shows up as 'false' in the console. When I hot reload the dashboard page the error icon turns to the 'new' icon, as I expected - why doesn't it do this straight away?

I'm not sure what I'm doing wrong, and why the widget can't see the value of takenSurvey, even though takenSurvey2() has been run in initState, and I've wrapped it in a Builder widget?

```<code>      class Dashboard extends StatefulWidget {
      static const String id = 'dashboard';
      @override
      _DashboardState createState() => _DashboardState();
    }

    class _DashboardState extends State<Dashboard> {
      final _auth = FirebaseAuth.instance;
      var userid;
      String surveyName;
      bool takenSurvey;
      String title;

 @override
  void initState() {
    super.initState();

    getCurrentUser();
    getUserID();
    currentSurveyName();
    takenSurvey2();
  }

void takenSurvey2() async {
    final snapShot = await Firestore.instance
        .collection('$surveyName' + '_entrants')
        .document(userid)
        .get();
    if (snapShot.exists) {
      takenSurvey = true;
    } else {
      takenSurvey = false;
    }
  }

 @override   Widget build(BuildContext context) {
      body: SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 24.0),
          child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
               Stack(
                  alignment: Alignment.center,
                  children: <Widget>[
                    Container(
                      width: MediaQuery.of(context).size.width * 0.9,
                      child: SquareButton(
                          buttonTitle: "",
                          fontSize: 36,
                          onPressed: () async {
                            final snapShot = await Firestore.instance
                                .collection('$surveyName' + '_entrants')
                                .document(userid)
                                .get();
                            if (snapShot.exists) {
                              _alreadyCompletedSurveyError();
                            } else if (surveyName.isEmpty)
                              _otherError();
                            else {
                              return Navigator.push(
                                  context,
                                  new MaterialPageRoute(
                                      builder: (BuildContext context) =>
                                          new TestSurvey(surveyName)));
                            }
                          }),
                    ),
                    Positioned(
                      right: 30,
                      top: 20,
                      child: Builder(builder: (context) {
                        if (takenSurvey == false) {
                          return Icon(
                            Foundation.burst_new,
                            size: 48,
                            color: Color(0xff303841),
                          );
                        } else if (takenSurvey == true) {
                          return Icon(
                            Foundation.check,
                            size: 48,
                            color: Color(0xff303841),
                          );
                        } else
                          return Icon(
                            MaterialIcons.error,
                            size: 48,
                            color: Color(0xff303841),
                          );
                      }),
                    ),
                    Container(
                      child: Text('Latest Survey',
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 36,
                              fontFamily: "Roboto")),
</code>```

答:
First notice that widgets build() method is synchronous, so it runs immediately on Flutter need and could be called as many times as framework need it, not called once

Secondly notice your takenSurvey has no default value and it initialized with null

So what happens next:

when the your widget gets into the tree initState is called

your async routines starts

build() method is called by framework and first frame is rendered

takenSurvey == null that's why error Icon is shown

sometime later your async routines completes (never before first frame) and takenSurvey value setted true/false

missed step - notify Flutter that routine is completed and we got some data to show

What about button pressed or hot reload - you doing this after your routine is completed, if you hit them before - you'll see null

Hot reload does rebuild tree and finally you can see data on screen

First simpliest fix to your code is to call setState() at the end of void takenSurvey2() routine - this will rebuild you widget(flutter reruns build())

```<code>void takenSurvey2() async {
   final snapShot = await Firestore.instance
      .collection('$surveyName' + '_entrants')
      .document(userid)
      .get();
   if (snapShot.exists) {
     takenSurvey = true;
   } else {
     takenSurvey = false;
   }
   setState((){});
}
</code>```

Surely you need to deal with takenSurvey == null - you need to show to user Loading indicator because you perform some async action but user does not knows what it's going on

Second and more convinient way is to use FutureBuilder (it's up to you to finish next code snippet to make it work, fill free to ask in comments)

```<code>    FutureBuilder(
        future: Firestore.instance
          .collection('$surveyName' + '_entrants')
          .document(userid)
          .get(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            if (snapshot.data.exists) {
              _alreadyCompletedSurveyError();
            } else if (surveyName.isEmpty)
              _otherError();
              ... more code
          } else {
            // show loading
          }
        },
      )
</code>```

And the last advice - you need to learn State Managment and how to separate logic from widgets.

You will need it on your developer way.

Start here
https://flutter.dev/docs/development/data-and-backend/state-mgmt

Body:
I have the below code, and the idea is that when the user logs in, they are pushed to this page ('dashboard'). I am trying to use initState to make the app run the function takenSurvey2(), which then creates a value for the bool takenSurvey. This comes from querying Cloud Firestore.

The value for the bool takenSurvey would then be used in the Stack's Positioned widget to determine which icon to show the user (if the user hasn't taken the survey (i.e. takenSurvey  = false) they would be shown a 'new' icon.

However what happens at the moment is that when the user logs in and the page loads, and the error icon shows, so the widget thinks that takenSurvey does not have a value of true or false. However, when I create an arbitrary button and use OnPressed to print the value of takenSurvey, it shows up as 'false' in the console. When I hot reload the dashboard page the error icon turns to the 'new' icon, as I expected - why doesn't it do this straight away?

I'm not sure what I'm doing wrong, and why the widget can't see the value of takenSurvey, even though takenSurvey2() has been run in initState, and I've wrapped it in a Builder widget?

      class Dashboard extends StatefulWidget {
      static const String id = 'dashboard';
      @override
      _DashboardState createState() => _DashboardState();
    }

    class _DashboardState extends State<Dashboard> {
      final _auth = FirebaseAuth.instance;
      var userid;
      String surveyName;
      bool takenSurvey;
      String title;

 @override
  void initState() {
    super.initState();

    getCurrentUser();
    getUserID();
    currentSurveyName();
    takenSurvey2();
  }

void takenSurvey2() async {
    final snapShot = await Firestore.instance
        .collection('$surveyName' + '_entrants')
        .document(userid)
        .get();
    if (snapShot.exists) {
      takenSurvey = true;
    } else {
      takenSurvey = false;
    }
  }

 @override   Widget build(BuildContext context) {
      body: SingleChildScrollView(
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 24.0),
          child: Column(
              mainAxisAlignment: MainAxisAlignment.start,
              children: <Widget>[
               Stack(
                  alignment: Alignment.center,
                  children: <Widget>[
                    Container(
                      width: MediaQuery.of(context).size.width * 0.9,
                      child: SquareButton(
                          buttonTitle: "",
                          fontSize: 36,
                          onPressed: () async {
                            final snapShot = await Firestore.instance
                                .collection('$surveyName' + '_entrants')
                                .document(userid)
                                .get();
                            if (snapShot.exists) {
                              _alreadyCompletedSurveyError();
                            } else if (surveyName.isEmpty)
                              _otherError();
                            else {
                              return Navigator.push(
                                  context,
                                  new MaterialPageRoute(
                                      builder: (BuildContext context) =>
                                          new TestSurvey(surveyName)));
                            }
                          }),
                    ),
                    Positioned(
                      right: 30,
                      top: 20,
                      child: Builder(builder: (context) {
                        if (takenSurvey == false) {
                          return Icon(
                            Foundation.burst_new,
                            size: 48,
                            color: Color(0xff303841),
                          );
                        } else if (takenSurvey == true) {
                          return Icon(
                            Foundation.check,
                            size: 48,
                            color: Color(0xff303841),
                          );
                        } else
                          return Icon(
                            MaterialIcons.error,
                            size: 48,
                            color: Color(0xff303841),
                          );
                      }),
                    ),
                    Container(
                      child: Text('Latest Survey',
                          style: TextStyle(
                              color: Colors.white,
                              fontSize: 36,
                              fontFamily: "Roboto")),

Body:
First notice that widgets build() method is synchronous, so it runs immediately on Flutter need and could be called as many times as framework need it, not called once

Secondly notice your takenSurvey has no default value and it initialized with null

So what happens next:

when the your widget gets into the tree initState is called

your async routines starts

build() method is called by framework and first frame is rendered

takenSurvey == null that's why error Icon is shown

sometime later your async routines completes (never before first frame) and takenSurvey value setted true/false

missed step - notify Flutter that routine is completed and we got some data to show

What about button pressed or hot reload - you doing this after your routine is completed, if you hit them before - you'll see null

Hot reload does rebuild tree and finally you can see data on screen

First simpliest fix to your code is to call setState() at the end of void takenSurvey2() routine - this will rebuild you widget(flutter reruns build())

void takenSurvey2() async {
   final snapShot = await Firestore.instance
      .collection('$surveyName' + '_entrants')
      .document(userid)
      .get();
   if (snapShot.exists) {
     takenSurvey = true;
   } else {
     takenSurvey = false;
   }
   setState((){});
}

Surely you need to deal with takenSurvey == null - you need to show to user Loading indicator because you perform some async action but user does not knows what it's going on

Second and more convinient way is to use FutureBuilder (it's up to you to finish next code snippet to make it work, fill free to ask in comments)

    FutureBuilder(
        future: Firestore.instance
          .collection('$surveyName' + '_entrants')
          .document(userid)
          .get(),
        builder: (context, snapshot) {
          if (snapshot.hasData) {
            if (snapshot.data.exists) {
              _alreadyCompletedSurveyError();
            } else if (surveyName.isEmpty)
              _otherError();
              ... more code
          } else {
            // show loading
          }
        },
      )

And the last advice - you need to learn State Managment and how to separate logic from widgets.

You will need it on your developer way.

Start here
https://flutter.dev/docs/development/data-and-backend/state-mgmt


问:
Getting encrypted body response WinHttp HTTPS
I'm trying to connect with google.com with port 443 SSL but when i call to WinHttpReadData returns encrypted text, but with WinHttpQueryHeaders i'm getting plain/text response headers from server.

Not sure at all why happens that, im referring to Headers no encrypted and Body yes, my objective is get the response body decrypted.

The source is here:

```<code>// ConsoleApplication3.cpp : Este archivo contiene la función "main". La ejecución del programa comienza y termina ahí.
//

#include "pch.h"
#include <windows.h>
#include <winhttp.h>
#include <iostream>
#include <string>
#include <algorithm>

int main(){

    DWORD dwSize = 2000;
    DWORD dwDownloaded = 0;
    LPSTR pszOutBuffer;
    DWORD headerSize = 0;
    char * lpOutBuffer = new char[dwSize / sizeof(char)];

    HINTERNET hSession = NULL;
    HINTERNET hConnect = NULL;
    HINTERNET hRequest = NULL;

    // Use WinHttpOpen to obtain a session handle.
    hSession = WinHttpOpen(L"WinHTTP Example/1.0",
        WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
        WINHTTP_NO_PROXY_NAME,
        WINHTTP_NO_PROXY_BYPASS, 0);

    // Specify an HTTP server.
    if (hSession)
        hConnect = WinHttpConnect(hSession, L"google.com",
            443, 0); //443 port for SSL/TLS

    std::cout << "hConnect " << hConnect << std::endl;

    // Create an HTTP request handle.
    if (hConnect)
        hRequest = WinHttpOpenRequest(hConnect, L"GET", L"/",
            L"HTTP/1.1", WINHTTP_NO_REFERER,
            NULL,
            WINHTTP_FLAG_SECURE); //SECURE FLAG

    std::cout << "hRequest " << hRequest << std::endl;

    if (hRequest) { //Adding Headers

        std::cout << "Añadiendo headers!\n";
        WinHttpAddRequestHeaders(hRequest,
            L"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            -1L,
            WINHTTP_ADDREQ_FLAG_ADD);
        WinHttpAddRequestHeaders(hRequest,
            L"Accept-Encoding: gzip, deflate, br",
            -1L,
            WINHTTP_ADDREQ_FLAG_ADD);

        WinHttpAddRequestHeaders(hRequest,
            L"Accept-Language: es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3",
            -1L,
            WINHTTP_ADDREQ_FLAG_ADD);

        WinHttpAddRequestHeaders(hRequest,
            L"Connection: keep-alive",
            -1L,
            WINHTTP_ADDREQ_FLAG_ADD);

        WinHttpAddRequestHeaders(hRequest,
            L"Host: google.com",
            -1L,
            WINHTTP_ADDREQ_FLAG_ADD);

        WinHttpAddRequestHeaders(hRequest,
            L"Upgrade-Insecure-Requests: 1",
            -1L,
            WINHTTP_ADDREQ_FLAG_ADD);

        WinHttpAddRequestHeaders(hRequest,
            L"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0",
            -1L,
            WINHTTP_ADDREQ_FLAG_ADD);

    }

    // Send a request.
    BOOL bResults;
    if (hRequest)
        bResults = WinHttpSendRequest(hRequest,
            WINHTTP_NO_ADDITIONAL_HEADERS,
            0, WINHTTP_NO_REQUEST_DATA, 0,
            0, 0);

    std::cout << "bResults " << bResults << " " << GetLastError() << std::endl;

    if (bResults)
        bResults = WinHttpReceiveResponse(hRequest, NULL);

    std::cout << "bResults " << bResults << " " << GetLastError() << std::endl;

    if (bResults)
    {
        WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_RAW_HEADERS,
            WINHTTP_HEADER_NAME_BY_INDEX, NULL,
            &dwSize, WINHTTP_NO_HEADER_INDEX);

        printf("Tamaño de los headers: %d", dwSize);

        // Allocate memory for the buffer.
        if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
        {
            lpOutBuffer = new char[dwSize / sizeof(char)];

            // Now, use WinHttpQueryHeaders to retrieve the header.
            bResults = WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_RAW_HEADERS,
                WINHTTP_HEADER_NAME_BY_INDEX,
                lpOutBuffer, &dwSize,
                WINHTTP_NO_HEADER_INDEX);
            if (bResults){

                char * headers_aqui = new char[dwSize / sizeof(char)];
                int dwSize2 = 0;
                for (int i = 0,i2 = 0; i < dwSize; i++) {

                    //std::cout << (int)str[i] << std::endl;
                    if ((int)lpOutBuffer[i] != 0) {
                        headers_aqui[i2] = lpOutBuffer[i];
                        dwSize2 = i2;
                        i2++;
                    }
                }

                std::cout << "Tamaño ahora: " << dwSize2 << std::endl;

                std::string str(headers_aqui, dwSize2);

                std::cout << "Header contents: \n" << str << "\n\n\n\n\n"; //No encrypted or compressed.

            }

        }

    }

    if (bResults)
    {
        do
        {
            // Check for available data.
            dwSize = 0;
            if (!WinHttpQueryDataAvailable(hRequest, &dwSize))
                printf("Error %u in WinHttpQueryDataAvailable.\n",
                    GetLastError());

            // Allocate space for the buffer.
            pszOutBuffer = new char[dwSize + 1];
            if (!pszOutBuffer)
            {
                printf("Out of memory\n");
                dwSize = 0;
            }
            else
            {
                // Read the data.
                ZeroMemory(pszOutBuffer, dwSize + 1);

                if (!WinHttpReadData(hRequest, (LPVOID)pszOutBuffer,
                    dwSize, &dwDownloaded))
                    printf("Error %u in WinHttpReadData.\n", GetLastError());
                else
                    printf("%s", pszOutBuffer); //Encrypted or compressed, think SSL encryption.

                // Free the memory allocated to the buffer.
                delete[] pszOutBuffer;
            }
        } while (dwSize > 0);
    }

    // Report any errors.
    if (!bResults)
        printf("Error %d has occurred.\n", GetLastError());

    // Close any open handles.
    if (hRequest) WinHttpCloseHandle(hRequest);
    if (hConnect) WinHttpCloseHandle(hConnect);
    if (hSession) WinHttpCloseHandle(hSession);

    //std::cout << "Hello World!\n";
}
</code>```

Output here: https://pastebin.com/cSkEugDT

I read the documentation but don't find anything about decryption of content in WinHttpReadData, obviously this happens only with https, when i test http it's return plain/text.

I suspect about some parameter to before calls to WinHttpReadData.

答:
Finally i get the mistake, this was on header Accept-Encoding

```<code>WinHttpAddRequestHeaders(hRequest,
        L"Accept-Encoding: gzip, deflate, br",
        -1L,
        WINHTTP_ADDREQ_FLAG_ADD);
</code>```

I commented and fix the issue. GZIP is a compression algorithm whos made this compressed text (deflate and br another algorithms with same purpose).

About Accept-Encoding header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding

Body:
I'm trying to connect with google.com with port 443 SSL but when i call to WinHttpReadData returns encrypted text, but with WinHttpQueryHeaders i'm getting plain/text response headers from server.

Not sure at all why happens that, im referring to Headers no encrypted and Body yes, my objective is get the response body decrypted.

The source is here:

// ConsoleApplication3.cpp : Este archivo contiene la función "main". La ejecución del programa comienza y termina ahí.
//

#include "pch.h"
#include <windows.h>
#include <winhttp.h>
#include <iostream>
#include <string>
#include <algorithm>

int main(){

    DWORD dwSize = 2000;
    DWORD dwDownloaded = 0;
    LPSTR pszOutBuffer;
    DWORD headerSize = 0;
    char * lpOutBuffer = new char[dwSize / sizeof(char)];

    HINTERNET hSession = NULL;
    HINTERNET hConnect = NULL;
    HINTERNET hRequest = NULL;

    // Use WinHttpOpen to obtain a session handle.
    hSession = WinHttpOpen(L"WinHTTP Example/1.0",
        WINHTTP_ACCESS_TYPE_DEFAULT_PROXY,
        WINHTTP_NO_PROXY_NAME,
        WINHTTP_NO_PROXY_BYPASS, 0);

    // Specify an HTTP server.
    if (hSession)
        hConnect = WinHttpConnect(hSession, L"google.com",
            443, 0); //443 port for SSL/TLS

    std::cout << "hConnect " << hConnect << std::endl;

    // Create an HTTP request handle.
    if (hConnect)
        hRequest = WinHttpOpenRequest(hConnect, L"GET", L"/",
            L"HTTP/1.1", WINHTTP_NO_REFERER,
            NULL,
            WINHTTP_FLAG_SECURE); //SECURE FLAG

    std::cout << "hRequest " << hRequest << std::endl;

    if (hRequest) { //Adding Headers

        std::cout << "Añadiendo headers!\n";
        WinHttpAddRequestHeaders(hRequest,
            L"Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8",
            -1L,
            WINHTTP_ADDREQ_FLAG_ADD);
        WinHttpAddRequestHeaders(hRequest,
            L"Accept-Encoding: gzip, deflate, br",
            -1L,
            WINHTTP_ADDREQ_FLAG_ADD);

        WinHttpAddRequestHeaders(hRequest,
            L"Accept-Language: es-ES,es;q=0.8,en-US;q=0.5,en;q=0.3",
            -1L,
            WINHTTP_ADDREQ_FLAG_ADD);

        WinHttpAddRequestHeaders(hRequest,
            L"Connection: keep-alive",
            -1L,
            WINHTTP_ADDREQ_FLAG_ADD);

        WinHttpAddRequestHeaders(hRequest,
            L"Host: google.com",
            -1L,
            WINHTTP_ADDREQ_FLAG_ADD);

        WinHttpAddRequestHeaders(hRequest,
            L"Upgrade-Insecure-Requests: 1",
            -1L,
            WINHTTP_ADDREQ_FLAG_ADD);

        WinHttpAddRequestHeaders(hRequest,
            L"User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:76.0) Gecko/20100101 Firefox/76.0",
            -1L,
            WINHTTP_ADDREQ_FLAG_ADD);

    }

    // Send a request.
    BOOL bResults;
    if (hRequest)
        bResults = WinHttpSendRequest(hRequest,
            WINHTTP_NO_ADDITIONAL_HEADERS,
            0, WINHTTP_NO_REQUEST_DATA, 0,
            0, 0);

    std::cout << "bResults " << bResults << " " << GetLastError() << std::endl;

    if (bResults)
        bResults = WinHttpReceiveResponse(hRequest, NULL);

    std::cout << "bResults " << bResults << " " << GetLastError() << std::endl;

    if (bResults)
    {
        WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_RAW_HEADERS,
            WINHTTP_HEADER_NAME_BY_INDEX, NULL,
            &dwSize, WINHTTP_NO_HEADER_INDEX);

        printf("Tamaño de los headers: %d", dwSize);

        // Allocate memory for the buffer.
        if (GetLastError() == ERROR_INSUFFICIENT_BUFFER)
        {
            lpOutBuffer = new char[dwSize / sizeof(char)];

            // Now, use WinHttpQueryHeaders to retrieve the header.
            bResults = WinHttpQueryHeaders(hRequest, WINHTTP_QUERY_RAW_HEADERS,
                WINHTTP_HEADER_NAME_BY_INDEX,
                lpOutBuffer, &dwSize,
                WINHTTP_NO_HEADER_INDEX);
            if (bResults){

                char * headers_aqui = new char[dwSize / sizeof(char)];
                int dwSize2 = 0;
                for (int i = 0,i2 = 0; i < dwSize; i++) {

                    //std::cout << (int)str[i] << std::endl;
                    if ((int)lpOutBuffer[i] != 0) {
                        headers_aqui[i2] = lpOutBuffer[i];
                        dwSize2 = i2;
                        i2++;
                    }
                }

                std::cout << "Tamaño ahora: " << dwSize2 << std::endl;

                std::string str(headers_aqui, dwSize2);

                std::cout << "Header contents: \n" << str << "\n\n\n\n\n"; //No encrypted or compressed.

            }

        }

    }

    if (bResults)
    {
        do
        {
            // Check for available data.
            dwSize = 0;
            if (!WinHttpQueryDataAvailable(hRequest, &dwSize))
                printf("Error %u in WinHttpQueryDataAvailable.\n",
                    GetLastError());

            // Allocate space for the buffer.
            pszOutBuffer = new char[dwSize + 1];
            if (!pszOutBuffer)
            {
                printf("Out of memory\n");
                dwSize = 0;
            }
            else
            {
                // Read the data.
                ZeroMemory(pszOutBuffer, dwSize + 1);

                if (!WinHttpReadData(hRequest, (LPVOID)pszOutBuffer,
                    dwSize, &dwDownloaded))
                    printf("Error %u in WinHttpReadData.\n", GetLastError());
                else
                    printf("%s", pszOutBuffer); //Encrypted or compressed, think SSL encryption.

                // Free the memory allocated to the buffer.
                delete[] pszOutBuffer;
            }
        } while (dwSize > 0);
    }

    // Report any errors.
    if (!bResults)
        printf("Error %d has occurred.\n", GetLastError());

    // Close any open handles.
    if (hRequest) WinHttpCloseHandle(hRequest);
    if (hConnect) WinHttpCloseHandle(hConnect);
    if (hSession) WinHttpCloseHandle(hSession);

    //std::cout << "Hello World!\n";
}

Output here: https://pastebin.com/cSkEugDT

I read the documentation but don't find anything about decryption of content in WinHttpReadData, obviously this happens only with https, when i test http it's return plain/text.

I suspect about some parameter to before calls to WinHttpReadData.

Body:
Finally i get the mistake, this was on header Accept-Encoding

WinHttpAddRequestHeaders(hRequest,
        L"Accept-Encoding: gzip, deflate, br",
        -1L,
        WINHTTP_ADDREQ_FLAG_ADD);

I commented and fix the issue. GZIP is a compression algorithm whos made this compressed text (deflate and br another algorithms with same purpose).

About Accept-Encoding header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-Encoding