问:
Flutter/Dart won't display FutureBuilder snapshot when resolved
I'm attempting to set a field value from SharedPreferences like so:

```<code>FutureBuilder<String>(
              future: _getUsername(),
              initialData: 'Bruh',
              builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
                print(snapshot);
                print(snapshot.data);
                print(snapshot.hasData);
                return snapshot.hasData ? TextFormField(initialValue: snapshot.data, onChanged: _setUsername) : TextFormField();
              }
            ),
</code>```

This is the _getUsername() future I'm using:

```<code>Future<String> _getUsername() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString('username') ?? 'hmm';
return "Fine";
}
</code>```

And this is the console output:

```<code>Reloaded 0 of 567 libraries in 352ms.
I/flutter (28961): AsyncSnapshot<String>(ConnectionState.done, tesy, null)
I/flutter (28961): tesy
I/flutter (28961): true
</code>```

As you can see, L2 of the output shows 'tesy', which is the value in SharedPreferences, but I only ever see 'Bruh' in the text field (the initial value).

In all the examples I can find, 'Bruh' would be displayed (extremely) briefly (if at all) before 'tesy' is then displayed in the input box. Where am I going wrong?

答:
I guess the problem is in TextFormField itself. When the component is being rebuilt, changed initialValue is not taken into account. If you want to have a "dynamic" initial value, it's better to provide an explicit controller. Something like this:

class TestApp extends StatefulWidget {
  @override
  _TestAppState createState() => _TestAppState();
}

class _TestAppState extends State<TestApp> {
  final TextEditingController _controller = TextEditingController();

  @override
  void initState() {
    super.initState();
    _controller.text = 'Initial';
    _initUsername();
  }

  Future<void> _initUsername() async {
    final username = await _getUsername();
    _controller.value = _controller.value.copyWith(text: username);
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: TextFormField(controller: _controller, onChanged: (_) {}),
      ),
    );
  }

  Future<String> _getUsername() async {
    await Future.delayed(Duration(seconds: 1));
    return 'Loaded';
  }
}
```

Body:
I'm attempting to set a field value from SharedPreferences like so:

FutureBuilder<String>(
              future: _getUsername(),
              initialData: 'Bruh',
              builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
                print(snapshot);
                print(snapshot.data);
                print(snapshot.hasData);
                return snapshot.hasData ? TextFormField(initialValue: snapshot.data, onChanged: _setUsername) : TextFormField();
              }
            ),

This is the _getUsername() future I'm using:

Future<String> _getUsername() async {
SharedPreferences prefs = await SharedPreferences.getInstance();
return prefs.getString('username') ?? 'hmm';
return "Fine";
}

And this is the console output:

Reloaded 0 of 567 libraries in 352ms.
I/flutter (28961): AsyncSnapshot<String>(ConnectionState.done, tesy, null)
I/flutter (28961): tesy
I/flutter (28961): true

As you can see, L2 of the output shows 'tesy', which is the value in SharedPreferences, but I only ever see 'Bruh' in the text field (the initial value).

In all the examples I can find, 'Bruh' would be displayed (extremely) briefly (if at all) before 'tesy' is then displayed in the input box. Where am I going wrong?


来源: stackexchange

问:
perl two consecutive back ticked shell command do not run
I am trying to write perl script for managing amazon ec2 instances. In part of my code, I have two shell commands, and when I invoke them, the first runs but not the second. I cannot seem to find a good explanation for this. Here is the code:

```<code>$run_instances = 'ec2-run-instances ami-8e1fece7 -k mykey -t t1.micro';
$outp = `$run_instances`;
$outp =~ /INSTANCE\s+(i-\w+)\s/;
$instance_id = $1;
$describe_instances = "ec2-describe-instances $instance_id";
$outp = `$describe_instances`;
$outp =~ /(ec2-(\d+-\d+-\d+-\d+).\S+)/;
</code>```

The problem is $outp here has the output of $run_instances. For some time I could not understand why I was getting the wrong output; then I realised that $describe_instances command does not run.

I looked at the value of $describe_instances, called that from the Linux shell, and it worked fine. I called it from another Perl script, and it worked fine.

Then I gave $outp the output that is captured when $run_instances runs ($outp = "INSTANCE ......"). It worked, so I got the idea that somehow when these two commands run consecutively the second does not run.

One more thing to note is that when I put above code in a loop every time $run_instances works but $describe_instances does not.

I would be really happy if you could provide some light on this :)

Thank you

答:
Is $outp defined or undefined after the:

```<code>$outp = `$describe_instances`;
</code>```

Have you verified that $instance_id is set to what you expect?
What are the values of $! and $? after the non-working backtick command?
Is anything being written to stderr by the non-working command?

ContentLicense: CC BY-SA 3.0

Body:
I am trying to write perl script for managing amazon ec2 instances. In part of my code, I have two shell commands, and when I invoke them, the first runs but not the second. I cannot seem to find a good explanation for this. Here is the code:

$run_instances = 'ec2-run-instances ami-8e1fece7 -k mykey -t t1.micro';
$outp = `$run_instances`;
$outp =~ /INSTANCE\s+(i-\w+)\s/;
$instance_id = $1;
$describe_instances = "ec2-describe-instances $instance_id";
$outp = `$describe_instances`;
$outp =~ /(ec2-(\d+-\d+-\d+-\d+).\S+)/;

The problem is $outp here has the output of $run_instances. For some time I could not understand why I was getting the wrong output; then I realised that $describe_instances command does not run.

I looked at the value of $describe_instances, called that from the Linux shell, and it worked fine. I called it from another Perl script, and it worked fine.

Then I gave $outp the output that is captured when $run_instances runs ($outp = "INSTANCE ......"). It worked, so I got the idea that somehow when these two commands run consecutively the second does not run.

One more thing to note is that when I put above code in a loop every time $run_instances works but $describe_instances does not.

I would be really happy if you could provide some light on this :)

Thank you

Body:
Is $outp defined or undefined after the:

$outp = `$describe_instances`;

Have you verified that $instance_id is set to what you expect?
What are the values of $! and $? after the non-working backtick command?
Is anything being written to stderr by the non-working command?


问:
Run Python program as service on Ubuntu 16.04 inside a virtual environment
I'm trying to get a Flask + SocketIO app running as a service on Ubuntu 16.04, inside a virtual environment. My server is restarted every day at 3 am (outside of my control), so I need it to automatically launch on startup.

Running the script by itself works fine:

```<code>$ python main.py
(29539) wsgi starting up on http://127.0.0.1:8081
</code>```

I can tell that it's working because it's serving pages (through an nginx server set up by following this Stack Overflow answer, though I don't think that's relevant.)

Here's my /etc/systemd/system/opendc.service:

```<code>[Unit]
Description=OpenDC flask + socketio service

[Service]
Environment=PYTHON_HOME=/var/www/opendc.ewi.tudelft.nl/web-server/venv
Environment=PATH=$VIRTUAL_ENV/bin:$PATH
ExecStart=/var/www/opendc.ewi.tudelft.nl/web-server main.py
Restart=always

[Install]
WantedBy=multi-user.target
</code>```

So when I try to get that going using:

```<code>$ sudo systemctl daemon-reload
$ sudo systemctl restart opendc
</code>```

It doesn't serve pages anymore. The status shows:

```<code>$ sudo systemctl status opendc
* opendc.service - OpenDC flask + socketio service
   Loaded: loaded (/etc/systemd/system/opendc.service; enabled; vendor preset: enabled)
   Active: inactive (dead) (Result: exit-code) since Fri 2016-08-19 10:48:31 CEST; 15min ago
  Process: 29533 ExecStart=/var/www/opendc.ewi.tudelft.nl/web-server main.py (code=exited, status=203/EXEC)
 Main PID: 29533 (code=exited, status=203/EXEC)

Aug 19 10:48:31 opendc.ewi.tudelft.nl systemd[1]: opendc.service: Service hold-off time over, scheduling restart.
Aug 19 10:48:31 opendc.ewi.tudelft.nl systemd[1]: Stopped OpenDC flask + socketio service.
Aug 19 10:48:31 opendc.ewi.tudelft.nl systemd[1]: opendc.service: Start request repeated too quickly.
Aug 19 10:48:31 opendc.ewi.tudelft.nl systemd[1]: Failed to start OpenDC flask + socketio service.
</code>```

I've looked up (code=exited, status=203/EXEC) and done some troubleshooting with what I found:

I checked that main.py is executable:

```<code>$ ls -l main.py
-rwxr-xr-x 1 leon leon 2007 Aug 19 10:46 main.py
</code>```

And that main.py has this first line to point to Python in the virtual environment:

```<code>#!/var/www/opendc.ewi.tudelft.nl/web-server/venv/bin/python
</code>```

So what's the problem here?

答:
Tried and tested way of making a python file run in a Virtual Environment as a service.

```<code>[Unit][Unit]
Description=Your own description
After=network.target

[Service]
Type=simple
Restart=always
WorkingDirectory=/home/path/to/WorkingDirectory/
VIRTUAL_ENV=/home/path/to/WorkingDirectory/venv
Environment=PATH=$VIRTUAL_ENV/bin:$PATH
ExecStart=/home/path/to/WorkingDirectory/venv/bin/python app.py
Restart=on-failure

