问:
Using chrome version is 98 and chromedriver 98.0.4758.80 . selenium version is 3.141.59. Still error
```<code>Starting ChromeDriver 98.0.4758.80 (7f0488e8ba0d8e019187c6325a16c29d9b7f4989-refs/branch-heads/4758@{#972}) on port 12326
Only local connections are allowed.
Please see https://chromedriver.chromium.org/security-considerations for suggestions on keeping ChromeDriver safe.
[1644434934.334][SEVERE]: listen() returned an error: An attempt was made to access a socket in a way forbidden by its access permissions. (0x271D)
[1644434934.335][SEVERE]: bind() returned an error: An attempt was made to access a socket in a way forbidden by its access permissions. (0x271D)
Unable to start server with either IPv4 or IPv6. Exiting...
Feb 10, 2022 12:59:14 AM org.openqa.selenium.os.OsProcess checkForError
SEVERE: org.apache.commons.exec.ExecuteException: Process exited with an error: 1 (Exit value: 1)
Exception in thread "main" org.openqa.selenium.WebDriverException: Timed out waiting for driver server to start.
Build info: version: '3.141.59', revision: 'e82be7d358', time: '2018-11-14T08:17:03'
System info: host: 'DESKTOP-UJJ98PR', ip: '192.168.45.184', os.name: 'Windows 10', os.arch: 'amd64', os.version: '10.0', java.version: '1.8.0_301'
Driver info: driver.version: ChromeDriver
    at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:202)
    at org.openqa.selenium.remote.service.DriverService.start(DriverService.java:188)
    at org.openqa.selenium.remote.service.DriverCommandExecutor.execute(DriverCommandExecutor.java:79)
    at org.openqa.selenium.remote.RemoteWebDriver.execute(RemoteWebDriver.java:552)
    at org.openqa.selenium.remote.RemoteWebDriver.startSession(RemoteWebDriver.java:213)
    at org.openqa.selenium.remote.RemoteWebDriver.<init>(RemoteWebDriver.java:131)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:181)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:168)
    at org.openqa.selenium.chrome.ChromeDriver.<init>(ChromeDriver.java:123)
    at pack1.Test.main(Test.java:9)
Caused by: org.openqa.selenium.net.UrlChecker$TimeoutException: Timed out waiting for [http://localhost:12326/status] to be available after 20009 ms
    at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:100)
    at org.openqa.selenium.remote.service.DriverService.waitUntilAvailable(DriverService.java:197)
    ... 9 more
Caused by: java.util.concurrent.TimeoutException
    at java.util.concurrent.FutureTask.get(FutureTask.java:205)
    at com.google.common.util.concurrent.SimpleTimeLimiter.callWithTimeout(SimpleTimeLimiter.java:156)
    at org.openqa.selenium.net.UrlChecker.waitUntilAvailable(UrlChecker.java:75)
    ... 10 more
</code>```

答: Seems to me that this URL http://localhost:12326/status is highly suspect. Try opening a well-known URL like https://www.google.com and see if your problem goes away. I am willing to bet it will. If your problem goes away, then you need to check what is happening with your localhost service. Most likely is not running, or the port is incorrect.


来源: stackexchange

问:
lodash check object properties has values
I have object with several properties, says it's something like this

```<code>{ a: "", b: undefined }
</code>```

in jsx is there any one line solution I can check whether that object's property is not empty or has value or not? If array there's a isEmpty method.

I tried this

```<code>const somethingKeyIsnotEmpty = Object.keys((props.something, key, val) => {
        return val[key] !== '' || val[key] !== undefined
})
</code>```

答:
const profile = {
name: 'John',
age: ''
};

const emptyProfile = .values(profile).every(.isEmpty);

This solution is more efficient to check if each key is really empty

ContentLicense: CC BY-SA 3.0

Body:
I have object with several properties, says it's something like this

{ a: "", b: undefined }

in jsx is there any one line solution I can check whether that object's property is not empty or has value or not? If array there's a isEmpty method.

I tried this

const somethingKeyIsnotEmpty = Object.keys((props.something, key, val) => {
        return val[key] !== '' || val[key] !== undefined
})

ContentLicense: CC BY-SA 4.0


问:
Using Powershell to Generate Report of C# Classes versus Methods and Properties
Has anyone used Powershell to generate a report of C# classes versus methods and properties?  I'll admit up front I'm not attempting first to write this myself, but someone out there has probably already done it, or would highly enjoy doing it.  The challenge will be recognizing things like method signatures across multiple lines.  You could join the string array returned by gc and search on that to make it easier.  If no one answers, I'll eventually post a solution, but probably many weeks from now.

Update:  I'm looking for a Powershell solution because that's already my main scripting language, and I'd like to be able to make changes over time, perhaps extend it to cover JavaScript for example, or change the report format, and I'd like it to work with any version of Visual Studio and C#.  I'm also looking for a text report, nothing graphical, so that it's more searchable and manipulatable.  I like simple fully programmable free things that impose no limits.  :)

Thanks,

Mike

答:
I'm sure you can access Reflection through PowerShell.

You should also look into NDepend, which can do a lot of this sort of thing.

OwnerDisplayName: Mike

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Mike

OwnerDisplayName: John Saunders


问:
Angular routing to open the expansion panel
First off I'm new to Angular, only been learning it for about a month so I just have a quick question that I can't seem to find anything on. So I'm trying to use a routerLink to go from one page to another, but also I want that page to open an expansion panel once it has landed on the desired page. My expansion panels aren't labeled in any way that would show up in the console, it just has the basic information. Would I have to create a method in order to open the tab once the routerLink is clicked?

Thanks in advance!

答:
When you create the project with nodeJS you have to add the attribute routing as ng new yourp_name --routing, if you don't do, you have to add the files manually. in the app-routing.module.ts you have a const routes, you have to add the path of your apps, for example if you have a HomePage, must be

```<code>const routes: Routes = [
  { path: "", redirectTo: "homepage", pathMatch: "full" },
  { path: "homepage", component: HomePageComponent }
];
</code>```

when you add it, it will create in all places automatically.

After it you can reference it in your apps as a routerlink with the path name you gave it, e.g

```<code><a routerLink="/homepage"></a>
</code>```

Hope it works

Body:
When you create the project with nodeJS you have to add the attribute routing as ng new yourp_name --routing, if you don't do, you have to add the files manually. in the app-routing.module.ts you have a const routes, you have to add the path of your apps, for example if you have a HomePage, must be

const routes: Routes = [
  { path: "", redirectTo: "homepage", pathMatch: "full" },
  { path: "homepage", component: HomePageComponent }
];

when you add it, it will create in all places automatically.

After it you can reference it in your apps as a routerlink with the path name you gave it, e.g

<a routerLink="/homepage"></a>

Hope it works


问:
Flutter Error: No named parameter with the name 'isVisible' error on url_launcher_web and pointer_interceptor
after running flutter pub upgrade I get these errors when I run flutter build web

```<code>../../development/flutter/.pub-cache/hosted/pub.dartlang.org/pointer_interceptor-0.9.2/lib/src/web.dart:31:6: Error: No named parameter with the name 'isVisible'.
  }, isVisible: false);
     ^^^^^^^^^

../../development/flutter/.pub-cache/hosted/pub.dartlang.org/url_launcher_web-2.0.7/lib/url_launcher_web.dart:50:61: Error: No named parameter with the name 'isVisible'.
        .registerViewFactory(linkViewType, linkViewFactory, isVisible: false);
</code>```

答:
The issue is that Url_launcher 6.0.18 automatically updated the internal library url_launcher_web from 2.0.6 to 2.0.7.

Now 2.0.7 uses flutter 2.10 and 2.0.6 uses flutter 2.5. They did that without "requiring" flutter 2.10 (which they fixed with url_launcher 2.0.8). But if you're still at flutter <2.10 you'll have an issue.

There is 2 options you have here:

cheap option. (I am using this now right now as a "hotfix"): Add this to your pubspec.yaml (below dependencies or dev_dependencies)

```<code>dependency_overrides:
  url_launcher_web: 2.0.6
</code>```

This just makes url_launcher load the "right" version.

The right option would be to upgrade your sdk to flutter 2.10 (with flutter upgrade). Maybe you just don't want to do that right now but you eventually should.

Body:
after running flutter pub upgrade I get these errors when I run flutter build web

../../development/flutter/.pub-cache/hosted/pub.dartlang.org/pointer_interceptor-0.9.2/lib/src/web.dart:31:6: Error: No named parameter with the name 'isVisible'.
  }, isVisible: false);
     ^^^^^^^^^

../../development/flutter/.pub-cache/hosted/pub.dartlang.org/url_launcher_web-2.0.7/lib/url_launcher_web.dart:50:61: Error: No named parameter with the name 'isVisible'.
        .registerViewFactory(linkViewType, linkViewFactory, isVisible: false);

Body:
The issue is that Url_launcher 6.0.18 automatically updated the internal library url_launcher_web from 2.0.6 to 2.0.7.

Now 2.0.7 uses flutter 2.10 and 2.0.6 uses flutter 2.5. They did that without "requiring" flutter 2.10 (which they fixed with url_launcher 2.0.8). But if you're still at flutter <2.10 you'll have an issue.

There is 2 options you have here:

cheap option. (I am using this now right now as a "hotfix"): Add this to your pubspec.yaml (below dependencies or dev_dependencies)

dependency_overrides:
  url_launcher_web: 2.0.6

This just makes url_launcher load the "right" version.

The right option would be to upgrade your sdk to flutter 2.10 (with flutter upgrade). Maybe you just don't want to do that right now but you eventually should.


问:
RStudio encounters fatal error and restarts on EVERY error in R
I recently changed employers and only have local administrator privileges on a virtual machine running Windows. I installed R and RStudio, both of which work fine, UNTIL I commit an error—any error. Once that happens, RStudio gives the dreaded "fatal error" message and restarts. The reprex is simple. Start RStudio and type as.Date('a'). This will give an error and cause Rstudio to shut down. It appears to be a java error with the key issue being (TypeError) : Cannot read property 'M' of null;. There have been many requests for help in RStudio's support forum with similar crashes which have not been answered, which is why I'm duplicating the question here.

Session Info and RStudio crash logs posted below

SessionInfo

```<code>R Under development (unstable) (2022-02-04 r81652 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 22000)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.utf8  LC_CTYPE=English_United States.utf8    LC_MONETARY=English_United States.utf8
[4] LC_NUMERIC=C                           LC_TIME=English_United States.utf8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] compiler_4.2.0 tools_4.2.0
</code>```

RStudio Logs