[Install]
WantedBy=multi-user.target
</code>```

I am putting this one here so I can always come back to it

Body:
I'm trying to get a Flask + SocketIO app running as a service on Ubuntu 16.04, inside a virtual environment. My server is restarted every day at 3 am (outside of my control), so I need it to automatically launch on startup.

Running the script by itself works fine:

$ python main.py
(29539) wsgi starting up on http://127.0.0.1:8081

I can tell that it's working because it's serving pages (through an nginx server set up by following this Stack Overflow answer, though I don't think that's relevant.)

Here's my /etc/systemd/system/opendc.service:

[Unit]
Description=OpenDC flask + socketio service

[Service]
Environment=PYTHON_HOME=/var/www/opendc.ewi.tudelft.nl/web-server/venv
Environment=PATH=$VIRTUAL_ENV/bin:$PATH
ExecStart=/var/www/opendc.ewi.tudelft.nl/web-server main.py
Restart=always

[Install]
WantedBy=multi-user.target

So when I try to get that going using:

$ sudo systemctl daemon-reload
$ sudo systemctl restart opendc

It doesn't serve pages anymore. The status shows:

$ sudo systemctl status opendc
* opendc.service - OpenDC flask + socketio service
   Loaded: loaded (/etc/systemd/system/opendc.service; enabled; vendor preset: enabled)
   Active: inactive (dead) (Result: exit-code) since Fri 2016-08-19 10:48:31 CEST; 15min ago
  Process: 29533 ExecStart=/var/www/opendc.ewi.tudelft.nl/web-server main.py (code=exited, status=203/EXEC)
 Main PID: 29533 (code=exited, status=203/EXEC)

Aug 19 10:48:31 opendc.ewi.tudelft.nl systemd[1]: opendc.service: Service hold-off time over, scheduling restart.
Aug 19 10:48:31 opendc.ewi.tudelft.nl systemd[1]: Stopped OpenDC flask + socketio service.
Aug 19 10:48:31 opendc.ewi.tudelft.nl systemd[1]: opendc.service: Start request repeated too quickly.
Aug 19 10:48:31 opendc.ewi.tudelft.nl systemd[1]: Failed to start OpenDC flask + socketio service.

I've looked up (code=exited, status=203/EXEC) and done some troubleshooting with what I found:

I checked that main.py is executable:

$ ls -l main.py
-rwxr-xr-x 1 leon leon 2007 Aug 19 10:46 main.py

And that main.py has this first line to point to Python in the virtual environment:

#!/var/www/opendc.ewi.tudelft.nl/web-server/venv/bin/python

So what's the problem here?

Body:
Tried and tested way of making a python file run in a Virtual Environment as a service.

[Unit][Unit]
Description=Your own description
After=network.target

[Service]
Type=simple
Restart=always
WorkingDirectory=/home/path/to/WorkingDirectory/
VIRTUAL_ENV=/home/path/to/WorkingDirectory/venv
Environment=PATH=$VIRTUAL_ENV/bin:$PATH
ExecStart=/home/path/to/WorkingDirectory/venv/bin/python app.py
Restart=on-failure

[Install]
WantedBy=multi-user.target

I am putting this one here so I can always come back to it

ContentLicense: CC BY-SA 4.0


问:
COMException: The object invoked has disconnected from its clients
I have a program written in C# that creates a Word doc by collating a bunch of text (extracted from objects). This application has worked fine for the past 4 years on many different machines, but right now it is breaking for one new client with the following error:

System.Runtime.InteropServices.COMException (0x80010108): The object
  invoked has disconnected from its clients. (Exception from HRESULT:
  0x80010108 (RPC_E_DISCONNECTED))    at
  Microsoft.Office.Interop.Word.DocumentClass.get_Content()    at
  MyCompany.MyApp.Main.btnPrint_Click(Object sender, EventArgs e)
  at System.Windows.Forms.Control.OnClick(EventArgs e)    at
  System.Windows.Forms.Button.OnClick(EventArgs e)    at
  System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)    at
  System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons
  button, Int32 clicks)    at
  System.Windows.Forms.Control.WndProc(Message& m)    at
  System.Windows.Forms.ButtonBase.WndProc(Message& m)    at
  System.Windows.Forms.Button.WndProc(Message& m)    at
  System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
  at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&
  m)    at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32
  msg, IntPtr wparam, IntPtr lparam)

Here's the code snippet (it won't compile as-is because this is just an excerpt, but it should make sense):

```<code>// This will be the collated doc
object missing = System.Type.Missing;
Document combinedDoc = null;

// Temp doc holders
string tempWordFilePath;
object tempWordFilePathObj;

// Loop thru records and add their content to Word doc
foreach (RecordWrapper rec in records)
{
    // Decode base64 attachment to byte-array
    byte[] b = decodeToBase64(rec.body);

    if (combinedDoc == null) combinedDoc = app.Documents.Add(ref missing, ref missing, ref missing, ref missing);

    tempWordFilePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + (string)o.Item("Name").Value;
    tempWordFilePathObj = tempWordFilePath;

    if (File.Exists(tempWordFilePath))
    {
        File.Delete(tempWordFilePath);
    }

    // Write bytes into a temp Word doc
    FileStream fs = new FileStream(tempWordFilePath, FileMode.CreateNew);
    fs.Write(b, 0, b.Length);
    fs.Close();

    // Load the temp file as a Document
    Document doc = app.Documents.Open(ref tempWordFilePathObj, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

    // Insert page break
    object collStart = combinedDoc.Content.Start;
    object collEnd = combinedDoc.Content.End;
    Range rng2 = combinedDoc.Range(ref collStart, ref collEnd);
    object collapseEnd = Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseEnd;
    rng2.Collapse(ref collapseEnd);

    // Paste range into resulting doc
    rng2.InsertFile(tempWordFilePath, ref missing, ref missing, ref missing, ref missing);

    object pageBrk = Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak;
    rng2.InsertBreak(ref pageBrk);

    doc.Close(ref missing, ref missing, ref missing);
    File.Delete(tempWordFilePath);
}
</code>```

I have read on an MSDN forum that this may be due to a missing library called SHDocVw.dll. I have repackaged my application with said library included but it's the same result. Others have said that it may be a Service Pack issue, but there haven't been any recommended solutions. Another person has recommended to ignore "80010108" errors but the idea was quickly dismissed by the OP. I have also read on here that this could be due to incorrect instantiation/referencing of certain Interop classes, but I don't see that happening in my code (or am I not seeing it?)

答:
I had the same issue on a Windows 2008 server with Microsoft Office 2013.

Try to repair your Microsoft Office installation.

On control panel choose the repair option and reset your PC.

It worked for me!

Body:
I have a program written in C# that creates a Word doc by collating a bunch of text (extracted from objects). This application has worked fine for the past 4 years on many different machines, but right now it is breaking for one new client with the following error:

System.Runtime.InteropServices.COMException (0x80010108): The object
  invoked has disconnected from its clients. (Exception from HRESULT:
  0x80010108 (RPC_E_DISCONNECTED))    at
  Microsoft.Office.Interop.Word.DocumentClass.get_Content()    at
  MyCompany.MyApp.Main.btnPrint_Click(Object sender, EventArgs e)
  at System.Windows.Forms.Control.OnClick(EventArgs e)    at
  System.Windows.Forms.Button.OnClick(EventArgs e)    at
  System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)    at
  System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons
  button, Int32 clicks)    at
  System.Windows.Forms.Control.WndProc(Message& m)    at
  System.Windows.Forms.ButtonBase.WndProc(Message& m)    at
  System.Windows.Forms.Button.WndProc(Message& m)    at
  System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
  at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message&
  m)    at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32
  msg, IntPtr wparam, IntPtr lparam)

Here's the code snippet (it won't compile as-is because this is just an excerpt, but it should make sense):

// This will be the collated doc
object missing = System.Type.Missing;
Document combinedDoc = null;

// Temp doc holders
string tempWordFilePath;
object tempWordFilePathObj;

// Loop thru records and add their content to Word doc
foreach (RecordWrapper rec in records)
{
    // Decode base64 attachment to byte-array
    byte[] b = decodeToBase64(rec.body);

    if (combinedDoc == null) combinedDoc = app.Documents.Add(ref missing, ref missing, ref missing, ref missing);

    tempWordFilePath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + "\\" + (string)o.Item("Name").Value;
    tempWordFilePathObj = tempWordFilePath;

    if (File.Exists(tempWordFilePath))
    {
        File.Delete(tempWordFilePath);
    }

    // Write bytes into a temp Word doc
    FileStream fs = new FileStream(tempWordFilePath, FileMode.CreateNew);
    fs.Write(b, 0, b.Length);
    fs.Close();

    // Load the temp file as a Document
    Document doc = app.Documents.Open(ref tempWordFilePathObj, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);

    // Insert page break
    object collStart = combinedDoc.Content.Start;
    object collEnd = combinedDoc.Content.End;
    Range rng2 = combinedDoc.Range(ref collStart, ref collEnd);
    object collapseEnd = Microsoft.Office.Interop.Word.WdCollapseDirection.wdCollapseEnd;
    rng2.Collapse(ref collapseEnd);

    // Paste range into resulting doc
    rng2.InsertFile(tempWordFilePath, ref missing, ref missing, ref missing, ref missing);

    object pageBrk = Microsoft.Office.Interop.Word.WdBreakType.wdPageBreak;
    rng2.InsertBreak(ref pageBrk);

    doc.Close(ref missing, ref missing, ref missing);
    File.Delete(tempWordFilePath);
}

I have read on an MSDN forum that this may be due to a missing library called SHDocVw.dll. I have repackaged my application with said library included but it's the same result. Others have said that it may be a Service Pack issue, but there haven't been any recommended solutions. Another person has recommended to ignore "80010108" errors but the idea was quickly dismissed by the OP. I have also read on here that this could be due to incorrect instantiation/referencing of certain Interop classes, but I don't see that happening in my code (or am I not seeing it?)


问:
How do I copy a string to the clipboard?
I'm trying to make a basic Windows application that builds a string out of user input and then adds it to the clipboard. How do I copy a string to the clipboard using Python?</p>

答:
Not all of the answers worked for my various python configurations so this solution only uses the subprocess module. However, copy_keyword has to be pbcopy for Mac or clip for Windows:

```<code>import subprocess
subprocess.run('copy_keyword', universal_newlines=True, input='New Clipboard Value ')
</code>```

Here's some more extensive code that automatically checks what the current operating system is:

```<code>import platform
import subprocess

copy_string = 'New Clipboard Value '

# Check which operating system is running to get the correct copying keyword.
if platform.system() == 'Darwin':
    copy_keyword = 'pbcopy'
elif platform.system() == 'Windows':
    copy_keyword = 'clip'

subprocess.run(copy_keyword, universal_newlines=True, input=copy_string)
</code>```

LastEditorDisplayName: Rich B

Body:
Not all of the answers worked for my various python configurations so this solution only uses the subprocess module. However, copy_keyword has to be pbcopy for Mac or clip for Windows:

import subprocess
subprocess.run('copy_keyword', universal_newlines=True, input='New Clipboard Value ')

Here's some more extensive code that automatically checks what the current operating system is:

import platform
import subprocess

copy_string = 'New Clipboard Value '

# Check which operating system is running to get the correct copying keyword.
if platform.system() == 'Darwin':
    copy_keyword = 'pbcopy'
elif platform.system() == 'Windows':
    copy_keyword = 'clip'

subprocess.run(copy_keyword, universal_newlines=True, input=copy_string)


问:
Get git commit list between tags from remote
If there any way I can retrieve all commits between tags from remote master? So far what I did is checkout to master branch and update the repo then fire the following command.</p>

```<code>git checkout master
git pull
git log tag1..tag2 --pretty=format:'* %h %an: %s (%cr)' -- .
</code>```

答:
You can specify the branch for git log

```<code>git fetch
git log origin/master tag1..tag2
</code>```

Body:
If there any way I can retrieve all commits between tags from remote master? So far what I did is checkout to master branch and update the repo then fire the following command.

git checkout master
git pull
git log tag1..tag2 --pretty=format:'* %h %an: %s (%cr)' -- .

Body:
You can specify the branch for git log

git fetch
git log origin/master tag1..tag2


问:
Python dbf Module, write fine, but not appear on VFP until pack() table
I use a dbf python module by Ethan to write records in a Visual Fox Pro dbf Table. I did this to append:

```<code>import dbf
Db = dbf.Table ('table.dbf')
Db.open (mode=dbf.READ_WRITE)
record = { 'NUMERO' : 1, 'TIPO' : 'TA' } # It's a simplified record, real record it's so long.
Db.append( record )
Db.close()
</code>```

The record is added to the dbf file, I can see on VFP Table, using VFP command window, but not appear in the VFP program. At first, I've supposed something happened inside VFP flow, but when I make a manual PACK with DBF Manager, the records appear correctly inside VFP Program, the record not appear in DBF Manager before do a PACK in the table neither.

I try to do

```<code>import dbf
Db = dbf.Table ('table.dbf')
Db.open (mode=dbf.READ_WRITE)
record = { 'NUMERO' : 1, 'TIPO' : 'TA' } # It's a simplified record, real record it's so long.
Db.append( record )
Db.pack() # Pack before close.
Db.close()
</code>```

But it's not working. Does somebody know what's happening?

答: The VFP program is probably using an index, and the Python dbf module doesn't support index files.  I suspect that a REINDEX command would also show the new record.

Body:
I use a dbf python module by Ethan to write records in a Visual Fox Pro dbf Table. I did this to append:

import dbf
Db = dbf.Table ('table.dbf')
Db.open (mode=dbf.READ_WRITE)
record = { 'NUMERO' : 1, 'TIPO' : 'TA' } # It's a simplified record, real record it's so long.
Db.append( record )
Db.close()

The record is added to the dbf file, I can see on VFP Table, using VFP command window, but not appear in the VFP program. At first, I've supposed something happened inside VFP flow, but when I make a manual PACK with DBF Manager, the records appear correctly inside VFP Program, the record not appear in DBF Manager before do a PACK in the table neither.

I try to do

import dbf
Db = dbf.Table ('table.dbf')
Db.open (mode=dbf.READ_WRITE)
record = { 'NUMERO' : 1, 'TIPO' : 'TA' } # It's a simplified record, real record it's so long.
Db.append( record )
Db.pack() # Pack before close.
Db.close()

But it's not working. Does somebody know what's happening?


问:
How to find the correct URL when you made some choices on the web page?
I'm very new to learn about web scraping. By using xpath selector i am trying to get the knowledge on that webpage : https://seffaflik.epias.com.tr/transparency/uretim/planlama/kgup.xhtml

But the point is, whenever you change the date or the powerplant name, URL does not change therefore when you fetch the response, you are getting always the same and wrong answer. Is there a way to find the correct URL or anything else related to HTML Markup etc ?

答:
For a scraping operation like this, you'll need to do a bit more than just load the document and then grab the content. The document in-question relies on JavaScript to load new information from some other resource after the user has defined a particular set of parameters and updated the form.

After loading the document, you'll need to define your search parameters. You can do this via JavaScript injection or via your browser's console. For example, if you were trying to define the value for the first date field, you could use

```<code>document.querySelectorAll('#j_idt199 input')[1].value = "Some/New/Date";
</code>```

Repeat this process for the other fields you wish to define in your search, and then run the following code to programmatically execute your search:

```<code>document.querySelector('#j_idt199 button').click();
</code>```

After that, you can either grab the information you want using plain JS query selectors, or you can implement a scraping library like artoo.js to help you interpret the data and export it.

Body:
For a scraping operation like this, you'll need to do a bit more than just load the document and then grab the content. The document in-question relies on JavaScript to load new information from some other resource after the user has defined a particular set of parameters and updated the form.

After loading the document, you'll need to define your search parameters. You can do this via JavaScript injection or via your browser's console. For example, if you were trying to define the value for the first date field, you could use

document.querySelectorAll('#j_idt199 input')[1].value = "Some/New/Date";

Repeat this process for the other fields you wish to define in your search, and then run the following code to programmatically execute your search:

document.querySelector('#j_idt199 button').click();

After that, you can either grab the information you want using plain JS query selectors, or you can implement a scraping library like artoo.js to help you interpret the data and export it.


问:
Microsoft Graph - Get latest message content only
I have a Logic App that watches a mail box and creates service tickets based on the content of those emails. They can create tickets this way or reply to them to update the ticket. The issue is with the reply. As I'm sure you know, in an email chain, the latest message has a copy of all the previous messages in the chain. Adding all this content on the comment of a ticket results in a bunch of duplication/visual clutter. So the question:

Is there a way to get only the most recent reply's text/content from a message? I was digging around the Microsoft Graph API but haven't had much luck identifying how to get this. In lieu of being able to do it via api I was going to just look for copied text in the message html and ignore it, but that seems like the way we'd do it if it was 1990.

Anyway, any help in this regard is much appreciated. Ideally it'd be done with Microsoft Graph because we're a mostly Microsoft stack here but any method is valid.

Thanks,

~Josh

答:
Turns out we ended up doing it with Microsoft Graph as expected. You have to jump through a few hoops (registering your application in Azure, getting a bearer token and such) but the end result is you can call:

https://graph.microsoft.com/v1.0/users/{userId}/messages/{messageId}?$select=uniqueBody

This will return your message's unique body.

To save you some time the request for the bearer token looks like this (you can use anything for the form-data boundary):

And then you add the token to the uniqueBody Request like this:

Please consult the Microsoft documentation for how to get these fields for your application: https://learn.microsoft.com/en-us/graph/auth-v2-user


问:
How to reconstruct a file from base64 encoding?
I'm trying to encode a file with base64, then send the encoded data and reconstruct the file on the other end. For example, I want to open a .png file located on my desktop, encode it, then decode it and save a new .png in a different directory.

I was referred to use the following article, but I receive an error as you can see below: https://www.programcreek.com/2013/09/convert-image-to-string-in-python/

```<code>import base64

with open('path_to_file', 'rb') as imageFile:
    x = base64.b64encode(imageFile.read())

fh = open('imageToSave.png', 'wb')
fh.write(x.decode('base64'))
fh.close()

File "directory", line 7, in <module>
    fh.write(x.decode('base64'))
LookupError: 'base64' is not a text encoding; use codecs.decode() to handle arbitrary codecs
</code>```

I tried looking for similar problems on stackoverflow, but I did not understand other solutions and was unable to implement them in my case. If there is a better way of accomplishing this task, please let me know.

答:
Why do you use decode, instead of base64.b64decode()?

Because that works fine:

```<code>>>> base64.b64encode(b"foo")
b'Zm9v'
>>> base64.b64decode('Zm9v')
b'foo'
</code>```

Or, in your case:

```<code>import base64

with open('path_to_file', 'rb') as imageFile:
    x = base64.b64encode(imageFile.read())

fh = open('imageToSave.png', 'wb')
fh.write(base64.b64decode(x))
fh.close()
</code>```

There is a difference between Python 2 and 3 here though. str.decode('base64') seems to work in Python 2, but not in 3.

Body:
I'm trying to encode a file with base64, then send the encoded data and reconstruct the file on the other end. For example, I want to open a .png file located on my desktop, encode it, then decode it and save a new .png in a different directory.

I was referred to use the following article, but I receive an error as you can see below: https://www.programcreek.com/2013/09/convert-image-to-string-in-python/

import base64

with open('path_to_file', 'rb') as imageFile:
    x = base64.b64encode(imageFile.read())

fh = open('imageToSave.png', 'wb')
fh.write(x.decode('base64'))
fh.close()

File "directory", line 7, in <module>
    fh.write(x.decode('base64'))
LookupError: 'base64' is not a text encoding; use codecs.decode() to handle arbitrary codecs

I tried looking for similar problems on stackoverflow, but I did not understand other solutions and was unable to implement them in my case. If there is a better way of accomplishing this task, please let me know.

Body:
Why do you use decode, instead of base64.b64decode()?

Because that works fine:

>>> base64.b64encode(b"foo")
b'Zm9v'
>>> base64.b64decode('Zm9v')
b'foo'

Or, in your case:

import base64

with open('path_to_file', 'rb') as imageFile:
    x = base64.b64encode(imageFile.read())

fh = open('imageToSave.png', 'wb')
fh.write(base64.b64decode(x))
fh.close()

There is a difference between Python 2 and 3 here though. str.decode('base64') seems to work in Python 2, but not in 3.


问:
Deduplication of records without sorting in a mainframe sequential dataset with already sorted data
This is a query on deduplicating an already sorted mainframe dataset without re-sorting it.

The input sequential dataset has the following structure. 'KEYn' in the first 4 bytes represents the key and the remainder of each row represents the rest of the record's data. There are records in which the same key is repeated though the remaining data is different in each record. The records are already sorted on 'KEYn'.

KEY1aaaaaa

KEY1bbbbbb

KEY2cccccc

KEY3xxxxxx

KEY3yyyyyy

KEY3zzzzzz

KEY3wwwwww

KEY4uuuuuu

KEY5hhhhhh

KEY5ffffff

My requirement is to pick up the first record of each key and drop the remaining 'duplicates'. so the output file for the above input should look like this:

KEY1aaaaaa

KEY2cccccc

KEY3xxxxxx

KEY4uuuuuu

KEY5hhhhhh

Since the data is already sorted, I don't want to use SORT utility with SUM FIELDS=NONE or ICETOOL with SELECT - FIRST operand since both of these will actually end up re-sorting the data on the deduplication key (KEYn). Also the actual dataset I am referring to is huge (1.6 billion records, AVGRLEN 900 VB) and a job actually ran out of sort work space trying to sort it in one go.

My query is: Is there any option available in JCL based utilities to do this deduplication without resorting and using sort work space? I am trying to avoid writing a COBOL/Assembler program to do this.

答:
Try this untested.</p>

```<code>OPTION COPY
INREC BUILD=(1,4,SEQNUM,3,ZD,RESTART=(5,4),5)
OUTFIL INCLUDE=(5,3,ZD,EQ,1),BUILD=(1,4,8)
</code>```

Body:
Try this untested.

OPTION COPY
INREC BUILD=(1,4,SEQNUM,3,ZD,RESTART=(5,4),5)
OUTFIL INCLUDE=(5,3,ZD,EQ,1),BUILD=(1,4,8)


问:
Concatenate two numpy arrays so that index order keeps the same?
Assume I have two numpy arrays as follows:

```<code>{0: array([ 2, 4, 8, 9, 12], dtype=int64),
1: array([ 1, 3, 5], dtype=int64)}
</code>```

Now I want to replace each array with the ID at the front, i.e. the values in array 0 become 0 and in array 1 become 1, then both arrays should be merged, whereby the index order must be correct.
I.e. desired output:

```<code>array([1, 0, 1, 0, 1, 0, 0 ,0])
</code>```

But that's what I get:

```<code>np.concatenate((h1,h2), axis=0)
array([0, 0, 0, 0, 0, 1, 1, 1])
</code>```

(Each array contains only unique values, if this helps.)

How can this be done?

答:
.concatenate Just appends lists/arrays.

Maybe an unconventional way to go about it, but you could repeat the [0 1] pattern for the len of the shortest array, using numpy.repeat and then add repeated 1 values for the difference of the two arrays?

```<code>if len(h1) > len(h2):
   temp = len(h2)
else:
   temp = len(h1)

diff = abs(h1-h2)

for i in range(temp):
   A = numpy.repeat(0, 1)

for i in range(diff):
   B = numpy.repeat(1)

C = numpy.concatenate((A,B), axis=0)
</code>```

Maybe not the most dynamic or kindest way to go about this but if your solution requires just that, then it could do the job in the meantime.

Body:
Assume I have two numpy arrays as follows:

{0: array([ 2, 4, 8, 9, 12], dtype=int64),
1: array([ 1, 3, 5], dtype=int64)}

Now I want to replace each array with the ID at the front, i.e. the values in array 0 become 0 and in array 1 become 1, then both arrays should be merged, whereby the index order must be correct.
I.e. desired output:

array([1, 0, 1, 0, 1, 0, 0 ,0])

But that's what I get:

np.concatenate((h1,h2), axis=0)
array([0, 0, 0, 0, 0, 1, 1, 1])

(Each array contains only unique values, if this helps.)

How can this be done?

Body:
.concatenate Just appends lists/arrays.

Maybe an unconventional way to go about it, but you could repeat the [0 1] pattern for the len of the shortest array, using numpy.repeat and then add repeated 1 values for the difference of the two arrays?

if len(h1) > len(h2):
   temp = len(h2)
else:
   temp = len(h1)

diff = abs(h1-h2)

for i in range(temp):
   A = numpy.repeat(0, 1)

for i in range(diff):
   B = numpy.repeat(1)

C = numpy.concatenate((A,B), axis=0)

Maybe not the most dynamic or kindest way to go about this but if your solution requires just that, then it could do the job in the meantime.


问:
MySQL: How to copy row from one table to another with skipping empty rows in source table?
Can anyone help me turn this PHP/MySQLesque pseudo-code into a working MySQL-query? Tables A and B have identical columns / column order.

```<code>UPDATE B SET
B.col_1 = A.col_1 IF(A.col_1 != '' AND A.col_1 != 0 AND A.col_1 != NULL),
B.col_2 = A.col_2 IF(A.col_2 != '' AND A.col_2 != 0 AND A.col_2 != NULL),
…
B.col_n = A.col_n IF(A.col_n != '' AND A.col_n != 0 AND A.col_n != NULL)
WHERE A.$uniqueField = B.$uniqueField
</code>```

Any of the n columns (email, firstName, lastName, phone, …) can be $uniqueField (handled by PHP), so I can't use insert-on-duplicate-key.

I found many examples to do it the other way round (i.e. copy rows and skip empty fields in target table), including a promising way via COALESCE, but I could not get this to work.

Any help would be highly appreciated ... thanks in advance!

答:
To start with, the syntax of your update statement is not correct. In MySQL, you need something like UPDATE B JOIN A ON ... SET ....

When it comes to the logic that you want to implement, although quite unclear, I suspect that this can be managed with CASE expressions:

```<code>UPDATE B
JOIN A ON A.$uniqueField = B.$uniqueField
SET
    B.col_1 = CASE
        WHEN A.col_1 <> '' AND A.col_1 <> '0'
        THEN A.col_1
        ELSE B.col_1
    END,
    B.col_2 = CASE
        WHEN A.col_2 <> '' AND A.col_2 <> '0'
        THEN A.col_2
        ELSE B.col_2
    END,
    ...
    B.col_N = CASE
        WHEN A.col_N <> '' AND A.col_N <> '0'
        THEN A.col_N
        ELSE B.col_N
    END
</code>```

For each column in the SET clause, the query updates it to the corresponding value in A (if such a record exists), if the value in A is not empty, not null and not 0. I assumed that all columns are of string datatype (hence '0' instead of 0 in your pseudo-code), since you do check that values are not empty strings.

Note: as commnented by spencer7503, the nulllity check is redondant: values that satisfy any of the two inequality conditions are guaranteed to be not null.

Body:
Can anyone help me turn this PHP/MySQLesque pseudo-code into a working MySQL-query? Tables A and B have identical columns / column order.

UPDATE B SET
B.col_1 = A.col_1 IF(A.col_1 != '' AND A.col_1 != 0 AND A.col_1 != NULL),
B.col_2 = A.col_2 IF(A.col_2 != '' AND A.col_2 != 0 AND A.col_2 != NULL),
…
B.col_n = A.col_n IF(A.col_n != '' AND A.col_n != 0 AND A.col_n != NULL)
WHERE A.$uniqueField = B.$uniqueField

Any of the n columns (email, firstName, lastName, phone, …) can be $uniqueField (handled by PHP), so I can't use insert-on-duplicate-key.

I found many examples to do it the other way round (i.e. copy rows and skip empty fields in target table), including a promising way via COALESCE, but I could not get this to work.

Any help would be highly appreciated ... thanks in advance!

Body:
To start with, the syntax of your update statement is not correct. In MySQL, you need something like UPDATE B JOIN A ON ... SET ....

When it comes to the logic that you want to implement, although quite unclear, I suspect that this can be managed with CASE expressions:

UPDATE B
JOIN A ON A.$uniqueField = B.$uniqueField
SET
    B.col_1 = CASE
        WHEN A.col_1 <> '' AND A.col_1 <> '0'
        THEN A.col_1
        ELSE B.col_1
    END,
    B.col_2 = CASE
        WHEN A.col_2 <> '' AND A.col_2 <> '0'
        THEN A.col_2
        ELSE B.col_2
    END,
    ...
    B.col_N = CASE
        WHEN A.col_N <> '' AND A.col_N <> '0'
        THEN A.col_N
        ELSE B.col_N
    END

For each column in the SET clause, the query updates it to the corresponding value in A (if such a record exists), if the value in A is not empty, not null and not 0. I assumed that all columns are of string datatype (hence '0' instead of 0 in your pseudo-code), since you do check that values are not empty strings.

Note: as commnented by spencer7503, the nulllity check is redondant: values that satisfy any of the two inequality conditions are guaranteed to be not null.


问:
tidyverse - delete a column within a nested column/list
I have the following data:

(Note: I'm using the current github version of dplyr within tidyverse which offerse some new experimental functions, like condense - which I'm using below, but I think that's not relevant for my problem/question).

```<code>library(tidyverse)
library(corrr)

dat <- data.frame(grp = rep(1:4, each = 25),
                  Q1 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q2 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q3 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q4 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q5 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q6 = sample(c(1:5, NA), 100, replace = TRUE))
</code>```

I now want to calculate the correlation between Q1 to Q6 within each group, and I'm using:

```<code>cor_dat <- dat %>%
  group_by(grp) %>%
  condense(cor = correlate(cur_data()))
</code>```

Which gives me the correlations as a list-column (?). Within each list, the first column is called rowname and I want to simply delete this column from each list in a tidyverse way. How can I do this?

I already tried something naive like select (-rowname), but this doesn't work.

答:
Oh my, it was as simple as:

```<code>cor_dat <- dat %>%
  group_by(grp) %>%
  condense(cor = correlate(cur_data())) %>%
  mutate(cor = list(cor[,-1]))
</code>```

Got there by trial & error. Although this only works with column positions, not names.

Body:
I have the following data:

(Note: I'm using the current github version of dplyr within tidyverse which offerse some new experimental functions, like condense - which I'm using below, but I think that's not relevant for my problem/question).

library(tidyverse)
library(corrr)

dat <- data.frame(grp = rep(1:4, each = 25),
                  Q1 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q2 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q3 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q4 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q5 = sample(c(1:5, NA), 100, replace = TRUE),
                  Q6 = sample(c(1:5, NA), 100, replace = TRUE))

I now want to calculate the correlation between Q1 to Q6 within each group, and I'm using:

cor_dat <- dat %>%
  group_by(grp) %>%
  condense(cor = correlate(cur_data()))

Which gives me the correlations as a list-column (?). Within each list, the first column is called rowname and I want to simply delete this column from each list in a tidyverse way. How can I do this?

I already tried something naive like select (-rowname), but this doesn't work.

Body:
Oh my, it was as simple as:

cor_dat <- dat %>%
  group_by(grp) %>%
  condense(cor = correlate(cur_data())) %>%
  mutate(cor = list(cor[,-1]))

Got there by trial & error. Although this only works with column positions, not names.


问:
How to suppress pip upgrade warning?
My pip version was off -- every pip command was saying:

```<code>You are using pip version 6.0.8, however version 8.1.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
</code>```

And I didn't like the answers given here: How can I get rid of this warning to upgrade from pip? because they all want to get pip out of sync with the RH version.

So I tried a clean system install with this VagrantFile:

```<code>Vagrant.configure("2") do |config|

  config.ssh.username   = 'root'
  config.ssh.password   = 'vagrant'
  config.ssh.insert_key = 'true'

  config.vm.box = "bento/centos-7.3"

  config.vm.provider "virtualbox" do |vb|
    vb.cpus   = "4"
    vb.memory = "2048"
  end

  config.vm.synced_folder "..", "/vagrant"

  config.vm.network "public_network", bridge: "eth0", ip: "192.168.1.31"

  config.vm.provision "shell", inline: <<-SHELL
    set -x

    # Install pip
    yum install -y epel-release
    yum install -y python-pip
    pip freeze   # See if pip prints version warning on fresh OS install.

  SHELL

end
</code>```

But then I got:

```<code>==> default: ++ pip freeze
==> default: You are using pip version 8.1.2, however version 9.0.1 is available.
==> default: You should consider upgrading via the 'pip install --upgrade pip' command.
</code>```

So it seems that I'm using the wrong commands to install pip. What are correct commands to use?

答:
Just adding to @sorin's answer

inside Dockerfile add these 2 lines to disable both pip version check and cache.

```<code>FROM python:3.6.10

ARG PIP_DISABLE_PIP_VERSION_CHECK=1
ARG PIP_NO_CACHE_DIR=1

RUN pip3 install -r requirements.txt
# ...
</code>```

Title: How to suppress pip upgrade warning?

Body:
My pip version was off -- every pip command was saying:

You are using pip version 6.0.8, however version 8.1.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

And I didn't like the answers given here: How can I get rid of this warning to upgrade from pip? because they all want to get pip out of sync with the RH version.

So I tried a clean system install with this VagrantFile:

Vagrant.configure("2") do |config|

  config.ssh.username   = 'root'
  config.ssh.password   = 'vagrant'
  config.ssh.insert_key = 'true'

  config.vm.box = "bento/centos-7.3"

  config.vm.provider "virtualbox" do |vb|
    vb.cpus   = "4"
    vb.memory = "2048"
  end

  config.vm.synced_folder "..", "/vagrant"

  config.vm.network "public_network", bridge: "eth0", ip: "192.168.1.31"

  config.vm.provision "shell", inline: <<-SHELL
    set -x

    # Install pip
    yum install -y epel-release
    yum install -y python-pip
    pip freeze   # See if pip prints version warning on fresh OS install.

  SHELL

end

But then I got:

==> default: ++ pip freeze
==> default: You are using pip version 8.1.2, however version 9.0.1 is available.
==> default: You should consider upgrading via the 'pip install --upgrade pip' command.

So it seems that I'm using the wrong commands to install pip. What are correct commands to use?

Body:
Just adding to @sorin's answer

inside Dockerfile add these 2 lines to disable both pip version check and cache.

FROM python:3.6.10

ARG PIP_DISABLE_PIP_VERSION_CHECK=1
ARG PIP_NO_CACHE_DIR=1

RUN pip3 install -r requirements.txt
# ...


问:
Rails server is running, but cannot connect to localhost:3000
I am learning Ruby on Rails with railstutorial.org
I had set everything up and working fine from Chapter 1. However, all of a sudden my next app has an issue.

I run "rails server"

```<code>=> Booting WEBrick
=> Rails 3.2.9 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2012-11-15 00:45:08] INFO  WEBrick 1.3.1
[2012-11-15 00:45:08] INFO  ruby 1.9.3 (2012-11-10) [x86_64-linux]
[2012-11-15 00:45:08] INFO  WEBrick::HTTPServer#start: pid=2752 port=3000
</code>```

Seems to be working fine, just like with my previous app.

However, I try connecting to localhost:3000 , 0.0.0.0:3000 , 127.0.0.1:3000 on various browsers and they all cannot establish a connection to the server.

Some things to note:

-I was able to connect to localhost just a while ago--it just seems like it suddenly stopped working out of the blue.

-My first app was working perfectly fine, but now it doesn't work for my first app either.

-I don't have firewalls blocking the port, and my hosts file is not the problem.

-I am on Ubuntu 12.10

I almost always find solutions via search, but not this time.. so I need some help please. It's very frustrating as I feel like it's a simple problem that I spent way too long being stuck on.

Thank you.

答: for me...I was behind a proxy at work and had to do rails s -b 0.0.0.0 -p 3000

Body:
I am learning Ruby on Rails with railstutorial.org
I had set everything up and working fine from Chapter 1. However, all of a sudden my next app has an issue.

I run "rails server"

=> Booting WEBrick
=> Rails 3.2.9 application starting in development on http://0.0.0.0:3000
=> Call with -d to detach
=> Ctrl-C to shutdown server
[2012-11-15 00:45:08] INFO  WEBrick 1.3.1
[2012-11-15 00:45:08] INFO  ruby 1.9.3 (2012-11-10) [x86_64-linux]
[2012-11-15 00:45:08] INFO  WEBrick::HTTPServer#start: pid=2752 port=3000

Seems to be working fine, just like with my previous app.

However, I try connecting to localhost:3000 , 0.0.0.0:3000 , 127.0.0.1:3000 on various browsers and they all cannot establish a connection to the server.

Some things to note:

-I was able to connect to localhost just a while ago--it just seems like it suddenly stopped working out of the blue.

-My first app was working perfectly fine, but now it doesn't work for my first app either.

-I don't have firewalls blocking the port, and my hosts file is not the problem.

-I am on Ubuntu 12.10

I almost always find solutions via search, but not this time.. so I need some help please. It's very frustrating as I feel like it's a simple problem that I spent way too long being stuck on.

Thank you.


问:
Pass fetch data to components using useState React Native
I am new to React Native. Actually this is my first app.

I have been trying to pass data from Fetch to components, but no luck there. I have researched Google up and down, left and right, tried million things, but still no go.

This is my App.js

```<code>import React, {useState, useEffect} from 'react';
import { View, StyleSheet, ScrollView } from 'react-native';