```<code>2022-02-09T17:56:41.573000Z [rsession-AvrahamAdler] WARNING findProgramOnPath returns wrong result: C:\Users\AVRAHA~1\AppData\Local\Programs\MiKTeX\miktex\bin\x64\pdflatex.exe != C:/Users/AvrahamAdler/AppData/Local/Programs/MiKTeX/miktex/bin/x64/pdflatex.exe; LOGGED FROM: class rstudio::core::FilePath __cdecl rstudio::session::module_context::findProgram(const class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > &) src/cpp/session/SessionModuleContext.cpp:1206
2022-02-09T17:56:41.573000Z [rsession-AvrahamAdler] WARNING findProgramOnPath returns wrong result: C:\Users\AVRAHA~1\AppData\Local\Programs\MiKTeX\miktex\bin\x64\pdflatex.exe != C:/Users/AvrahamAdler/AppData/Local/Programs/MiKTeX/miktex/bin/x64/pdflatex.exe; LOGGED FROM: class rstudio::core::FilePath __cdecl rstudio::session::module_context::findProgram(const class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > &) src/cpp/session/SessionModuleContext.cpp:1206
2022-02-09T17:56:41.577000Z [rsession-AvrahamAdler] WARNING findProgramOnPath returns wrong result: C:\Users\AVRAHA~1\AppData\Local\Programs\MiKTeX\miktex\bin\x64\pdflatex.exe != C:/Users/AvrahamAdler/AppData/Local/Programs/MiKTeX/miktex/bin/x64/pdflatex.exe; LOGGED FROM: class rstudio::core::FilePath __cdecl rstudio::session::module_context::findProgram(const class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > &) src/cpp/session/SessionModuleContext.cpp:1206
2022-02-09T17:56:41.577000Z [rsession-AvrahamAdler] WARNING findProgramOnPath returns wrong result: C:\Users\AVRAHA~1\AppData\Local\Programs\MiKTeX\miktex\bin\x64\pdflatex.exe != C:/Users/AvrahamAdler/AppData/Local/Programs/MiKTeX/miktex/bin/x64/pdflatex.exe; LOGGED FROM: class rstudio::core::FilePath __cdecl rstudio::session::module_context::findProgram(const class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > &) src/cpp/session/SessionModuleContext.cpp:1206
2022-02-09T17:56:43.063059Z [rsession-AvrahamAdler] ERROR CLIENT EXCEPTION (rsession-AvrahamAdler): (TypeError) : Cannot read property 'M' of null;|||org/rstudio/studio/client/workbench/views/source/editors/text/AceEditor.java#4487::setScrollSpeed|||org/rstudio/studio/client/workbench/views/source/editors/text/AceEditorMonitor.java#46::monitor|||org/rstudio/studio/client/workbench/views/source/editors/text/AceEditorMonitor.java#70::execute|||com/google/gwt/core/client/impl/SchedulerImpl.java#140::execute|||com/google/gwt/core/client/impl/Impl.java#306::apply|||com/google/gwt/core/client/impl/Impl.java#345::entry0|||rstudio-0.js#-1::eval|||com/google/gwt/cell/client/AbstractEditableCell.java#41::viewDataMap|||Client-ID: 33e600bb-c1b1-46bf-b562-ab5cba070b0e|||User-Agent: Mozilla/5.0 (Windows NT 10.0  Win64  x64) AppleWebKit/537.36 (KHTML, like Gecko) QtWebEngine/5.12.8 Chrome/69.0.3497.128 Safari/537.36
2022-02-09T17:56:43.063059Z [rsession-AvrahamAdler] ERROR CLIENT EXCEPTION (rsession-AvrahamAdler): (TypeError) : Cannot read property 'M' of null;|||org/rstudio/studio/client/workbench/views/source/editors/text/AceEditor.java#4487::setScrollSpeed|||org/rstudio/studio/client/workbench/views/source/editors/text/AceEditorMonitor.java#46::monitor|||org/rstudio/studio/client/workbench/views/source/editors/text/AceEditorMonitor.java#70::execute|||com/google/gwt/core/client/impl/SchedulerImpl.java#140::execute|||com/google/gwt/core/client/impl/Impl.java#306::apply|||com/google/gwt/core/client/impl/Impl.java#345::entry0|||rstudio-0.js#-1::eval|||com/google/gwt/cell/client/AbstractEditableCell.java#41::viewDataMap|||Client-ID: 33e600bb-c1b1-46bf-b562-ab5cba070b0e|||User-Agent: Mozilla/5.0 (Windows NT 10.0  Win64  x64) AppleWebKit/537.36 (KHTML, like Gecko) QtWebEngine/5.12.8 Chrome/69.0.3497.128 Safari/537.36
</code>```

答:
RStudio is about to come out with version 2022.02.0.  As I write this it hasn't been released, but you can get daily builds from https://dailies.rstudio.com/ .  The NEWS for that release includes the statement