import Header from './parts/header';
// import BigNews from './parts/big-news';
import Index from './screens/index.js';

const authorization = { authorization: '1234aa' };

export default function App() {
  const [fetchApiData, setApiData] = useState();

  useEffect(() =>
  fetch('https://example.com/get-app-home.php', {
    method: 'POST', // or 'PUT'
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(authorization),
  })
  .then(res => res.json())
  .then(res => {
    this.setState({ setApiData: res })
  })
  .catch(() => this.setState({ hasErrors: true }))
  );
  return (
    <View style={styles.viewport}>
      <Header />
      <ScrollView style={styles.contentHolder}>
        <Index content={fetchApiData}/>
      </ScrollView>
    </View>
);

}
</code>```

And this is my index.js file

```<code>import React from 'react';
import { View, Text } from 'react-native';

import BigNews from '../parts/big-news';
import SmallNews from '../parts/small-news';
import Colors from '../constants/colors'

const Index = props => {

    return (
      <View>
        <BigNews
        image={props.content.first.image}
        pretitle={props.content.first.pretitle}
        title={props.content.first.title}
        introduction={props.content.first.introduction}
        style={{color: props.content.first.mark}}/>

        <SmallNews
        image={props.content.second.image}
        pretitle={props.content.second.pretitle}
        title={props.content.second.title}
        style={{color: props.content.first.mark}}/>

        <SmallNews
        image={props.content.second.image}
        pretitle={props.content.second.pretitle}
        title={props.content.second.title}
        style={{color: props.content.first.mark}}/>

        <SmallNews
        image={props.content.second.image}
        pretitle={props.content.second.pretitle}
        title={props.content.second.title}
        style={{color: props.content.first.mark}}/>
      </View>
    );
}
export default Index;
</code>```

I am constantly getting TypeError: undefined is not an object (evaluating 'props.content.first')

I tried million ways, but most of the times this is the error that I see. If I do console.log of state I get either undefined or empty.

答:
You are not setting your data this.setState is for class components. Replace this.setState with setApiData().

useState returns the initial state and a fucntion to update that value.

```<code>const [ hasError, setHasErrors] = useState(false);