RStudio now supports the experimental UTF-8 UCRT builds of R (#9824)

so it should fix your problems (and according to a comment, it did).  However, do pay attention to the warning at the top of that web page:

Daily builds are intended for testing purposes, and are not recommended for general use. For stable builds, please visit rstudio.com.

Body:
I recently changed employers and only have local administrator privileges on a virtual machine running Windows. I installed R and RStudio, both of which work fine, UNTIL I commit an error—any error. Once that happens, RStudio gives the dreaded "fatal error" message and restarts. The reprex is simple. Start RStudio and type as.Date('a'). This will give an error and cause Rstudio to shut down. It appears to be a java error with the key issue being (TypeError) : Cannot read property 'M' of null;. There have been many requests for help in RStudio's support forum with similar crashes which have not been answered, which is why I'm duplicating the question here.

Session Info and RStudio crash logs posted below

SessionInfo

R Under development (unstable) (2022-02-04 r81652 ucrt)
Platform: x86_64-w64-mingw32/x64 (64-bit)
Running under: Windows 10 x64 (build 22000)

Matrix products: default

locale:
[1] LC_COLLATE=English_United States.utf8  LC_CTYPE=English_United States.utf8    LC_MONETARY=English_United States.utf8
[4] LC_NUMERIC=C                           LC_TIME=English_United States.utf8

attached base packages:
[1] stats     graphics  grDevices utils     datasets  methods   base

loaded via a namespace (and not attached):
[1] compiler_4.2.0 tools_4.2.0

RStudio Logs

2022-02-09T17:56:41.573000Z [rsession-AvrahamAdler] WARNING findProgramOnPath returns wrong result: C:\Users\AVRAHA~1\AppData\Local\Programs\MiKTeX\miktex\bin\x64\pdflatex.exe != C:/Users/AvrahamAdler/AppData/Local/Programs/MiKTeX/miktex/bin/x64/pdflatex.exe; LOGGED FROM: class rstudio::core::FilePath __cdecl rstudio::session::module_context::findProgram(const class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > &) src/cpp/session/SessionModuleContext.cpp:1206
2022-02-09T17:56:41.573000Z [rsession-AvrahamAdler] WARNING findProgramOnPath returns wrong result: C:\Users\AVRAHA~1\AppData\Local\Programs\MiKTeX\miktex\bin\x64\pdflatex.exe != C:/Users/AvrahamAdler/AppData/Local/Programs/MiKTeX/miktex/bin/x64/pdflatex.exe; LOGGED FROM: class rstudio::core::FilePath __cdecl rstudio::session::module_context::findProgram(const class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > &) src/cpp/session/SessionModuleContext.cpp:1206
2022-02-09T17:56:41.577000Z [rsession-AvrahamAdler] WARNING findProgramOnPath returns wrong result: C:\Users\AVRAHA~1\AppData\Local\Programs\MiKTeX\miktex\bin\x64\pdflatex.exe != C:/Users/AvrahamAdler/AppData/Local/Programs/MiKTeX/miktex/bin/x64/pdflatex.exe; LOGGED FROM: class rstudio::core::FilePath __cdecl rstudio::session::module_context::findProgram(const class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > &) src/cpp/session/SessionModuleContext.cpp:1206
2022-02-09T17:56:41.577000Z [rsession-AvrahamAdler] WARNING findProgramOnPath returns wrong result: C:\Users\AVRAHA~1\AppData\Local\Programs\MiKTeX\miktex\bin\x64\pdflatex.exe != C:/Users/AvrahamAdler/AppData/Local/Programs/MiKTeX/miktex/bin/x64/pdflatex.exe; LOGGED FROM: class rstudio::core::FilePath __cdecl rstudio::session::module_context::findProgram(const class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > &) src/cpp/session/SessionModuleContext.cpp:1206
2022-02-09T17:56:43.063059Z [rsession-AvrahamAdler] ERROR CLIENT EXCEPTION (rsession-AvrahamAdler): (TypeError) : Cannot read property 'M' of null;|||org/rstudio/studio/client/workbench/views/source/editors/text/AceEditor.java#4487::setScrollSpeed|||org/rstudio/studio/client/workbench/views/source/editors/text/AceEditorMonitor.java#46::monitor|||org/rstudio/studio/client/workbench/views/source/editors/text/AceEditorMonitor.java#70::execute|||com/google/gwt/core/client/impl/SchedulerImpl.java#140::execute|||com/google/gwt/core/client/impl/Impl.java#306::apply|||com/google/gwt/core/client/impl/Impl.java#345::entry0|||rstudio-0.js#-1::eval|||com/google/gwt/cell/client/AbstractEditableCell.java#41::viewDataMap|||Client-ID: 33e600bb-c1b1-46bf-b562-ab5cba070b0e|||User-Agent: Mozilla/5.0 (Windows NT 10.0  Win64  x64) AppleWebKit/537.36 (KHTML, like Gecko) QtWebEngine/5.12.8 Chrome/69.0.3497.128 Safari/537.36
2022-02-09T17:56:43.063059Z [rsession-AvrahamAdler] ERROR CLIENT EXCEPTION (rsession-AvrahamAdler): (TypeError) : Cannot read property 'M' of null;|||org/rstudio/studio/client/workbench/views/source/editors/text/AceEditor.java#4487::setScrollSpeed|||org/rstudio/studio/client/workbench/views/source/editors/text/AceEditorMonitor.java#46::monitor|||org/rstudio/studio/client/workbench/views/source/editors/text/AceEditorMonitor.java#70::execute|||com/google/gwt/core/client/impl/SchedulerImpl.java#140::execute|||com/google/gwt/core/client/impl/Impl.java#306::apply|||com/google/gwt/core/client/impl/Impl.java#345::entry0|||rstudio-0.js#-1::eval|||com/google/gwt/cell/client/AbstractEditableCell.java#41::viewDataMap|||Client-ID: 33e600bb-c1b1-46bf-b562-ab5cba070b0e|||User-Agent: Mozilla/5.0 (Windows NT 10.0  Win64  x64) AppleWebKit/537.36 (KHTML, like Gecko) QtWebEngine/5.12.8 Chrome/69.0.3497.128 Safari/537.36


问:
Get a list of numbers that adds up to a number "n" (using repetition of number) - how would one consider the case of using same number multiple times?
```<code>def getList(n, input_list, caching_list):
</code>```

The function should return a list that adds up to a number "n" using numbers from the input_list, given that numbers can be repeated. Looking to use recursion.

current code:

```<code>def getList(n, input_list, caching_list):
  if n == 0 :
    return caching_list
  if n < 0 or len(input_list) == 0:
    return []

  for i in input_list:
    if find_sum(n-i,input_list,caching_list) == caching_list:
        caching_list.append(i)
        return caching_list
  return []
</code>```

example
n = 13, input_list= [2,3,5] should result in [2,2,2,2,2,3] or [5,5,2] or anything that adds to 13.

Doing this with using a number just 1 time is easy, but how would one consider the case of using same number multiple times?

答:
With recursion, this can be solved using a depth-first search (DFS) algorithm, but it can throw RecursionError: maximum recursion depth exceeded in comparison

```<code>def find(n2, plist):
    result = []
    def find2(n):
        if n == 0:
            return True
        if n < 0:
            return False
        for p in plist:
            if find2(n-p):
                result.append(p)
                return True
    find2(n2)
    return result

print(find(17, [2,3,5]))       # [3, 2, 2, 2, 2, 2, 2, 2]
print(find(7, [3,5]))          # []
print(find(77777, [3,5,7,11])) # recursion error
</code>```

To get rid of the recursion error, recursive DFS can be rewritten into iterative DFS.

Body:
def getList(n, input_list, caching_list):

The function should return a list that adds up to a number "n" using numbers from the input_list, given that numbers can be repeated. Looking to use recursion.

current code:

def getList(n, input_list, caching_list):
  if n == 0 :
    return caching_list
  if n < 0 or len(input_list) == 0:
    return []

  for i in input_list:
    if find_sum(n-i,input_list,caching_list) == caching_list:
        caching_list.append(i)
        return caching_list
  return []

example
n = 13, input_list= [2,3,5] should result in [2,2,2,2,2,3] or [5,5,2] or anything that adds to 13.

Doing this with using a number just 1 time is easy, but how would one consider the case of using same number multiple times?

Body:
With recursion, this can be solved using a depth-first search (DFS) algorithm, but it can throw RecursionError: maximum recursion depth exceeded in comparison

def find(n2, plist):
    result = []
    def find2(n):
        if n == 0:
            return True
        if n < 0:
            return False
        for p in plist:
            if find2(n-p):
                result.append(p)
                return True
    find2(n2)
    return result

print(find(17, [2,3,5]))       # [3, 2, 2, 2, 2, 2, 2, 2]
print(find(7, [3,5]))          # []
print(find(77777, [3,5,7,11])) # recursion error

To get rid of the recursion error, recursive DFS can be rewritten into iterative DFS.


问:
Extract string between exact word and pattern using stringr
I have been wondering how to extract string in R using stringr or another package between the exact word "to the" (which is always lowercase) and the very second comma in a sentence.

For instance:

String: "This not what I want to the THIS IS WHAT I WANT, DO YOU SEE IT?, this is not what I want"

Desired output: "THIS IS WHAT I WANT, DO YOU SEE IT?"

I have this vector:

```<code>x<-c("This not what I want to the THIS IS WHAT I WANT, DO YOU SEE IT?, this is not what I want",
     "HYU_IO TO TO to the I WANT, THIS, this i dont, want", "uiui uiu to the xxxx,,this is not, what I want")
</code>```

and I am trying to use this code

```<code>str_extract(string = x, pattern = "(?<=to the ).*(?=\\,)")
</code>```

but I cant seem to get it to work to properly give me this:

```<code>"THIS IS WHAT I WANT, DO YOU SEE IT?"
"I WANT, THIS"
"xxxx,"
</code>```

Thank you guys so much for your time and help

答:
You were close!

```<code>str_extract(string = x, pattern = "(?<=to the )[^,]*,[^,]*")
# [1] "THIS IS WHAT I WANT, DO YOU SEE IT?"
# [2] "I WANT, THIS"
# [3] "xxxx,"
</code>```

The look-behind stays the same, [^,]* matches anything but a comma, then , matches exactly one comma, then [^,]* again for anything but a comma.

Body:
I have been wondering how to extract string in R using stringr or another package between the exact word "to the" (which is always lowercase) and the very second comma in a sentence.

For instance:

String: "This not what I want to the THIS IS WHAT I WANT, DO YOU SEE IT?, this is not what I want"

Desired output: "THIS IS WHAT I WANT, DO YOU SEE IT?"

I have this vector:

x<-c("This not what I want to the THIS IS WHAT I WANT, DO YOU SEE IT?, this is not what I want",
     "HYU_IO TO TO to the I WANT, THIS, this i dont, want", "uiui uiu to the xxxx,,this is not, what I want")

and I am trying to use this code

str_extract(string = x, pattern = "(?<=to the ).*(?=\\,)")

but I cant seem to get it to work to properly give me this:

"THIS IS WHAT I WANT, DO YOU SEE IT?"
"I WANT, THIS"
"xxxx,"

Thank you guys so much for your time and help

Body:
You were close!

str_extract(string = x, pattern = "(?<=to the )[^,]*,[^,]*")
# [1] "THIS IS WHAT I WANT, DO YOU SEE IT?"
# [2] "I WANT, THIS"
# [3] "xxxx,"

The look-behind stays the same, [^,]* matches anything but a comma, then , matches exactly one comma, then [^,]* again for anything but a comma.


问:
how to make application with android
I am trying to create a new android apps but it says me like this

[2011-08-18 15:27:39 - jeetu] Conversion to Dalvik format failed:
  Unable to execute dex: wrapper was not properly loaded first

What does it mean?

答:
You can read developers guide. It is really good. - http://developer.android.com/guide/index.html

I love reading Pragmatic Hello Android also..
  link - http://pragprog.com/book/eband3/hello-android

Title: how to make application with android


问:
I cannot paste Rstudio console output into Excel anymore
So previously, when I ran statistics in R, I was able to copy and paste to Excel works sheet (for example rstudio console window output), but now it seems like there is a problem. When I now press paste (or ctrl+v), it just leaves it empty and nothing is pasted into the worksheet. It works if I paste it to notepad first and then copy and paste it to Excel.

What is the problem and how can I solve it?

答:
I have the same problem when trying to copy/paste a tibble, but making it into a data.frame solves the issue. The output from this:

```<code>a <- c("abc",9238)
b <- c("def",123)
tibble(a,b)
</code>```

shows up blank when I copy/paste, but this gives console output that works:

```<code>tibble(a,b) %>% data.frame()
</code>```

Body:
I have the same problem when trying to copy/paste a tibble, but making it into a data.frame solves the issue. The output from this:

a <- c("abc",9238)
b <- c("def",123)
tibble(a,b)

shows up blank when I copy/paste, but this gives console output that works:

tibble(a,b) %>% data.frame()


问:
problem whit the new orm method AttributeError: 'sale.order.line' object has no attribute 'get' odoo
i want to add lines to the order_line from other sale order but it giveme an error AttributeError: 'sale.order.line' object has no attribute 'get' odoo

my code below

```<code>from odoo import fields, models, api

class InvoiceOrder(models.Model):
    _inherit = "sale.order"

    container_id=fields.Many2one(comodel_name="container.shipment",string="Container")

    @api.onchange("container_id")
    def _onchange_lines_conatiner(self):

        if self.container_id != None:

            container=self.env["container.shipment"].search(
                [
                    ("name", "=", self.container_id.name),
                ], limit=1
            )
            order_line_def= self.order_line

            dict_order={}
            vals=[]

            for bulk in container.bulk_ids:
                for order in bulk.line_ids:
                    order_id=order.order_id
                    order_line1=order_id.order_line

                    order_line_def= order_line1 + order_line_def
                    for record in order_line_def:
                        dict_order.update({
                                'product_id': record.product_id.id,
                                'name': record.name,
                                'product_uom_qty':record.product_uom_qty,
                                'product_uom': record.product_uom,
                                'price_unit': record.price_unit,
                                'order_id': self.id,

                            })
                        vals.append(dict_order)

                        for line1 in vals:
                            order1 = self.env['sale.order.line'].new(line1)

                            return order1
</code>```

答:
Odoo expects the onchange method to return a dictionary

The odoo documentation says that the method may return a dictionary for changing field domains and pop up a warning message, like in the old API:

```<code>return {
    'domain': {'other_id': [('partner_id', '=', partner_id)]},
    'warning': {'title': "Warning", 'message': "What is this?"},
}
</code>```

To fix that error, do not return a sale.order.line record

Body:
i want to add lines to the order_line from other sale order but it giveme an error AttributeError: 'sale.order.line' object has no attribute 'get' odoo

my code below

from odoo import fields, models, api

class InvoiceOrder(models.Model):
    _inherit = "sale.order"

    container_id=fields.Many2one(comodel_name="container.shipment",string="Container")

    @api.onchange("container_id")
    def _onchange_lines_conatiner(self):

        if self.container_id != None:

            container=self.env["container.shipment"].search(
                [
                    ("name", "=", self.container_id.name),
                ], limit=1
            )
            order_line_def= self.order_line

            dict_order={}
            vals=[]

            for bulk in container.bulk_ids:
                for order in bulk.line_ids:
                    order_id=order.order_id
                    order_line1=order_id.order_line

                    order_line_def= order_line1 + order_line_def
                    for record in order_line_def:
                        dict_order.update({
                                'product_id': record.product_id.id,
                                'name': record.name,
                                'product_uom_qty':record.product_uom_qty,
                                'product_uom': record.product_uom,
                                'price_unit': record.price_unit,
                                'order_id': self.id,

                            })
                        vals.append(dict_order)

                        for line1 in vals:
                            order1 = self.env['sale.order.line'].new(line1)

                            return order1

Body:
Odoo expects the onchange method to return a dictionary

The odoo documentation says that the method may return a dictionary for changing field domains and pop up a warning message, like in the old API:

return {
    'domain': {'other_id': [('partner_id', '=', partner_id)]},
    'warning': {'title': "Warning", 'message': "What is this?"},
}

To fix that error, do not return a sale.order.line record


问:
How to plot 'log' and 'first difference of log' in R?
This might sound easy question to some people, but I am a beginner in R and I couldn't find an answer to my problem.

So, basically, I have uploaded my excel data into R. I have three variables. The first variable is in the format of the date (1994-01-03), the other two are just numbers.

dataset looks like this

I have plotted my main graphs using this command:

plot(dataset$observation_date,dataset$interest_rate,t="l", xlab = "Observation date" , ylab = "Interest Rate")

Now I need to plot a graph of the "log" and "first difference of log" of two variables.

Big thanks in advance for any help!!

答:
If you want this all on one plot, you are going to need to use the lines() function and play around with the specifics such as the line types etc.

The code I have is:

# Creating some dummy data
dt<-data.frame(time=c(1:10),
               interest_rate = c(1:10))

dt$logged_interest<- log(dt$interest_rate)
# Make blank column
dt$logged_diff<- NA
# First difference excludes the first term
dt$logged_diff[2:10]<- diff(dt$logged_interest)

# The Plot
plot(dt$time,dt$interest_rate,
     type = "l",
     xlab = "Time" ,
     ylab = "Interest Rate",
     ylim=c(-1,10),
     main="Interest Rates over Time")
lines(dt$time,dt$logged_interest,lty=2)
lines(dt$time,dt$logged_diff,lty=3)
legend("bottomright",
       legend=c("Interest Rate",
                "Logged Interest Rate",
                "First Difference of Log"),
       lty=1:3, cex=0.8)
```

Hope this is helpful!

Body:
If you want this all on one plot, you are going to need to use the lines() function and play around with the specifics such as the line types etc.

The code I have is:

# Creating some dummy data
dt<-data.frame(time=c(1:10),
               interest_rate = c(1:10))

dt$logged_interest<- log(dt$interest_rate)
# Make blank column
dt$logged_diff<- NA
# First difference excludes the first term
dt$logged_diff[2:10]<- diff(dt$logged_interest)

# The Plot
plot(dt$time,dt$interest_rate,
     type = "l",
     xlab = "Time" ,
     ylab = "Interest Rate",
     ylim=c(-1,10),
     main="Interest Rates over Time")
lines(dt$time,dt$logged_interest,lty=2)
lines(dt$time,dt$logged_diff,lty=3)
legend("bottomright",
       legend=c("Interest Rate",
                "Logged Interest Rate",
                "First Difference of Log"),
       lty=1:3, cex=0.8)

Hope this is helpful!


问:
Linking OpenVR through VCPKG via CMAKE
I have Installed OpenVR through vcpkg and am trying to link it via CMAKE, the issue is that I don't know how to do it, nor can I find any info on how to.

Unlike other packages where once installed it tells you how to link via CMAKE by using find_package and target_link_libraries, OpenVR doesn't. I initially assumed that

```<code>find_package(openvr CONFIG REQUIRED)
target_link_libraries(${Proj_Name} PRIVATE openvr::openvr)
</code>```

would work but instead I get the error

```<code>CMake Error at C:/dev/vcpkg/vcpkg/scripts/buildsystems/vcpkg.cmake:793 (_find_package):
Could not find a package configuration file provided by "openvr" with any
of the following names:

openvrConfig.cmake
openvr-config.cmake

Add the installation prefix of "openvr" to CMAKE_PREFIX_PATH or set
"openvr_DIR" to a directory containing one of the above files.  If "openvr"
provides a separate development package or SDK, be sure it has been
installed.
</code>```

Usually vcpkg.cmake provides CMAKE with the config.cmake files but not for OpenVR, so how do i link it properly?

答:
Here is a find module that seems to work. OpenVR does some very non-standard things with its debug library naming. I tested this on Linux, and it works, but I do not have easy access to a Windows machine right now. Let me see the error message if it fails and I can try to fix it.

You'll use it like this, from the top-level CMakeLists.txt

```<code># ./CMakeLists.txt
cmake_minimum_required(VERSION 3.22)
project(test)

list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")

find_package(OpenVR REQUIRED)

add_executable(main main.cpp)
target_link_libraries(main PRIVATE OpenVR::OpenVR)
</code>```

And then just put the following find module in cmake/FindOpenVR.cmake:

```<code># cmake/FindOpenVR.cmake
cmake_minimum_required(VERSION 3.22)

function(_OpenVR_find)
  include(FindPackageHandleStandardArgs)
  include(SelectLibraryConfigurations)

  ## Find the include path
  find_path(OpenVR_INCLUDE_DIR NAMES openvr.h)

  ## Determine version by scanning header
  if (OpenVR_INCLUDE_DIR)
    set(openvr_header "${OpenVR_INCLUDE_DIR}/openvr.h")

    set(re_major "^\tstatic const uint32_t k_nSteamVRVersionMajor = ([0-9]+).*;$")
    set(re_minor "^\tstatic const uint32_t k_nSteamVRVersionMinor = ([0-9]+).*;$")
    set(re_patch "^\tstatic const uint32_t k_nSteamVRVersionBuild = ([0-9]+).*;$")

    file(STRINGS "${openvr_header}" OpenVR_VERSION_MAJOR REGEX "${re_major}")
    file(STRINGS "${openvr_header}" OpenVR_VERSION_MINOR REGEX "${re_minor}")
    file(STRINGS "${openvr_header}" OpenVR_VERSION_PATCH REGEX "${re_patch}")

    string(REGEX REPLACE "${re_major}" "\\1"
           OpenVR_VERSION_MAJOR "${OpenVR_VERSION_MAJOR}")
    string(REGEX REPLACE "${re_minor}" "\\1"
           OpenVR_VERSION_MINOR "${OpenVR_VERSION_MINOR}")
    string(REGEX REPLACE "${re_patch}" "\\1"
           OpenVR_VERSION_PATCH "${OpenVR_VERSION_PATCH}")

    if (OpenVR_VERSION_MAJOR AND OpenVR_VERSION_MINOR AND OpenVR_VERSION_PATCH)
      set(OpenVR_VERSION
          "${OpenVR_VERSION_MAJOR}.${OpenVR_VERSION_MINOR}.${OpenVR_VERSION_PATCH}")
    endif ()
  endif ()

  ## Find the library
  find_library(OpenVR_LIBRARY_RELEASE NAMES openvr_api)

  # OpenVR uses a highly non-standard additional suffix to mark debug libraries
  list(TRANSFORM CMAKE_FIND_LIBRARY_SUFFIXES APPEND ".dbg")
  find_library(OpenVR_LIBRARY_DEBUG NAMES openvr_api)

  select_library_configurations(OpenVR)

  ## Perform all the standard required, version, etc. argument checks.
  find_package_handle_standard_args(
    OpenVR
    REQUIRED_VARS OpenVR_LIBRARY OpenVR_INCLUDE_DIR
    VERSION_VAR OpenVR_VERSION
    HANDLE_VERSION_RANGE
    HANDLE_COMPONENTS
  )

  ## Create OpenVR::OpenVR imported target.
  if (OpenVR_FOUND AND NOT OpenVR::OpenVR)
    add_library(OpenVR::OpenVR UNKNOWN IMPORTED)
    target_include_directories(OpenVR::OpenVR INTERFACE "${OpenVR_INCLUDE_DIR}")
    set_target_properties(
      OpenVR::OpenVR PROPERTIES IMPORTED_LOCATION "${OpenVR_LIBRARY}"
    )

    foreach (cfg IN ITEMS RELEASE DEBUG)
      if (OpenVR_LIBRARY_${cfg})
        set_property(
          TARGET OpenVR::OpenVR APPEND PROPERTY IMPORTED_CONFIGURATIONS ${cfg}
        )
        set_target_properties(
          OpenVR::OpenVR PROPERTIES
          IMPORTED_LOCATION_${cfg} "${OpenVR_LIBRARY_${cfg}}"
        )
      endif ()
    endforeach ()
  endif ()

  ## Export whitelisted variables
  set(OpenVR_FOUND "${OpenVR_FOUND}" PARENT_SCOPE)
  set(OpenVR_VERSION "${OpenVR_VERSION}" PARENT_SCOPE)
endfunction()

_OpenVR_find()

function(_OpenVR_find)
endfunction()

function(_OpenVR_find)
endfunction()
</code>```

Title: Linking OpenVR through VCPKG via CMAKE

Body:
I have Installed OpenVR through vcpkg and am trying to link it via CMAKE, the issue is that I don't know how to do it, nor can I find any info on how to.

Unlike other packages where once installed it tells you how to link via CMAKE by using find_package and target_link_libraries, OpenVR doesn't. I initially assumed that

find_package(openvr CONFIG REQUIRED)
target_link_libraries(${Proj_Name} PRIVATE openvr::openvr)

would work but instead I get the error

CMake Error at C:/dev/vcpkg/vcpkg/scripts/buildsystems/vcpkg.cmake:793 (_find_package):
Could not find a package configuration file provided by "openvr" with any
of the following names:

openvrConfig.cmake
openvr-config.cmake

Add the installation prefix of "openvr" to CMAKE_PREFIX_PATH or set
"openvr_DIR" to a directory containing one of the above files.  If "openvr"
provides a separate development package or SDK, be sure it has been
installed.

Usually vcpkg.cmake provides CMAKE with the config.cmake files but not for OpenVR, so how do i link it properly?

Body:
Here is a find module that seems to work. OpenVR does some very non-standard things with its debug library naming. I tested this on Linux, and it works, but I do not have easy access to a Windows machine right now. Let me see the error message if it fails and I can try to fix it.

You'll use it like this, from the top-level CMakeLists.txt

# ./CMakeLists.txt
cmake_minimum_required(VERSION 3.22)
project(test)

list(APPEND CMAKE_MODULE_PATH "${CMAKE_CURRENT_SOURCE_DIR}/cmake")

find_package(OpenVR REQUIRED)

add_executable(main main.cpp)
target_link_libraries(main PRIVATE OpenVR::OpenVR)

And then just put the following find module in cmake/FindOpenVR.cmake:

# cmake/FindOpenVR.cmake
cmake_minimum_required(VERSION 3.22)

function(_OpenVR_find)
  include(FindPackageHandleStandardArgs)
  include(SelectLibraryConfigurations)

  ## Find the include path
  find_path(OpenVR_INCLUDE_DIR NAMES openvr.h)

  ## Determine version by scanning header
  if (OpenVR_INCLUDE_DIR)
    set(openvr_header "${OpenVR_INCLUDE_DIR}/openvr.h")

    set(re_major "^\tstatic const uint32_t k_nSteamVRVersionMajor = ([0-9]+).*;$")
    set(re_minor "^\tstatic const uint32_t k_nSteamVRVersionMinor = ([0-9]+).*;$")
    set(re_patch "^\tstatic const uint32_t k_nSteamVRVersionBuild = ([0-9]+).*;$")

    file(STRINGS "${openvr_header}" OpenVR_VERSION_MAJOR REGEX "${re_major}")
    file(STRINGS "${openvr_header}" OpenVR_VERSION_MINOR REGEX "${re_minor}")
    file(STRINGS "${openvr_header}" OpenVR_VERSION_PATCH REGEX "${re_patch}")

    string(REGEX REPLACE "${re_major}" "\\1"
           OpenVR_VERSION_MAJOR "${OpenVR_VERSION_MAJOR}")
    string(REGEX REPLACE "${re_minor}" "\\1"
           OpenVR_VERSION_MINOR "${OpenVR_VERSION_MINOR}")
    string(REGEX REPLACE "${re_patch}" "\\1"
           OpenVR_VERSION_PATCH "${OpenVR_VERSION_PATCH}")

    if (OpenVR_VERSION_MAJOR AND OpenVR_VERSION_MINOR AND OpenVR_VERSION_PATCH)
      set(OpenVR_VERSION
          "${OpenVR_VERSION_MAJOR}.${OpenVR_VERSION_MINOR}.${OpenVR_VERSION_PATCH}")
    endif ()
  endif ()

  ## Find the library
  find_library(OpenVR_LIBRARY_RELEASE NAMES openvr_api)

  # OpenVR uses a highly non-standard additional suffix to mark debug libraries
  list(TRANSFORM CMAKE_FIND_LIBRARY_SUFFIXES APPEND ".dbg")
  find_library(OpenVR_LIBRARY_DEBUG NAMES openvr_api)

  select_library_configurations(OpenVR)

  ## Perform all the standard required, version, etc. argument checks.
  find_package_handle_standard_args(
    OpenVR
    REQUIRED_VARS OpenVR_LIBRARY OpenVR_INCLUDE_DIR
    VERSION_VAR OpenVR_VERSION
    HANDLE_VERSION_RANGE
    HANDLE_COMPONENTS
  )

  ## Create OpenVR::OpenVR imported target.
  if (OpenVR_FOUND AND NOT OpenVR::OpenVR)
    add_library(OpenVR::OpenVR UNKNOWN IMPORTED)
    target_include_directories(OpenVR::OpenVR INTERFACE "${OpenVR_INCLUDE_DIR}")
    set_target_properties(
      OpenVR::OpenVR PROPERTIES IMPORTED_LOCATION "${OpenVR_LIBRARY}"
    )

    foreach (cfg IN ITEMS RELEASE DEBUG)
      if (OpenVR_LIBRARY_${cfg})
        set_property(
          TARGET OpenVR::OpenVR APPEND PROPERTY IMPORTED_CONFIGURATIONS ${cfg}
        )
        set_target_properties(
          OpenVR::OpenVR PROPERTIES
          IMPORTED_LOCATION_${cfg} "${OpenVR_LIBRARY_${cfg}}"
        )
      endif ()
    endforeach ()
  endif ()

  ## Export whitelisted variables
  set(OpenVR_FOUND "${OpenVR_FOUND}" PARENT_SCOPE)
  set(OpenVR_VERSION "${OpenVR_VERSION}" PARENT_SCOPE)
endfunction()

_OpenVR_find()

function(_OpenVR_find)
endfunction()

function(_OpenVR_find)
endfunction()


问:
flutter - Image picker - need to convert 'List<XFile>' to 'List<File>?'
I'm using image_picker package to get images and show them in a carousel.

```<code>    postNotifier(true).selectedPostImages != null
        ? Container(
            height: 400,
            width: 400,
            child: CarouselSlider.builder(
                options: CarouselOptions(height: 300),
                itemCount: selectedImagesList!.length,
                itemBuilder: (BuildContext context, index, realIndex) {
                  final selectedImage = selectedImagesList[index];
                  return buildImage(selectedImage, index);
                }),
          )
        : const SizedBox(
            height: 0,
          ),
</code>```

and I'm getting the images for carousel builder from this buildImage() widget

```<code>  Widget buildImage(File selectedImage, int index) => Container(
        margin: EdgeInsets.symmetric(horizontal: 12),
        color: Colors.grey,
        child: Image.file(selectedImage),
      );
</code>```

my PostNotifier class in another file

```<code>class PostNotifier extends ChangeNotifier {

  List<File>? _selectedPostImages;
  List<File>? get selectedPostImages => _selectedPostImages;

  Future<List?> pickPostImages() async {
    final _imageList = await ImagePicker().pickMultiImage(imageQuality: 5);
    if (_imageList != null) {
      _selectedPostImages = _imageList; //I'm getting the error here.
      notifyListeners();
    }
  }
</code>```

The error flutter shows is:

A value of type 'List' can't be assigned to a variable of type 'List?'.
Try changing the type of the variable, or casting the right-hand type to 'List?'.

I tried using flutter_absolute_path as suggested in other answers in such a situation to get the path and set it to the array but when I run on emulator I get this error

```<code>The plugin `flutter_absolute_path` uses a deprecated version of the Android embedding.
To avoid unexpected runtime failures, or future build failures, try to see if this plugin supports the Android V2 embedding. Otherwise, consider removing it since a future release of Flutter will remove these deprecated APIs.
If you are plugin author, take a look at the docs for migrating the plugin to the V2 embedding: https://flutter.dev/go/android-plugin-migration.
Launching lib\main.dart on Android SDK built for x86 in debug mode...
lib\main.dart:1
/C:/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_absolute_path-1.0.6/lib/flutter_absolute_path.dart:11:23: Error: Null safety features are disabled for this library.
Try removing the package language version or setting the language version to 2.12 or higher.
  static Future<String?> getAbsolutePath(String uri) async {
                      ^
Error: Cannot run with sound null safety, because the following dependencies
don't support null safety:

 - package:flutter_absolute_path

For solutions, see https://dart.dev/go/unsound-null-safety
: Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't.
lib/…/notifier/post.notifier.dart:101
        File tempFile = File(filePath);
                             ^
/C:/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_absolute_path-1.0.6/lib/flutter_absolute_path.dart:15:17: Error: Null safety features are disabled for this library.
Try removing the package language version or setting the language version to 2.12 or higher.
    final String? path = await _channel.invokeMethod('getAbsolutePath', params);
                ^
2

FAILURE: Build failed with an exception.

* Where:
Script 'C:\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1102

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1m 48s
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)
</code>```

and the app never opens on emualtor.

What do I do? I want to implement this multi image picker.

答:
XFile is a image_picker package's wrapper for the picked file(s). Hence, you obtain a List<XFile> from await ImagePicker().pickMultiImage() call, but try to assign it to a _selectedPostImages field that expects List<File> which produces the type mismatch error.

So, you can either:

Rewrite the _selectedPostImages to expect List<XFile>, like List<XFile>? _selectedPostImages.

Map the _imageList to a list of File, like _selectedPostImages = _imageList.map<File>((xfile) => File(xfile.path)).toList()

Body:
I'm using image_picker package to get images and show them in a carousel.

    postNotifier(true).selectedPostImages != null
        ? Container(
            height: 400,
            width: 400,
            child: CarouselSlider.builder(
                options: CarouselOptions(height: 300),
                itemCount: selectedImagesList!.length,
                itemBuilder: (BuildContext context, index, realIndex) {
                  final selectedImage = selectedImagesList[index];
                  return buildImage(selectedImage, index);
                }),
          )
        : const SizedBox(
            height: 0,
          ),

and I'm getting the images for carousel builder from this buildImage() widget

  Widget buildImage(File selectedImage, int index) => Container(
        margin: EdgeInsets.symmetric(horizontal: 12),
        color: Colors.grey,
        child: Image.file(selectedImage),
      );

my PostNotifier class in another file

class PostNotifier extends ChangeNotifier {

  List<File>? _selectedPostImages;
  List<File>? get selectedPostImages => _selectedPostImages;

  Future<List?> pickPostImages() async {
    final _imageList = await ImagePicker().pickMultiImage(imageQuality: 5);
    if (_imageList != null) {
      _selectedPostImages = _imageList; //I'm getting the error here.
      notifyListeners();
    }
  }

The error flutter shows is:

A value of type 'List' can't be assigned to a variable of type 'List?'.
Try changing the type of the variable, or casting the right-hand type to 'List?'.

I tried using flutter_absolute_path as suggested in other answers in such a situation to get the path and set it to the array but when I run on emulator I get this error

The plugin `flutter_absolute_path` uses a deprecated version of the Android embedding.
To avoid unexpected runtime failures, or future build failures, try to see if this plugin supports the Android V2 embedding. Otherwise, consider removing it since a future release of Flutter will remove these deprecated APIs.
If you are plugin author, take a look at the docs for migrating the plugin to the V2 embedding: https://flutter.dev/go/android-plugin-migration.
Launching lib\main.dart on Android SDK built for x86 in debug mode...
lib\main.dart:1
/C:/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_absolute_path-1.0.6/lib/flutter_absolute_path.dart:11:23: Error: Null safety features are disabled for this library.
Try removing the package language version or setting the language version to 2.12 or higher.
  static Future<String?> getAbsolutePath(String uri) async {
                      ^
Error: Cannot run with sound null safety, because the following dependencies
don't support null safety:

 - package:flutter_absolute_path

For solutions, see https://dart.dev/go/unsound-null-safety
: Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't.
lib/…/notifier/post.notifier.dart:101
        File tempFile = File(filePath);
                             ^
/C:/flutter/.pub-cache/hosted/pub.dartlang.org/flutter_absolute_path-1.0.6/lib/flutter_absolute_path.dart:15:17: Error: Null safety features are disabled for this library.
Try removing the package language version or setting the language version to 2.12 or higher.
    final String? path = await _channel.invokeMethod('getAbsolutePath', params);
                ^
2

FAILURE: Build failed with an exception.

* Where:
Script 'C:\flutter\packages\flutter_tools\gradle\flutter.gradle' line: 1102

* What went wrong:
Execution failed for task ':app:compileFlutterBuildDebug'.
> Process 'command 'C:\flutter\bin\flutter.bat'' finished with non-zero exit value 1

* Try:
> Run with --stacktrace option to get the stack trace.
> Run with --info or --debug option to get more log output.
> Run with --scan to get full insights.

* Get more help at https://help.gradle.org

BUILD FAILED in 1m 48s
Exception: Gradle task assembleDebug failed with exit code 1
Exited (sigterm)

and the app never opens on emualtor.

What do I do? I want to implement this multi image picker.


问:
Get Group sum not using group.Sum() in linq
The following query works, but I want to get the same result without using grp.Sum(). Can we do it?</p>
```<code>from item in (await VehicleReplaceCostDataAsync())
                group item by (item.type, item.size, item.ADA, item.eseq) into grp
                orderby (grp.Key.eseq, grp.Key.size, grp.Key.ADA)
                select new VehicleReplacementCost
                {
                    type = grp.Key.type,
                    size = grp.Key.size,
                    ADA = grp.Key.ADA,
                    count = grp.Sum(x => x.count),
                    cost = grp.Sum(x => x.cost),
                    Fcount = grp.Sum(x => x.Fcount),
                    Fcost = grp.Sum(x => x.Fcost),
                    eseq = grp.Key.eseq,
                }).ToList();
</code>```

答:
Thanks for the answer from Astrid.  It looks like a good one, but I didn't test it.  My colleague gave this solution instead by using yield:</p>
```<code>var groups = costs
                .GroupBy(type => (type.SystemId, type.Type, type.Size, type.ADA, type.Eseq))
                .OrderBy(group => (group.Key.SystemId, group.Key.Eseq, group.Key.Size, group.Key.ADA));

            foreach (var group in groups)
            {
                var result = new ProgramGuideVehicleCostRow
                {
                    SystemId = group.Key.SystemId,
                    Type = group.Key.Type,
                    Size = group.Key.Size,
                    ADA = group.Key.ADA,
                };
                foreach (var row in group)
                {
                    result.Cost += row.Cost;
                    result.Fcost += row.Fcost;
                    result.Count += row.Count;
                    result.Fcount += row.Fcount;
                }
                yield return result;
            }
</code>```

Body:
The following query works, but I want to get the same result without using grp.Sum(). Can we do it?

from item in (await VehicleReplaceCostDataAsync())
                group item by (item.type, item.size, item.ADA, item.eseq) into grp
                orderby (grp.Key.eseq, grp.Key.size, grp.Key.ADA)
                select new VehicleReplacementCost
                {
                    type = grp.Key.type,
                    size = grp.Key.size,
                    ADA = grp.Key.ADA,
                    count = grp.Sum(x => x.count),
                    cost = grp.Sum(x => x.cost),
                    Fcount = grp.Sum(x => x.Fcount),
                    Fcost = grp.Sum(x => x.Fcost),
                    eseq = grp.Key.eseq,
                }).ToList();

Body:
Thanks for the answer from Astrid.  It looks like a good one, but I didn't test it.  My colleague gave this solution instead by using yield:

var groups = costs
                .GroupBy(type => (type.SystemId, type.Type, type.Size, type.ADA, type.Eseq))
                .OrderBy(group => (group.Key.SystemId, group.Key.Eseq, group.Key.Size, group.Key.ADA));

            foreach (var group in groups)
            {
                var result = new ProgramGuideVehicleCostRow
                {
                    SystemId = group.Key.SystemId,
                    Type = group.Key.Type,
                    Size = group.Key.Size,
                    ADA = group.Key.ADA,
                };
                foreach (var row in group)
                {
                    result.Cost += row.Cost;
                    result.Fcost += row.Fcost;
                    result.Count += row.Count;
                    result.Fcount += row.Fcount;
                }
                yield return result;
            }


问:
Optimizing/Reducing For-loops
I am learning C and I want to have an idea on how can I reduce the for-loops, to make it more presentable.

```<code>#include<stdio.h>

int main() {

char input[81];
int i;
char input2[9][9];
int col,row;
printf("Enter sudoku board:");
scanf("%s",&input);

for (i=0;i<9;i++) {
    for (col=0;col<9;col++)
        input2[0][col]=input[i];
    for (col=0;col<9;col++)
        input2[1][col]=input[i];
    for (col=0;col<9;col++)
        input2[2][col]=input[i];
    for (col=0;col<9;col++)
        input2[3][col]=input[i];
    for (col=0;col<9;col++)
        input2[4][col]=input[i];
    for (col=0;col<9;col++)
        input2[5][col]=input[i];
    for (col=0;col<9;col++)
        input2[6][col]=input[i];
    for (col=0;col<9;col++)
        input2[7][col]=input[i];
    for (col=0;col<9;col++)
        input2[8][col]=input[i];
}
</code>```

this shows that the user would enter 81 numbers in an array then the numbers entered will be transferred to a 9x9 array. thanks in advance!:)

答:
As a first step below code should work -

```<code>int i,j;
for(i=0;i<9;i++)
{
    for(j=0;j<9;j++)
    {
        input2[i][j]=input[i];

    }
}
</code>```

EDIT: I have given solution for making the for loops 'more readable', to do whatever functionality OP mentioned. Have not suggested any thing other than that like whether his original code is correct or incorrect?

Title: Optimizing/Reducing For-loops

Body:
I am learning C and I want to have an idea on how can I reduce the for-loops, to make it more presentable.

#include<stdio.h>

int main() {

char input[81];
int i;
char input2[9][9];
int col,row;
printf("Enter sudoku board:");
scanf("%s",&input);

for (i=0;i<9;i++) {
    for (col=0;col<9;col++)
        input2[0][col]=input[i];
    for (col=0;col<9;col++)
        input2[1][col]=input[i];
    for (col=0;col<9;col++)
        input2[2][col]=input[i];
    for (col=0;col<9;col++)
        input2[3][col]=input[i];
    for (col=0;col<9;col++)
        input2[4][col]=input[i];
    for (col=0;col<9;col++)
        input2[5][col]=input[i];
    for (col=0;col<9;col++)
        input2[6][col]=input[i];
    for (col=0;col<9;col++)
        input2[7][col]=input[i];
    for (col=0;col<9;col++)
        input2[8][col]=input[i];
}

this shows that the user would enter 81 numbers in an array then the numbers entered will be transferred to a 9x9 array. thanks in advance!:)

Body:
As a first step below code should work -

int i,j;
for(i=0;i<9;i++)
{
    for(j=0;j<9;j++)
    {
        input2[i][j]=input[i];

    }
}

EDIT: I have given solution for making the for loops 'more readable', to do whatever functionality OP mentioned. Have not suggested any thing other than that like whether his original code is correct or incorrect?


问:
Finding the length of RNA given certain conditions using Python
I'm tasked with designing a function which recognises the length of the RNA code (excluding the start and stop codons). The function must also determine if their code is actually valid (must contain AUG as a start codon and UGA, UAA, or UAG at the end)
Note: RNA starts with a start codon AUG and ends with UGA, UAA, or UAG
The function must return "Not readable RNA code" if the above conditions are not met.

```<code>def rna_length(mrna):
    start_trans = 'AUG'

    end_trans1 = 'UAA'
    end_trans2 = 'UGA'
    end_trans3 = 'UAG'

    if ((mrna[0:3]!=start_trans) and (mrna [-3:]!=end_trans1 or end_trans2 or end_trans3)):

        return "Not readable RNA code"

    else:
        (mrna[0:3]==start_trans) and (mrna [-3:]==end_trans1 or end_trans2 or end_trans3)

        length = len(mrna[3:-3])

        return length
</code>```

But this code won't work for 'AUGAGGCACCUUCUGCUCCUUAC'. It returns the length instead of "Not readable'

答:
def rna_length(mrna):
    length_of_code = len(mrna)

    start_codon = mrna[:3]
    stop_codon = mrna[-3:]

    if (start_codon == 'AUG' and (stop_codon in ('UAG', 'UAA', 'UGA'))):
        return print(f"rna_length('{mrna}') == {length_of_code - 6}")
    else:
        return "Not readable RNA code"
```

Body:
I'm tasked with designing a function which recognises the length of the RNA code (excluding the start and stop codons). The function must also determine if their code is actually valid (must contain AUG as a start codon and UGA, UAA, or UAG at the end)
Note: RNA starts with a start codon AUG and ends with UGA, UAA, or UAG
The function must return "Not readable RNA code" if the above conditions are not met.

def rna_length(mrna):
    start_trans = 'AUG'

    end_trans1 = 'UAA'
    end_trans2 = 'UGA'
    end_trans3 = 'UAG'

    if ((mrna[0:3]!=start_trans) and (mrna [-3:]!=end_trans1 or end_trans2 or end_trans3)):

        return "Not readable RNA code"

    else:
        (mrna[0:3]==start_trans) and (mrna [-3:]==end_trans1 or end_trans2 or end_trans3)

        length = len(mrna[3:-3])

        return length

But this code won't work for 'AUGAGGCACCUUCUGCUCCUUAC'. It returns the length instead of "Not readable'


问:
How to push 1 D array to a column
I'm trying to push 1D array to a column but Im keep getting that error "Exception: The parameters (number[]) don't match the method signature for SpreadsheetApp.Range.setValues." which what I understood is that I cant use setValues for 1D array, it has to be 2D array or more.

Here is my code.

```<code>  var range = ss.getRange(3,5,ss.getLastRow()-2).getValues();
  var qValues = [];
  for( var i=0; i<range.length; i++ ) {
    qValues.push([range[i][0]]); // index 0 = column E.
  }

  var values = ss.getRange(3,14,ss.getLastRow()-2,11).getValues(); // N3:T??
  var results = [];
  for(var i=0; i<values.length; i++ ) {
    results.push((([values[i][0]+values[i][2]+values[i][4]+values[i][6]+values[i][8]+values[i][10]])*120*qValues[i][0])/1000); // index 0 = column N, etc.
  }

   ss.getRange(3, 27,).setValues(results);

</code>```

I tried to add

```<code>results.push([""]);
</code>```

before the setValues statement but it didn't work as well

If you need more info please let me know.

Thank you

答:
Basically you need to convert your 1D array into 2D array to put it into a column. It can be done this way:

var arr = [1, 2, 3, 4];
var arr_2d = arr.map(x => [x]);

console.log(arr_2d); // > [[1],[2],[3],[4]]```
</div>
</div>
</p>
<p>For your case the last line could be something like this:</p>
```ss.getRange(3, 27, results.length, results[0].length).setValues(results.map(x => [x]));
```
<p>But I don't know if your array is a valid array and what the range you want to fill. Probably in your case the array is not array at all.</p>
<p>Could you show the contents of the array <code>results</code>?</p>
```console.log(results)
```
<p>Because this operation looks extremely weird:</p>
```([ values[i][0] +
   values[i][2] +
   values[i][4] +
   values[i][6] +
   values[i][8] +
   values[i][10] ]) * 120 * qValues[i][0]
```
<p>I frankly don't understand what you're trying to gain.</p>
<p>Perhaps there shouldn't be the brackets <code>[...]</code>:</p>
```( values[i][0] +
  values[i][2] +
  values[i][4] +
  values[i][6] +
  values[i][8] +
  values[i][10] ) * 120 * qValues[i][0]
```

Title: How to push 1 D array to a column

Body:
I'm trying to push 1D array to a column but Im keep getting that error "Exception: The parameters (number[]) don't match the method signature for SpreadsheetApp.Range.setValues." which what I understood is that I cant use setValues for 1D array, it has to be 2D array or more.

Here is my code.

  var range = ss.getRange(3,5,ss.getLastRow()-2).getValues();
  var qValues = [];
  for( var i=0; i<range.length; i++ ) {
    qValues.push([range[i][0]]); // index 0 = column E.
  }

  var values = ss.getRange(3,14,ss.getLastRow()-2,11).getValues(); // N3:T??
  var results = [];
  for(var i=0; i<values.length; i++ ) {
    results.push((([values[i][0]+values[i][2]+values[i][4]+values[i][6]+values[i][8]+values[i][10]])*120*qValues[i][0])/1000); // index 0 = column N, etc.
  }

   ss.getRange(3, 27,).setValues(results);

I tried to add

results.push([""]);

before the setValues statement but it didn't work as well

If you need more info please let me know.

Thank you

Body:
Basically you need to convert your 1D array into 2D array to put it into a column. It can be done this way:

var arr = [1, 2, 3, 4];
var arr_2d = arr.map(x => [x]);

console.log(arr_2d); // > [[1],[2],[3],[4]]

For your case the last line could be something like this:

ss.getRange(3, 27, results.length, results[0].length).setValues(results.map(x => [x]));

But I don't know if your array is a valid array and what the range you want to fill. Probably in your case the array is not array at all.

Could you show the contents of the array results?

console.log(results)

Because this operation looks extremely weird:

([ values[i][0] +
   values[i][2] +
   values[i][4] +
   values[i][6] +
   values[i][8] +
   values[i][10] ]) * 120 * qValues[i][0]

I frankly don't understand what you're trying to gain.

Perhaps there shouldn't be the brackets [...]:

( values[i][0] +
  values[i][2] +
  values[i][4] +
  values[i][6] +
  values[i][8] +
  values[i][10] ) * 120 * qValues[i][0]


问:
How can I get this type carosol slider in flutter?
Hello Here I need a carosol slider like this one,
In full screen view height 250-300, width Get.width.

Can anyone help me please to get this carosol slider in flutter.

答:
I made this widget, I haven't tested it with Images, but in principle it works:

class Carrousel extends StatelessWidget {
  Carrousel({
    Key? key,
    required this.children,
    required this.height,
    required this.delay,
    this.selectedColor,
    this.color,
    this.fit = BoxFit.contain,
  })  : assert(children.isNotEmpty),
        super(key: key);

  final List<Widget> children;
  final double height;
  final Color? selectedColor;
  final Color? color;
  final Duration delay;
  final BoxFit fit;

  @override
  Widget build(BuildContext context) {
    bool justChanged = false;
    final width = MediaQuery.of(context).size.width;
    final currentChild = ValueNotifier<Widget>(children.first);
    Timer.periodic(
      delay,
      (_) {
        int newIndex = children.indexOf(currentChild.value) + 1;
        if (newIndex == children.length) {
          newIndex = 0;
        }
        if (!justChanged) {
          currentChild.value = children[newIndex];
        } else {
          justChanged = false;
        }
      },
    );
    return SizedBox(
      width: width,
      height: height,
      child: Stack(
        children: [
          ValueListenableBuilder<Widget>(
            valueListenable: currentChild,
            builder: (context, child, _) {
              return SizedBox(
                width: width,
                height: height,
                child: child,
              );
            },
          ),
          SizedBox(
            width: width,
            child: Align(
              alignment: Alignment.bottomCenter,
              child: ValueListenableBuilder<Widget>(
                valueListenable: currentChild,
                builder: (context, _currentChild, __) {
                  return Row(
                    mainAxisSize: MainAxisSize.min,
                    children: children.map<Widget>((child) {
                      Color _color = color ?? Colors.grey;
                      if (child == _currentChild) {
                        _color = selectedColor ?? Colors.white;
                      }
                      return Card(
                        shape: const CircleBorder(),
                        elevation: 7,
                        child: SizedBox(
                          height: height * 0.05,
                          child: CircleAvatar(
                            backgroundColor: _color,
                            child: InkWell(
                              customBorder: const CircleBorder(),
                              onTap: () {
                                justChanged = true;
                                currentChild.value = child;
                              },
                            ),
                          ),
                        ),
                      );
                    }).toList(),
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
}

```

  Here for you to try:
<pre class="lang-dart prettyprint-override"><code>import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Carrousel',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    final random = Random(DateTime.now().millisecondsSinceEpoch);
    final lenght = random.nextInt(5) + 2;
    final List<Color> colors = [];
    for (int i = 0; i < lenght; i++) {
      colors.add(Color.fromRGBO(
        random.nextInt(0xff),
        random.nextInt(0xff),
        random.nextInt(0xff),
        1,
      ));
    }
    return Scaffold(
      appBar: AppBar(
        title: const Text('Carrousel'),
      ),
      body: Align(
        alignment: Alignment.topCenter,
        child: Carrousel(
          height: 300,
          delay: const Duration(seconds: 5),
          children: colorsWidgets(colors),
        ),
      ),
    );
  }

  List<Widget> colorsWidgets(List<Color> colors) {
    return colors.map<Widget>(
      (color) {
        return Container(color: color);
      },
    ).toList();
  }
}

class Carrousel extends StatelessWidget {
  Carrousel({
    Key? key,
    required this.children,
    required this.height,
    required this.delay,
    this.selectedColor,
    this.color,
    this.fit = BoxFit.contain,
  })  : assert(children.isNotEmpty),
        super(key: key);

  final List<Widget> children;
  final double height;
  final Color? selectedColor;
  final Color? color;
  final Duration delay;
  final BoxFit fit;

  @override
  Widget build(BuildContext context) {
    bool justChanged = false;
    final width = MediaQuery.of(context).size.width;
    final currentChild = ValueNotifier<Widget>(children.first);
    Timer.periodic(
      delay,
      (_) {
        int newIndex = children.indexOf(currentChild.value) + 1;
        if (newIndex == children.length) {
          newIndex = 0;
        }
        if (!justChanged) {
          currentChild.value = children[newIndex];
        } else {
          justChanged = false;
        }
      },
    );
    return SizedBox(
      width: width,
      height: height,
      child: Stack(
        children: [
          ValueListenableBuilder<Widget>(
            valueListenable: currentChild,
            builder: (context, child, _) {
              return SizedBox(
                width: width,
                height: height,
                child: child,
              );
            },
          ),
          SizedBox(
            width: width,
            child: Align(
              alignment: Alignment.bottomCenter,
              child: ValueListenableBuilder<Widget>(
                valueListenable: currentChild,
                builder: (context, _currentChild, __) {
                  return Row(
                    mainAxisSize: MainAxisSize.min,
                    children: children.map<Widget>((child) {
                      Color _color = color ?? Colors.grey;
                      if (child == _currentChild) {
                        _color = selectedColor ?? Colors.white;
                      }
                      return Card(
                        shape: const CircleBorder(),
                        elevation: 7,
                        child: SizedBox(
                          height: height * 0.05,
                          child: CircleAvatar(
                            backgroundColor: _color,
                            child: InkWell(
                              customBorder: const CircleBorder(),
                              onTap: () {
                                justChanged = true;
                                currentChild.value = child;
                              },
                            ),
                          ),
                        ),
                      );
                    }).toList(),
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
}

</code>```

Body:
I made this widget, I haven't tested it with Images, but in principle it works:

class Carrousel extends StatelessWidget {
  Carrousel({
    Key? key,
    required this.children,
    required this.height,
    required this.delay,
    this.selectedColor,
    this.color,
    this.fit = BoxFit.contain,
  })  : assert(children.isNotEmpty),
        super(key: key);

  final List<Widget> children;
  final double height;
  final Color? selectedColor;
  final Color? color;
  final Duration delay;
  final BoxFit fit;

  @override
  Widget build(BuildContext context) {
    bool justChanged = false;
    final width = MediaQuery.of(context).size.width;
    final currentChild = ValueNotifier<Widget>(children.first);
    Timer.periodic(
      delay,
      (_) {
        int newIndex = children.indexOf(currentChild.value) + 1;
        if (newIndex == children.length) {
          newIndex = 0;
        }
        if (!justChanged) {
          currentChild.value = children[newIndex];
        } else {
          justChanged = false;
        }
      },
    );
    return SizedBox(
      width: width,
      height: height,
      child: Stack(
        children: [
          ValueListenableBuilder<Widget>(
            valueListenable: currentChild,
            builder: (context, child, _) {
              return SizedBox(
                width: width,
                height: height,
                child: child,
              );
            },
          ),
          SizedBox(
            width: width,
            child: Align(
              alignment: Alignment.bottomCenter,
              child: ValueListenableBuilder<Widget>(
                valueListenable: currentChild,
                builder: (context, _currentChild, __) {
                  return Row(
                    mainAxisSize: MainAxisSize.min,
                    children: children.map<Widget>((child) {
                      Color _color = color ?? Colors.grey;
                      if (child == _currentChild) {
                        _color = selectedColor ?? Colors.white;
                      }
                      return Card(
                        shape: const CircleBorder(),
                        elevation: 7,
                        child: SizedBox(
                          height: height * 0.05,
                          child: CircleAvatar(
                            backgroundColor: _color,
                            child: InkWell(
                              customBorder: const CircleBorder(),
                              onTap: () {
                                justChanged = true;
                                currentChild.value = child;
                              },
                            ),
                          ),
                        ),
                      );
                    }).toList(),
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
}

  Here for you to try:

import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Carrousel',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({Key? key}) : super(key: key);

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  @override
  Widget build(BuildContext context) {
    final random = Random(DateTime.now().millisecondsSinceEpoch);
    final lenght = random.nextInt(5) + 2;
    final List<Color> colors = [];
    for (int i = 0; i < lenght; i++) {
      colors.add(Color.fromRGBO(
        random.nextInt(0xff),
        random.nextInt(0xff),
        random.nextInt(0xff),
        1,
      ));
    }
    return Scaffold(
      appBar: AppBar(
        title: const Text('Carrousel'),
      ),
      body: Align(
        alignment: Alignment.topCenter,
        child: Carrousel(
          height: 300,
          delay: const Duration(seconds: 5),
          children: colorsWidgets(colors),
        ),
      ),
    );
  }

  List<Widget> colorsWidgets(List<Color> colors) {
    return colors.map<Widget>(
      (color) {
        return Container(color: color);
      },
    ).toList();
  }
}

class Carrousel extends StatelessWidget {
  Carrousel({
    Key? key,
    required this.children,
    required this.height,
    required this.delay,
    this.selectedColor,
    this.color,
    this.fit = BoxFit.contain,
  })  : assert(children.isNotEmpty),
        super(key: key);

  final List<Widget> children;
  final double height;
  final Color? selectedColor;
  final Color? color;
  final Duration delay;
  final BoxFit fit;

  @override
  Widget build(BuildContext context) {
    bool justChanged = false;
    final width = MediaQuery.of(context).size.width;
    final currentChild = ValueNotifier<Widget>(children.first);
    Timer.periodic(
      delay,
      (_) {
        int newIndex = children.indexOf(currentChild.value) + 1;
        if (newIndex == children.length) {
          newIndex = 0;
        }
        if (!justChanged) {
          currentChild.value = children[newIndex];
        } else {
          justChanged = false;
        }
      },
    );
    return SizedBox(
      width: width,
      height: height,
      child: Stack(
        children: [
          ValueListenableBuilder<Widget>(
            valueListenable: currentChild,
            builder: (context, child, _) {
              return SizedBox(
                width: width,
                height: height,
                child: child,
              );
            },
          ),
          SizedBox(
            width: width,
            child: Align(
              alignment: Alignment.bottomCenter,
              child: ValueListenableBuilder<Widget>(
                valueListenable: currentChild,
                builder: (context, _currentChild, __) {
                  return Row(
                    mainAxisSize: MainAxisSize.min,
                    children: children.map<Widget>((child) {
                      Color _color = color ?? Colors.grey;
                      if (child == _currentChild) {
                        _color = selectedColor ?? Colors.white;
                      }
                      return Card(
                        shape: const CircleBorder(),
                        elevation: 7,
                        child: SizedBox(
                          height: height * 0.05,
                          child: CircleAvatar(
                            backgroundColor: _color,
                            child: InkWell(
                              customBorder: const CircleBorder(),
                              onTap: () {
                                justChanged = true;
                                currentChild.value = child;
                              },
                            ),
                          ),
                        ),
                      );
                    }).toList(),
                  );
                },
              ),
            ),
          ),
        ],
      ),
    );
  }
}


问:
Optimizing a certain query
I have a query that goes such:

bankNumber and BIC are both indexed.

```<code>SELECT * FROM `bank1` WHERE `bankNumber` <= 200000 or `BIC` = 'Berlin'
</code>```

By using the EXPLAIN, it uses both of the keys in possible_keys. I read in an article that one of the things that not to do when queries for indicies is to use OR.

I am tasked to optimize this query so that only one key gets used in the execution strategy.
What should I do in this case?

Things that I've tried:

Obviously went for AND, that did give me the desired result from EXPLAIN, but the data results are completely different.

答:
AND obviously will produce different results.  The only way to use indexes would be to union:

```<code>select bank1.* from (
    select id from bank1 where bankNumber <= 200000
    union distinct
    select id from bank1 where BIC='Berlin'
) ids
join bank1 on bank1.id=ids.id
</code>```

But I question your entire goal; is the query in fact too slow?  It doesn't seem like you would have enough bank rows that a full table scan would be that bad.

Title: Optimizing a certain query

Body:
I have a query that goes such:

bankNumber and BIC are both indexed.

SELECT * FROM `bank1` WHERE `bankNumber` <= 200000 or `BIC` = 'Berlin'

By using the EXPLAIN, it uses both of the keys in possible_keys. I read in an article that one of the things that not to do when queries for indicies is to use OR.

I am tasked to optimize this query so that only one key gets used in the execution strategy.
What should I do in this case?

Things that I've tried:

Obviously went for AND, that did give me the desired result from EXPLAIN, but the data results are completely different.

Body:
AND obviously will produce different results.  The only way to use indexes would be to union:

select bank1.* from (
    select id from bank1 where bankNumber <= 200000
    union distinct
    select id from bank1 where BIC='Berlin'
) ids
join bank1 on bank1.id=ids.id

But I question your entire goal; is the query in fact too slow?  It doesn't seem like you would have enough bank rows that a full table scan would be that bad.


问:
How can extract an income statement from all company concepts?
All company concepts in xbrl format can be extracted with sec's RESTful api.
For example,i want to get tesla's concepts in xbrl format in 2020, get the tesla's cik and the url for api.

```<code>cik='1318605'
url = 'https://data.sec.gov/api/xbrl/companyfacts/CIK{:>010s}.json'.format(cik)
</code>```

To express financial statement in 2020 with elements fy and fp:

```<code>'fy' ==  2020 and 'fp' == 'FY'
</code>```

I write the whole python code to call sec's api:

```<code>import requests
import json
cik='1318605'
url = 'https://data.sec.gov/api/xbrl/companyfacts/CIK{:>010s}.json'.format(cik)
headers = {
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36"
          }
res = requests.get(url=url,headers=headers)
result = json.loads(res.text)
concepts_list = list(result['facts']['us-gaap'].keys())
data_concepts = result['facts']['us-gaap']

fdata = {}
for item in concepts_list:
    data = data_concepts[item]['units']
    data_units = list(data_concepts[item]['units'].keys())
    for data_units_attr in data_units:
        for record in data[data_units_attr]:
            if record['fy'] ==  2020 and record['fp'] == 'FY':
                fdata[item] = record['val']
</code>```

fdata contains all the company concepts and its value in 2020 for tesla,show part of it:

```<code>fdata
{'AccountsAndNotesReceivableNet': 334000000,
 'AccountsPayableCurrent': 6051000000,
 'AccountsReceivableNetCurrent': 1886000000,
</code>```

How can get all concepts below to income statement?I want to extract it to make an income statement.

Maybe i should add some values in dei with almost same way as above.

```<code>EntityCommonStockSharesOutstanding:959853504
EntityPublicFloat:160570000000
</code>```

It is simple to parse financial statement such as income statement from ixbrl file:

```<code>https://www.sec.gov/ix?doc=/Archives/edgar/data/0001318605/000156459021004599/tsla-10k_20201231.htm
</code>```

I can get it ,please help to replicate the annual income statement on 2020 for Tesla from sec's RESTful api,or extract the income statement from the whole instance file:

```<code>https://www.sec.gov/Archives/edgar/data/1318605/000156459021004599/0001564590-21-004599.txt
</code>```

If you tell me how to get all concepts belong to income statement ,i can fulfill the job ,with the same way  balance and cashflow statement all can be extracted.In my case the fdata contain all concepts belong to income,balance,cashflow statement,which concept in fdata belong to which financial statement? How to map every concepts into income,balance,cashflow statement?

```<code>#expression in pseudocode
income_statement = fdata[all_concepts_belong_to_income_statement]
balance_statement = fdata[all_concepts_belong_to_balance_statement]
cashflow_statement = fdata[all_concepts_belong_to_cashflow_statement]
</code>```

答:
I get a indirect way to extract income statement via SEC's api,SEC already publish all data extracted from raw xbrl file(called xbrl instance published also),the tool which parse xbrl file to form four csv files num.txt,sub.txt,pre.txt,tag.txt is not published,what i want to do is to create the tool myself.

Step1:

Download dataset from https://www.sec.gov/dera/data/financial-statement-data-sets.html on 2020,and unzip it ,we get pre.txt,num.txt,sub.txt,tag.txt.

Step2:

Create database and table pre,num,sub,tag according to fields in pre.txt,num.txt,sub.txt,tag.txt.

Step3:

Import pre.txt,num.txt,sub.txt,tag.txt into table pre,num,sub,tag.

Step4:

Query in my postgresql:

```<code>the adsh number for tesla's financial statement on 2020 is `0001564590-21-004599`

\set accno  '0001564590-21-004599'
select tag,value from num where adsh=:'accno' and ddate = '2020-12-31' and qtrs=4  and tag in
(select tag from pre where adsh=:'accno' and stmt='IS');
                                             tag                                             |      value
---------------------------------------------------------------------------------------------+------------------
 NetIncomeLoss                                                                               |   721000000.0000
 OperatingLeasesIncomeStatementLeaseRevenue                                                  |  1052000000.0000
 GrossProfit                                                                                |  6630000000.0000
 InterestExpense                                                                             |   748000000.0000
 CostOfRevenue                                                                               | 24906000000.0000
 WeightedAverageNumberOfSharesOutstandingBasic                                               |   933000000.0000
 IncomeLossFromContinuingOperationsBeforeIncomeTaxesExtraordinaryItemsNoncontrollingInterest |  1154000000.0000
 EarningsPerShareDiluted                                                                     |           0.6400
 ProfitLoss                                                                                |   862000000.0000
 OperatingExpenses                                                                           |  4636000000.0000
 InvestmentIncomeInterest                                                                    |    30000000.0000
 OperatingIncomeLoss                                                                         |  1994000000.0000
 SellingGeneralAndAdministrativeExpense                                                      |  3145000000.0000
 NetIncomeLossAttributableToNoncontrollingInterest                                           |   141000000.0000
 StockholdersEquityNoteStockSplitConversionRatio1                                            |           5.0000
 NetIncomeLossAvailableToCommonStockholdersBasic                                             |   690000000.0000
 Revenues                                                                                | 31536000000.0000
 IncomeTaxExpenseBenefit                                                                     |   292000000.0000
 OtherNonoperatingIncomeExpense                                                              |  -122000000.0000
 WeightedAverageNumberOfDilutedSharesOutstanding                                             |  1083000000.0000
 EarningsPerShareBasic                                                                       |           0.7400
 ResearchAndDevelopmentExpense                                                               |  1491000000.0000
 BuyOutOfNoncontrollingInterest                                                              |    31000000.0000
 CostOfAutomotiveLeasing                                                                     |   563000000.0000
 CostOfRevenuesAutomotive                                                                    | 20259000000.0000
 CostOfServicesAndOther                                                                      |  2671000000.0000
 SalesRevenueAutomotive                                                                      | 27236000000.0000
 SalesRevenueServicesAndOtherNet                                                             |  2306000000.0000
(28 rows)
</code>```

stmt='IS':get tag in the income statement,ddate='2020-12-31':annual report on 2020 year.Please read SEC's data field definition for qtrs,you may know why to set qtrs=4 in the select command.

Make a comparison with https://www.nasdaq.com/market-activity/stocks/tsla/financials,show part of it,look at the 12/31/2020 column:

```<code>Period Ending:  12/31/2021  12/31/2020  12/31/2019  12/31/2018
Total Revenue   $53,823,000 $31,536,000 $24,578,000 $21,461,000
Cost of Revenue $40,217,000 $24,906,000 $20,509,000 $17,419,000
Gross Profit    $13,606,000 $6,630,000  $4,069,000  $4,042,000
Research and Development    $2,593,000  $1,491,000  $1,343,000  $1,460,000
</code>```

All the number are equal,the terms in xbrl are:Revenues,CostOfRevenue,GrossProfit,ResearchAndDevelopmentExpense ,the respective terms in financial accounting concepts are:Total Revenue,Cost of Revenue,Gross Profit,Research and Development. What i get are  right numbers.

Somedays later,i can find the direct way to parse raw xbrl file to get the income statement,i am not familiar with xbrl yet,wish stackoverflow community help me fulfill my goal.

Body:
All company concepts in xbrl format can be extracted with sec's RESTful api.
For example,i want to get tesla's concepts in xbrl format in 2020, get the tesla's cik and the url for api.

cik='1318605'
url = 'https://data.sec.gov/api/xbrl/companyfacts/CIK{:>010s}.json'.format(cik)

To express financial statement in 2020 with elements fy and fp:

'fy' ==  2020 and 'fp' == 'FY'

I write the whole python code to call sec's api:

import requests
import json
cik='1318605'
url = 'https://data.sec.gov/api/xbrl/companyfacts/CIK{:>010s}.json'.format(cik)
headers = {
    "User-Agent": "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/95.0.4638.69 Safari/537.36"
          }
res = requests.get(url=url,headers=headers)
result = json.loads(res.text)
concepts_list = list(result['facts']['us-gaap'].keys())
data_concepts = result['facts']['us-gaap']

fdata = {}
for item in concepts_list:
    data = data_concepts[item]['units']
    data_units = list(data_concepts[item]['units'].keys())
    for data_units_attr in data_units:
        for record in data[data_units_attr]:
            if record['fy'] ==  2020 and record['fp'] == 'FY':
                fdata[item] = record['val']

fdata contains all the company concepts and its value in 2020 for tesla,show part of it:

fdata
{'AccountsAndNotesReceivableNet': 334000000,
 'AccountsPayableCurrent': 6051000000,
 'AccountsReceivableNetCurrent': 1886000000,

How can get all concepts below to income statement?I want to extract it to make an income statement.

Maybe i should add some values in dei with almost same way as above.

EntityCommonStockSharesOutstanding:959853504
EntityPublicFloat:160570000000

It is simple to parse financial statement such as income statement from ixbrl file:

https://www.sec.gov/ix?doc=/Archives/edgar/data/0001318605/000156459021004599/tsla-10k_20201231.htm

I can get it ,please help to replicate the annual income statement on 2020 for Tesla from sec's RESTful api,or extract the income statement from the whole instance file:

https://www.sec.gov/Archives/edgar/data/1318605/000156459021004599/0001564590-21-004599.txt

If you tell me how to get all concepts belong to income statement ,i can fulfill the job ,with the same way  balance and cashflow statement all can be extracted.In my case the fdata contain all concepts belong to income,balance,cashflow statement,which concept in fdata belong to which financial statement? How to map every concepts into income,balance,cashflow statement?

#expression in pseudocode
income_statement = fdata[all_concepts_belong_to_income_statement]
balance_statement = fdata[all_concepts_belong_to_balance_statement]
cashflow_statement = fdata[all_concepts_belong_to_cashflow_statement]

Body:
I get a indirect way to extract income statement via SEC's api,SEC already publish all data extracted from raw xbrl file(called xbrl instance published also),the tool which parse xbrl file to form four csv files num.txt,sub.txt,pre.txt,tag.txt is not published,what i want to do is to create the tool myself.

Step1:

Download dataset from https://www.sec.gov/dera/data/financial-statement-data-sets.html on 2020,and unzip it ,we get pre.txt,num.txt,sub.txt,tag.txt.

Step2:

Create database and table pre,num,sub,tag according to fields in pre.txt,num.txt,sub.txt,tag.txt.

Step3:

Import pre.txt,num.txt,sub.txt,tag.txt into table pre,num,sub,tag.

Step4:

Query in my postgresql:

the adsh number for tesla's financial statement on 2020 is `0001564590-21-004599`

\set accno  '0001564590-21-004599'
select tag,value from num where adsh=:'accno' and ddate = '2020-12-31' and qtrs=4  and tag in
(select tag from pre where adsh=:'accno' and stmt='IS');
                                             tag                                             |      value
---------------------------------------------------------------------------------------------+------------------
 NetIncomeLoss                                                                               |   721000000.0000
 OperatingLeasesIncomeStatementLeaseRevenue                                                  |  1052000000.0000
 GrossProfit                                                                                |  6630000000.0000
 InterestExpense                                                                             |   748000000.0000
 CostOfRevenue                                                                               | 24906000000.0000
 WeightedAverageNumberOfSharesOutstandingBasic                                               |   933000000.0000
 IncomeLossFromContinuingOperationsBeforeIncomeTaxesExtraordinaryItemsNoncontrollingInterest |  1154000000.0000
 EarningsPerShareDiluted                                                                     |           0.6400
 ProfitLoss                                                                                |   862000000.0000
 OperatingExpenses                                                                           |  4636000000.0000
 InvestmentIncomeInterest                                                                    |    30000000.0000
 OperatingIncomeLoss                                                                         |  1994000000.0000
 SellingGeneralAndAdministrativeExpense                                                      |  3145000000.0000
 NetIncomeLossAttributableToNoncontrollingInterest                                           |   141000000.0000
 StockholdersEquityNoteStockSplitConversionRatio1                                            |           5.0000
 NetIncomeLossAvailableToCommonStockholdersBasic                                             |   690000000.0000
 Revenues                                                                                | 31536000000.0000
 IncomeTaxExpenseBenefit                                                                     |   292000000.0000
 OtherNonoperatingIncomeExpense                                                              |  -122000000.0000
 WeightedAverageNumberOfDilutedSharesOutstanding                                             |  1083000000.0000
 EarningsPerShareBasic                                                                       |           0.7400
 ResearchAndDevelopmentExpense                                                               |  1491000000.0000
 BuyOutOfNoncontrollingInterest                                                              |    31000000.0000
 CostOfAutomotiveLeasing                                                                     |   563000000.0000
 CostOfRevenuesAutomotive                                                                    | 20259000000.0000
 CostOfServicesAndOther                                                                      |  2671000000.0000
 SalesRevenueAutomotive                                                                      | 27236000000.0000
 SalesRevenueServicesAndOtherNet                                                             |  2306000000.0000
(28 rows)

stmt='IS':get tag in the income statement,ddate='2020-12-31':annual report on 2020 year.Please read SEC's data field definition for qtrs,you may know why to set qtrs=4 in the select command.

Make a comparison with https://www.nasdaq.com/market-activity/stocks/tsla/financials,show part of it,look at the 12/31/2020 column:

Period Ending:  12/31/2021  12/31/2020  12/31/2019  12/31/2018
Total Revenue   $53,823,000 $31,536,000 $24,578,000 $21,461,000
Cost of Revenue $40,217,000 $24,906,000 $20,509,000 $17,419,000
Gross Profit    $13,606,000 $6,630,000  $4,069,000  $4,042,000
Research and Development    $2,593,000  $1,491,000  $1,343,000  $1,460,000

All the number are equal,the terms in xbrl are:Revenues,CostOfRevenue,GrossProfit,ResearchAndDevelopmentExpense ,the respective terms in financial accounting concepts are:Total Revenue,Cost of Revenue,Gross Profit,Research and Development. What i get are  right numbers.

Somedays later,i can find the direct way to parse raw xbrl file to get the income statement,i am not familiar with xbrl yet,wish stackoverflow community help me fulfill my goal.