.then(res => res.json())
.then(res => {
  setApiData(res)
})
.catch(() => setHasErrors(true))
);
</code>```

As George pointed out, the initial state is set to empty, doing props.content.first.image will result in an error. Either set the initial value to an object like

```<code>const [ fetchApiData, setApiData ] = useState({
   first: {},
   second: {}
});
</code>```

or validate the values in your component.

```<code>const Index = props => {

  return (
   <View>
    <BigNews
    image={props && props.content && props.content.first && props.content.first.image}
    pretitle={props && props.content && props.content.pretitle && props.content.first.pretitle}
    title={props && props.content && props.content.title && props.content.first.title}
    introduction={props && props.content && props.content.introduction && props.content.first.introduction}
    style={{color: props && props.content && props.content.first && props.content.first.mark}}/>

    ...
  </View>
  );
}
export default Index;
</code>```

Body:
I am new to React Native. Actually this is my first app.

I have been trying to pass data from Fetch to components, but no luck there. I have researched Google up and down, left and right, tried million things, but still no go.

This is my App.js

import React, {useState, useEffect} from 'react';
import { View, StyleSheet, ScrollView } from 'react-native';

import Header from './parts/header';
// import BigNews from './parts/big-news';
import Index from './screens/index.js';

const authorization = { authorization: '1234aa' };

export default function App() {
  const [fetchApiData, setApiData] = useState();

  useEffect(() =>
  fetch('https://example.com/get-app-home.php', {
    method: 'POST', // or 'PUT'
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(authorization),
  })
  .then(res => res.json())
  .then(res => {
    this.setState({ setApiData: res })
  })
  .catch(() => this.setState({ hasErrors: true }))
  );
  return (
    <View style={styles.viewport}>

      <ScrollView style={styles.contentHolder}>
        <Index content={fetchApiData}/>
      </ScrollView>
    </View>
);

}

And this is my index.js file

import React from 'react';
import { View, Text } from 'react-native';

import BigNews from '../parts/big-news';
import SmallNews from '../parts/small-news';
import Colors from '../constants/colors'

const Index = props => {

    return (
      <View>
        <BigNews
        image={props.content.first.image}
        pretitle={props.content.first.pretitle}
        title={props.content.first.title}
        introduction={props.content.first.introduction}
        style={{color: props.content.first.mark}}/>

        <SmallNews
        image={props.content.second.image}
        pretitle={props.content.second.pretitle}
        title={props.content.second.title}
        style={{color: props.content.first.mark}}/>

        <SmallNews
        image={props.content.second.image}
        pretitle={props.content.second.pretitle}
        title={props.content.second.title}
        style={{color: props.content.first.mark}}/>

        <SmallNews
        image={props.content.second.image}
        pretitle={props.content.second.pretitle}
        title={props.content.second.title}
        style={{color: props.content.first.mark}}/>
      </View>
    );
}
export default Index;

I am constantly getting TypeError: undefined is not an object (evaluating 'props.content.first')

I tried million ways, but most of the times this is the error that I see. If I do console.log of state I get either undefined or empty.

Body:
You are not setting your data this.setState is for class components. Replace this.setState with setApiData().

useState returns the initial state and a fucntion to update that value.

const [ hasError, setHasErrors] = useState(false);

.then(res => res.json())
.then(res => {
  setApiData(res)
})
.catch(() => setHasErrors(true))
);

As George pointed out, the initial state is set to empty, doing props.content.first.image will result in an error. Either set the initial value to an object like

const [ fetchApiData, setApiData ] = useState({
   first: {},
   second: {}
});

or validate the values in your component.

const Index = props => {

  return (
   <View>
    <BigNews
    image={props && props.content && props.content.first && props.content.first.image}
    pretitle={props && props.content && props.content.pretitle && props.content.first.pretitle}
    title={props && props.content && props.content.title && props.content.first.title}
    introduction={props && props.content && props.content.introduction && props.content.first.introduction}
    style={{color: props && props.content && props.content.first && props.content.first.mark}}/>

    ...
  </View>
  );
}
export default Index;


问:
In Typescript, how to define a type with exact number of property of unknown names
Let's say I have a variable. It has a name and a value, and I want them both for something, e.g. to log them - the value and a variable name. It can be done like so:

const some_symbol = "qwer"
const some_other_symbol = 100000

const log1 = (name: string, value: any) => console.log(name, value)

log1("some_symbol", some_symbol)
log1("some_other_symbol", some_other_symbol)
log1("some_symbol", some_symbol, "some_other_symbol", some_other_symbol) // compile time error
log1() // compile time error

```

<p>But a much better way would be</p>

<pre class="lang-js prettyprint-override"><code>log2({some_symbol})
log2({some_other_symbol})
</code>```

To do so I can write a function

const log2 = (obj: { [key: string]: any }) => {
    const keys = Object.keys(obj)
    if( keys.length !== 1 ) throw new Error("only one key is expected")
    const key = keys[0]
    console.log(key, obj[key])
}
```

<p>But</p>

<pre class="lang-js prettyprint-override"><code>log2({some_symbol, some_other_symbol}) // compiles. run time error
log2({}) // compiles. run time error
</code>```

I want compilation to fail on lines like log2({v1, v2}) and log2({}).

I would like get rid of dynamic type checks, and enforce a compile time check that obj param has only one key. And in general case - exact number of keys which names are unknown to me.

答:
With sufficient type system juggling you can get the compiler to complain if your object has more than one known key. Something like this might work:

```<code>type OneKey<T, K extends keyof T = keyof T> =
    string extends K ? never : number extends K ? never :
    K extends any ? { [P in keyof T]?: P extends K ? T[P] : never } : never;

function log2<T extends object & OneKey<T>>(obj: T): void;
function log2(obj: any) {
    const keys = Object.keys(obj)
    if (keys.length !== 1) throw new Error("only one key is expected")
    const key = keys[0]
    console.log(key, obj[key])
}
</code>```

We're limiting T to object types without index signatures (because you can't be sure an index-signature object has only one key), and then we are making sure that the object is assignable to a "one-key" version of itself.  If the object you pass is type {a: string, b: number} then it checks against the union {a?: string, b?: undefined} | {a?: undefined, b?: number}.  Meaning it checks "either an a and no b, or a b and no a".  That doesn't match, so it fails.  If you pass type {a: string}, then the checked type is {a?: string}, which does match.

Let's make sure it works:

```<code>log2({ some_symbol }); // okay
log2({ some_symbol, some_other_symbol }); // error
//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Type '{ some_symbol: string; some_other_symbol: number; }' is not assignable
// to type '{ some_symbol?: undefined; some_other_symbol?: number | undefined; }'.
log2({}); // error
//   ~~
// Type '{}' is not assignable to parameter of type 'never'.
</code>```

Looks good to me.

Note that there are probably all sorts of edge cases. The type system isn't geared toward enforcing this type of check.  I'd expect if you pass an object with optional keys, or which is itself a union, you might see weird behavior.

Hope that helps; good luck!

Playground link to code

Body:
Let's say I have a variable. It has a name and a value, and I want them both for something, e.g. to log them - the value and a variable name. It can be done like so:

const some_symbol = "qwer"
const some_other_symbol = 100000

const log1 = (name: string, value: any) => console.log(name, value)

log1("some_symbol", some_symbol)
log1("some_other_symbol", some_other_symbol)
log1("some_symbol", some_symbol, "some_other_symbol", some_other_symbol) // compile time error
log1() // compile time error

But a much better way would be

log2({some_symbol})
log2({some_other_symbol})

To do so I can write a function

const log2 = (obj: { [key: string]: any }) => {
    const keys = Object.keys(obj)
    if( keys.length !== 1 ) throw new Error("only one key is expected")
    const key = keys[0]
    console.log(key, obj[key])
}

But

log2({some_symbol, some_other_symbol}) // compiles. run time error
log2({}) // compiles. run time error

I want compilation to fail on lines like log2({v1, v2}) and log2({}).

I would like get rid of dynamic type checks, and enforce a compile time check that obj param has only one key. And in general case - exact number of keys which names are unknown to me.

Body:
With sufficient type system juggling you can get the compiler to complain if your object has more than one known key. Something like this might work:

type OneKey<T, K extends keyof T = keyof T> =
    string extends K ? never : number extends K ? never :
    K extends any ? { [P in keyof T]?: P extends K ? T[P] : never } : never;

function log2<T extends object & OneKey<T>>(obj: T): void;
function log2(obj: any) {
    const keys = Object.keys(obj)
    if (keys.length !== 1) throw new Error("only one key is expected")
    const key = keys[0]
    console.log(key, obj[key])
}

We're limiting T to object types without index signatures (because you can't be sure an index-signature object has only one key), and then we are making sure that the object is assignable to a "one-key" version of itself.  If the object you pass is type {a: string, b: number} then it checks against the union {a?: string, b?: undefined} | {a?: undefined, b?: number}.  Meaning it checks "either an a and no b, or a b and no a".  That doesn't match, so it fails.  If you pass type {a: string}, then the checked type is {a?: string}, which does match.

Let's make sure it works:

log2({ some_symbol }); // okay
log2({ some_symbol, some_other_symbol }); // error
//   ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Type '{ some_symbol: string; some_other_symbol: number; }' is not assignable
// to type '{ some_symbol?: undefined; some_other_symbol?: number | undefined; }'.
log2({}); // error
//   ~~
// Type '{}' is not assignable to parameter of type 'never'.

Looks good to me.

Note that there are probably all sorts of edge cases. The type system isn't geared toward enforcing this type of check.  I'd expect if you pass an object with optional keys, or which is itself a union, you might see weird behavior.

Hope that helps; good luck!

<a href="http://www.typescriptlang.org/play/#code/C4TwDgpgBA8gdhA0hEAeAKgGioqEAewEcAJgM5QDWKA9gGZTpQC8VtD6AfCwLABQUQVDLAATgEs4AczyFi5HFAD8UBADcIoqAC5VAVwC2AI02yipCrhXrT2-kMUFzCgIZwQyqAG8oAbQAKUJJsIPSMALpKuoFO8pae6AHhOqoQGloAvik2ogDc-Pb8dHpwAMbA4jRwUAA2NFIATBhmcVA0RgBWEOVQAGSwCMhoXJwAFO0duugAlLpqNOIk+XzFZRVVtfUN4526biDT3vZCpVUiIRSsMJ3dwAB01CBkOx3Tx4LiDKOPZHc1xFJgAALKAAQmYrAAjIdgaIaAB3VKIgCiojholGACIqjUPFVoI8ghQCJByhASJi3gITmdgCEWBdfAAGcLvKCnOBkGj-P71b4obATXyPcJUjIFPgc85cgwQAD6ZBAxm5DMxAEd4ZpMfwpXSZfKaMDNAqlUYVVCmZbLRLdZspJCGaM4C5ZboRBJpNg1C4anoIHt3IdmNwpdyILypE6XRAvT6-VT+HVGqMfPqTcqalAMtNclAAPR5tqUFwgRNbFPCGiy9NmmrYNOGoHGxUZrM5-OFzTo-gFoQAPwHg6Hw5Ho5HPcL6HA0AA5Kmq-KW7W3WJJFJcw2jaIa9zdHBDCY8lmZ0TVIaoC4yGRxFJnUZ-lAJ1BgDRn9OoHPK9Wl9yolASiQEB0JI5IbgucqNs2pq-nuB6mAAPv+pBASBSzHncZbJl42a5r2XY0KIT6CAOT5TpAH7YSe4gUHA56Xtet4uPe0AvlAYAuKI0ZEFoYSgORM45DOdxAA" rel="nofollow noreferrer">Playground link to code


问:
Replace text link with image: CSS problem
I'm using Technique #8 from Nine Techniques for CSS Image Replacement but I'm not seeing the results I expect: instead of nicely positioned images, I'm getting... well, look for yourself:

http://beatchamber.officemedic.net

One change I've made to the technique is to change all the width: 100%/height: 100% values to the actual sizes; without that the images didn't display at all. I'm baffled, however, as to why the technique isn't working. Any suggestions?

答:
Its working demo here text is replace by Image using CSS code

Working Demo


问:
How to toggle class "active" in an accordion
I'm trying to make my accordion behave like in the image bellow, but I'm dont know how I can toggle the "active" class with my jquery code.

The first item ("cashback online") starts as "active", but I want to remove its class when I click in another item.

The image explains very clearly the expected behavior that I want.

My code:

$('.menu').on('click', function() {
  $('.content').hide();
  $(this).find('.content').show();
});

$('.menu').on('click', function(event) {
  $target = $(event.target);
  $target.addClass('active');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.sectionThree-container>ul {
  list-style: none;
}

.sectionThree-container>ul p {
  display: none;
}

.sectionThreeOptions>h2 {
  font-family: Poppins;
  font-style: normal;
  font-weight: bold;
  font-size: 22px;
  line-height: 22px;
  color: #4F4F4F;
  margin-left: 22px;
  cursor: pointer;
}

.sectionThreeOptions>h2.active {
  font-family: Poppins;
  font-style: normal;
  font-weight: bold;
  font-size: 30px;
  line-height: 22px;
  color: #222222;
  margin-left: 0;
}

.sectionThree-container .circle {
  width: 32px;
  height: 32px;
  left: 142px;
  top: 2050px;
  background: #FF6B7D;
  color: #fff;
  border-radius: 50%;
  margin: 20px 0 20px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 30px;
}

.sectionThree-container .circle.active {
  width: 60px;
  height: 60px;
  left: 128px;
  top: 1820px;
  background: #EF1247;
  margin-left: -10px;
}

.sectionThree-container>ul>li>p.active {
  margin-bottom: 60px;
}

.sectionThreeOptions {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
}</code>```

1

cashback online

        Ofereça cashback a seus clientes em nossos

        mais de 300 e-commerces parceiros através de

        uma plataforma personalizável

2

cashback offline

        Ofereça cashback em lojas físicas parceiras

        ou em sua própria rede e produtos através de uma

        experiência online e offline

3

recompensas

        Tenha sua própria plataforma de recompensas,

        permitindo que seus usuários acumulem e

        troquem pontos em mais de 50 parceiros

4

gamificação

        Torne a experiência ainda mais imersiva com

        mecânicas de gamificação na sua plataforma

        de fidelização personalizada

```

答:
add this on click

$('.menu div,.menu div h2').removeClass('active');
 $(this).find('div,div h2').addClass('active');

see snippet

$('.menu').on('click', function () {
 $('.content').hide();
 $(this).find('.content').show();
});

$('.menu').on('click', function (event) {
  $('.menu div,.menu div h2').removeClass('active');
  $(this).find('div,div h2').addClass('active');
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.sectionThree-container>ul {
    list-style: none;
}

.sectionThree-container>ul p {
    display: none;
}

.sectionThreeOptions>h2 {
    font-family: Poppins;
    font-style: normal;
    font-weight: bold;
    font-size: 22px;
    line-height: 22px;
    color: #4F4F4F;
    margin-left: 22px;
    cursor: pointer;
}

.sectionThreeOptions>h2.active {
    font-family: Poppins;
    font-style: normal;
    font-weight: bold;
    font-size: 30px;
    line-height: 22px;
    color: #222222;
    margin-left: 0;
}

.sectionThree-container .circle {
    width: 32px;
    height: 32px;
    left: 142px;
    top: 2050px;
    background: #FF6B7D;
    color: #fff;
    border-radius: 50%;
    margin: 20px 0 20px 0;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 30px;
}

.sectionThree-container .circle.active {
    width: 60px;
    height: 60px;
    left: 128px;
    top: 1820px;
    background: #EF1247;
    margin-left: -10px;
}

.sectionThree-container>ul>li>p.active {
    margin-bottom: 60px;
}

.sectionThreeOptions {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
}</code>```

1

cashback online

                        Ofereça cashback a seus clientes em nossos

                        mais de 300 e-commerces parceiros através de

                        uma plataforma personalizável

2

cashback offline

                        Ofereça cashback em lojas físicas parceiras

                        ou em sua própria rede e produtos através de uma

                        experiência online e offline

3

recompensas

                        Tenha sua própria plataforma de recompensas,

                         permitindo que seus usuários acumulem e

                          troquem pontos em mais de 50 parceiros

4

gamificação

                        Torne a experiência ainda mais imersiva com

                        mecânicas de gamificação na sua plataforma

                        de fidelização personalizada

```

Body:
I'm trying to make my accordion behave like in the image bellow, but I'm dont know how I can toggle the "active" class with my jquery code.

The first item ("cashback online") starts as "active", but I want to remove its class when I click in another item.

The image explains very clearly the expected behavior that I want.

My code:

$('.menu').on('click', function() {
  $('.content').hide();
  $(this).find('.content').show();
});

$('.menu').on('click', function(event) {
  $target = $(event.target);
  $target.addClass('active');
});

.sectionThree-container>ul {
  list-style: none;
}

.sectionThree-container>ul p {
  display: none;
}

.sectionThreeOptions>h2 {
  font-family: Poppins;
  font-style: normal;
  font-weight: bold;
  font-size: 22px;
  line-height: 22px;
  color: #4F4F4F;
  margin-left: 22px;
  cursor: pointer;
}

.sectionThreeOptions>h2.active {
  font-family: Poppins;
  font-style: normal;
  font-weight: bold;
  font-size: 30px;
  line-height: 22px;
  color: #222222;
  margin-left: 0;
}

.sectionThree-container .circle {
  width: 32px;
  height: 32px;
  left: 142px;
  top: 2050px;
  background: #FF6B7D;
  color: #fff;
  border-radius: 50%;
  margin: 20px 0 20px 0;
  display: flex;
  justify-content: center;
  align-items: center;
  margin-right: 30px;
}

.sectionThree-container .circle.active {
  width: 60px;
  height: 60px;
  left: 128px;
  top: 1820px;
  background: #EF1247;
  margin-left: -10px;
}

.sectionThree-container>ul>li>p.active {
  margin-bottom: 60px;
}

.sectionThreeOptions {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
}

1

cashback online

        Ofereça cashback a seus clientes em nossos

        mais de 300 e-commerces parceiros através de

        uma plataforma personalizável

2

cashback offline

        Ofereça cashback em lojas físicas parceiras

        ou em sua própria rede e produtos através de uma

        experiência online e offline

3

recompensas

        Tenha sua própria plataforma de recompensas,

        permitindo que seus usuários acumulem e

        troquem pontos em mais de 50 parceiros

4

gamificação

        Torne a experiência ainda mais imersiva com

        mecânicas de gamificação na sua plataforma

        de fidelização personalizada

Body:
add this on click

$('.menu div,.menu div h2').removeClass('active');
 $(this).find('div,div h2').addClass('active');

see snippet

$('.menu').on('click', function () {
 $('.content').hide();
 $(this).find('.content').show();
});

$('.menu').on('click', function (event) {
  $('.menu div,.menu div h2').removeClass('active');
  $(this).find('div,div h2').addClass('active');
});

.sectionThree-container>ul {
    list-style: none;
}

.sectionThree-container>ul p {
    display: none;
}

.sectionThreeOptions>h2 {
    font-family: Poppins;
    font-style: normal;
    font-weight: bold;
    font-size: 22px;
    line-height: 22px;
    color: #4F4F4F;
    margin-left: 22px;
    cursor: pointer;
}

.sectionThreeOptions>h2.active {
    font-family: Poppins;
    font-style: normal;
    font-weight: bold;
    font-size: 30px;
    line-height: 22px;
    color: #222222;
    margin-left: 0;
}

.sectionThree-container .circle {
    width: 32px;
    height: 32px;
    left: 142px;
    top: 2050px;
    background: #FF6B7D;
    color: #fff;
    border-radius: 50%;
    margin: 20px 0 20px 0;
    display: flex;
    justify-content: center;
    align-items: center;
    margin-right: 30px;
}

.sectionThree-container .circle.active {
    width: 60px;
    height: 60px;
    left: 128px;
    top: 1820px;
    background: #EF1247;
    margin-left: -10px;
}

.sectionThree-container>ul>li>p.active {
    margin-bottom: 60px;
}

.sectionThreeOptions {
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: flex-start;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="sectionThree-container">
            <ul>
                <li class="menu">
                    <div class="sectionThreeOptions">
                        <div class="circle active">1</div>
                        <h2 class="active">cashback online</h2>
                    </div>
                    <p class="content" style="display: inline">
                        Ofereça cashback a seus clientes em nossos </br>
                        mais de 300 e-commerces parceiros através de </br>
                        uma plataforma personalizável
                    </p>
                </li>
                  <li class="menu">
                    <div class="sectionThreeOptions">
                        <div class="circle">2</div>
                        <h2>cashback offline</h2>
                    </div>
                    <p class="content">
                        Ofereça cashback em lojas físicas parceiras </br>
                        ou em sua própria rede e produtos através de uma </br>
                        experiência online e offline
                    </p>
                </li>
                <li class="menu">
                    <div class="sectionThreeOptions">
                        <div class="circle">3</div>
                        <h2>recompensas</h2>
                    </div>
                    <p class="content">
                        Tenha sua própria plataforma de recompensas,</br>
                         permitindo que seus usuários acumulem e </br>
                          troquem pontos em mais de 50 parceiros
                    </p>
                </li>
                <li class="menu">
                    <div class="sectionThreeOptions">
                        <div class="circle">4</div>
                        <h2>gamificação</h2>
                    </div>
                    <p class="content">
                        Torne a experiência ainda mais imersiva com </br>
                        mecânicas de gamificação na sua plataforma </br>
                        de fidelização personalizada
                    </p>
                </li>
            </ul>

            <div class="sectionThreeOptionsImage">
                <img src="images/imagemUm.png" id="sectionThreeImage" alt="">
            </div>
        </div>
    </div>


问:
Flutter ListViews with other Items
I've been experimenting with ListViews a little and have come across a use case that I am unsure how to create.

Say I have a list of data that I'd like to display using a ListView.builder() which iterates through the list and creates a card for each one. Simple, enough.

However, now I'd like to add a button at the bottom of this list that does something useful, and it must be a part of the same scroll as the listview above it.

So, I'd like a scrolling list of data with a button at the bottom.
My first thought was to simply put the listview in a column with the button but, of course, the button is not a part of the scroll in this case.

I then thought of nesting the ListView.builder() inside of a standard ListView() like so -

```<code>ListView(
  children: [
    ListView.builder(
      ...
    ),
    RaisedButton(...),
  ],
)
</code>```

Unofrtunately I received errors upon trying this, but am not even sure if this is the correct solution.
Any help would be much appreciated, thank you!

答:
You can add the button as the last item of the ListView.builder

```<code>return ListView.builder(
  itemCount: 10,//Add One more for the button
  itemBuilder: (BuildContext context, int index) {
    // If it is the last item return the button
    if (index == 9) {
      return RaisedButton(onPressed: null);
    }

    //If not, return a card
    return Card();
  },
);
</code>```

Title: Flutter ListViews with other Items

Body:
I've been experimenting with ListViews a little and have come across a use case that I am unsure how to create.

Say I have a list of data that I'd like to display using a ListView.builder() which iterates through the list and creates a card for each one. Simple, enough.

However, now I'd like to add a button at the bottom of this list that does something useful, and it must be a part of the same scroll as the listview above it.

So, I'd like a scrolling list of data with a button at the bottom.
My first thought was to simply put the listview in a column with the button but, of course, the button is not a part of the scroll in this case.

I then thought of nesting the ListView.builder() inside of a standard ListView() like so -

ListView(
  children: [
    ListView.builder(
      ...
    ),
    RaisedButton(...),
  ],
)

Unofrtunately I received errors upon trying this, but am not even sure if this is the correct solution.
Any help would be much appreciated, thank you!

Body:
You can add the button as the last item of the ListView.builder

return ListView.builder(
  itemCount: 10,//Add One more for the button
  itemBuilder: (BuildContext context, int index) {
    // If it is the last item return the button
    if (index == 9) {
      return RaisedButton(onPressed: null);
    }

    //If not, return a card
    return Card();
  },
);


问:
Packages to verify the re-rendering in es5 components other than "WhyDidYouRender"
Right now I'm using the WhyDidYourender package to verify the component re-rendering but there are few components in my repo that uses es2015. WhyDidYouRender is not working in es2015 components. Seeing below error:

```<code>TypeError: Class constructor MyComponent cannot be invoked without 'new'
</code>```

So need a way to verify the re-rendering for es5 components. Also, tried Chrome highlights to verify the re-rendering, please don't recommend that.

Any help is appreciated, Thanks!
WhyDidYouRender repo link: https://github.com/welldone-software/why-did-you-render

答:
Support the ES6 or not is rely on your Browser. It's more like you trying to use the class but there is no instance to access.

Transpiled to es5 class is available in PR#8656, the whole react class elements are supported to extend with this library. If you transpile your classes by ES5 or ES6, use below code:

// traspiled to es5
const whyDidYouRender = require('@welldone-software/why-did-you-render);
// traspiled to es6
const whyDidYouRender = require('@welldone-software/why-did-you-render/dist/no-classes-transpile/umd/whyDidYouRender.min.js');

```

Body:
Right now I'm using the WhyDidYourender package to verify the component re-rendering but there are few components in my repo that uses es2015. WhyDidYouRender is not working in es2015 components. Seeing below error:

TypeError: Class constructor MyComponent cannot be invoked without 'new'

So need a way to verify the re-rendering for es5 components. Also, tried Chrome highlights to verify the re-rendering, please don't recommend that.

Any help is appreciated, Thanks!
WhyDidYouRender repo link: https://github.com/welldone-software/why-did-you-render


问:
Android get latest AOSP commits into my project
My Android application faced some freezing issues in some rare scenarios. After some research I found that this issue was caused by an Android bug which already was reported at issuetracker.google.com. Recently I got notified that the issue was fixed.

Now my question is, how do I make sure that this commit to AOSP that should presumably fix the freezes is already included in my project? It might have something to do with the build.gradle file, which looks like this:

```<code>dependencies {
    implementation 'androidx.preference:preference:1.1.0'
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.2.0-alpha03'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.0-beta4'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.vectordrawable:vectordrawable:1.1.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    ...
}
</code>```

For every implementation, a version number exists. So do I have to wait until Google releases the latest version of the package in which the fix is included and then use this latest version? Or will I get the latest fix just by resyncing the project?

I apologize if this is a stupid question, but I did not quite understand yet how the sync between the AOSP repository and my Android project works. Thanks in advance for any help.

Link to the Bug on Issuetracker. It is required to log in with a Google Account to view the Issuetracker.

答:
I would say 'androidx.appcompat:appcompat:1.2.0-alpha03'.

From the Issue Tracker we learn the link to the Patch that fixed the bug. In the patch page, we see the fix is in the 'appcompat' folder/library (the list of modified files at the bottom). Also, in the top-left, we see the repository and the branch where the patch was merged (repo platform/frameworks/support, branch androidx-master-dev). It is important that the patch is marked as MERGED. Only merged patches are integrated into released libraries.

Clicking on the branch link sends us to the repo/branch from which all androidx.* libs are built (See these instructions how to build androidx.* libs yourself and use them locally). Here we have to search for the patch that fixed that bug but the androidx repository receives a lot of patches and the list is pretty long. Fortunately, that search/filter box from top-right accepts a directory key. By adding 'directory:appcompat' in the search box we see only the patches from appcompat lib. It is easy to spot the 'Fix stopped Activities not resuming on < API 24' patch and right above it another patch 'Bump AppCompat version to 1.2.0-alpha03' that sets the version for the fixed appcompat lib.

Body:
My Android application faced some freezing issues in some rare scenarios. After some research I found that this issue was caused by an Android bug which already was reported at issuetracker.google.com. Recently I got notified that the issue was fixed.

Now my question is, how do I make sure that this commit to AOSP that should presumably fix the freezes is already included in my project? It might have something to do with the build.gradle file, which looks like this:

dependencies {
    implementation 'androidx.preference:preference:1.1.0'
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'com.google.android.material:material:1.2.0-alpha03'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.0-beta4'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.vectordrawable:vectordrawable:1.1.0'
    implementation 'androidx.recyclerview:recyclerview:1.1.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    ...
}

For every implementation, a version number exists. So do I have to wait until Google releases the latest version of the package in which the fix is included and then use this latest version? Or will I get the latest fix just by resyncing the project?

I apologize if this is a stupid question, but I did not quite understand yet how the sync between the AOSP repository and my Android project works. Thanks in advance for any help.

Link to the Bug on Issuetracker. It is required to log in with a Google Account to view the Issuetracker.


问:
Does sklearn PCA fit_transform() center input variables?
Question in the title. After calling pca.fit(X), suppose I called pca.fit_transform(new_X). Is new_X automatically centered by PCA? The documentation is unclear on this point.

答:
From the docs:

Linear dimensionality reduction using Singular Value Decomposition of
  the data to project it to a lower dimensional space. The input data is
  centered but not scaled for each feature before applying the SVD.

https://scikit-learn.org/stable/modules/generated/sklearn.decomposition.PCA.html

fit_transform is just the equivalent of running fit and transform consecutively on the same input matrix. The fit function calculates the means for centering the data, and the transform function applies the mean centering using the means calculated during fit.

Therefore to fit on one matrix, and apply the centering parameters learnt from that matrix to another (as, for example, when applying a model learnt on a training set to a test/validation set), you would need to use fit and transform separately.


问:
C++ QueryPerformanceCounter and QueryPerformanceFrequency
I have been attempting to create a timer for my game and I heard about QueryPerformanceCounter and QueryPerformanceFrequency. Could someone please explain how these can be used to calculate time/fps/ticks in a game loop?.</p>

答:
Microsoft support has a Knowledge Base article specifically about this:

How To Use QueryPerformanceCounter to Time Code

Basically you use QueryPerformanceCounter to get a high resolution timer value before and after the event you want to time.

Then use QueryPerformanceFrequency to get the number of ticks per second. Divide the time difference by this value to convert the value to seconds.