问:
How to delete all files in folder except CSV?
I wrote a dataframe to a csv in Pyspark. And I got the output files in the directory as:

._SUCCESS.crc

.part-00000-6cbfdcfd-afff-4ded-802c-6ccd67f3804a-c000.csv.crc

part-00000-6cbfdcfd-afff-4ded-802c-6ccd67f3804a-c000.csv

How do I keep only the CSV file in the directory and delete rest of the files, using Python?

答:
You can also have fun with list comprehension for doing this:</p>
```<code>import os

dir_path = 'output/'

[os.remove(os.path.join(dir_path, item)) for item in os.listdir(dir_path) if not item.endswith('.csv')]
</code>```

Body:
You can also have fun with list comprehension for doing this:

import os

dir_path = 'output/'

[os.remove(os.path.join(dir_path, item)) for item in os.listdir(dir_path) if not item.endswith('.csv')]


来源: stackexchange

问:
Preventing VS 2019 from rebuilding a solution though no source has changed
I am trying to track down a VS 2019 build issue for a few weeks which drives me crazy. I have a C# project (targeting .Net Framework 4.8) which VS rebuilds regularly even when nothing has changed. The project is not very complex and has no specific dependencies, but a postbuild event which must always be executed. Hence I used the approach described in this answer, which forces msbuild to do the "up-to-date" check instead of the VS IDE. This has worked well for years, but started to make trouble a few weeks ago.

To create a minimal reproducible example:

use the VS project wizard to create a trivial "hello world" console app, .Net Fw 4.8, AnyCpu

add the following lines to the csproj file:

```<code><PropertyGroup>
   <RunPostBuildEvent>Always</RunPostBuildEvent>
   <PostBuildEvent>
   </PostBuildEvent>
   <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck>
</PropertyGroup>
</code>```

change the "Run Post Build" setting in the IDE's project settings to "On Build Success" (or back to "Always", this does not really matter), save the settings

The Postbuild action is intentionally left empty, one can add arbitrary actions here, but even an empty action will produce the issue.

When I choose to rebuild the solution in the IDE (using Ctrl-Shift-B), without touching anything the source code, the executable is recreated. This effect occurs when the time between two consecutive builds is approx. 10 seconds or more, when I rebuild the solution quicker, the exe file stays untouched.

To make the effect more visible, I set "AssemblyVersion("1.0.0.*"), stripped the "AssemblyInformationalVersion" attribute from AssemblyInfo.cs, so the build system assigns a new build number to the exe file with each new creation, which allows to observe the effect in the Windows Explorer more easily (by activating the "File Version" column in the Explorer view).

Note this effect does not seem to occur when I comment out either the post build event, or the DisableFastUpToDateCheck setting.

I observed this with VS 2019 V16.11.9 and V16.11.10 (currently the latest versions in the "2019" product line).

In my real project, this happens for a central DLL inside a solution where more then 70 other projects depend on, including a large C++/CLI dll, resulting in a build time of ~2 minutes - every time I only want to start the debugger, since this causes a new build! And yes, I also tried to set the "project build output" settings to "Diagnostic", but could not find anything suspicious in the large amount of messages.

答:
PostBuildEvent is problematic and 'old style' since it doesn't define its inputs and outputs. Because of that msbuild can't calculate whether it caused any files to change and thus forces a rebuild.

By replacing the postbuildevent with a custom target and by correctly specifying the inputs and outputs of the target, MSBuild can check whether any of the inpu ts have changed and whether the outputs are up to date to properly decide to skip the build altogether.

See:

https://learn.microsoft.com/en-us/visualstudio/msbuild/incremental-builds?view=vs-2022

PostBuildEvent is also no longer supported in new style SDK projects. Visual Studio will now automatically generate a new target when you setup a postbuild event in the UI.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to track down a VS 2019 build issue for a few weeks which drives me crazy. I have a C# project (targeting .Net Framework 4.8) which VS rebuilds regularly even when nothing has changed. The project is not very complex and has no specific dependencies, but a postbuild event which must always be executed. Hence I used the approach described in this answer, which forces msbuild to do the "up-to-date" check instead of the VS IDE. This has worked well for years, but started to make trouble a few weeks ago.

To create a minimal reproducible example:

use the VS project wizard to create a trivial "hello world" console app, .Net Fw 4.8, AnyCpu

add the following lines to the csproj file:

<PropertyGroup>
   <RunPostBuildEvent>Always</RunPostBuildEvent>
   <PostBuildEvent>
   </PostBuildEvent>
   <DisableFastUpToDateCheck>true</DisableFastUpToDateCheck>
</PropertyGroup>

change the "Run Post Build" setting in the IDE's project settings to "On Build Success" (or back to "Always", this does not really matter), save the settings

The Postbuild action is intentionally left empty, one can add arbitrary actions here, but even an empty action will produce the issue.

When I choose to rebuild the solution in the IDE (using Ctrl-Shift-B), without touching anything the source code, the executable is recreated. This effect occurs when the time between two consecutive builds is approx. 10 seconds or more, when I rebuild the solution quicker, the exe file stays untouched.

To make the effect more visible, I set "AssemblyVersion("1.0.0.*"), stripped the "AssemblyInformationalVersion" attribute from AssemblyInfo.cs, so the build system assigns a new build number to the exe file with each new creation, which allows to observe the effect in the Windows Explorer more easily (by activating the "File Version" column in the Explorer view).

Note this effect does not seem to occur when I comment out either the post build event, or the DisableFastUpToDateCheck setting.

I observed this with VS 2019 V16.11.9 and V16.11.10 (currently the latest versions in the "2019" product line).

In my real project, this happens for a central DLL inside a solution where more then 70 other projects depend on, including a large C++/CLI dll, resulting in a build time of ~2 minutes - every time I only want to start the debugger, since this causes a new build! And yes, I also tried to set the "project build output" settings to "Diagnostic", but could not find anything suspicious in the large amount of messages.


问:
How to set time to Zeros in DateTime?
Lets say I have the following DateTime variable

```<code>DateTime CurDate = '26/3/2014 12:00:00 AM';
</code>```

I'm wondering how can I set the CurDate so that the value will become 26/3/2014 00:00:00 AM

Note that I still want the time, but with all zeros.

**P/S: The reason for having all zeros is because the datetime value stored in SQL Server is 26/3/2014 00:00:00.000. I need to cast CurDate to have all zeros in order to match database data

答:
Put .Date and get the date part with zero time part.
I use Linq as:

var list = Results.Where(x => x.ExpDate.Date >= From.Date && x.ExpDate.Date <= To.Date).ToList();

ContentLicense: CC BY-SA 3.0

Title: How to set time to Zeros in DateTime?

Body:
Lets say I have the following DateTime variable

DateTime CurDate = '26/3/2014 12:00:00 AM';

I'm wondering how can I set the CurDate so that the value will become 26/3/2014 00:00:00 AM

Note that I still want the time, but with all zeros.

**P/S: The reason for having all zeros is because the datetime value stored in SQL Server is 26/3/2014 00:00:00.000. I need to cast CurDate to have all zeros in order to match database data


问:
How to set Date limit to 6 months from current date Flutter?
I need to set the calendar limit to next 6 months from now. the code i tried to run is given below:

```<code>Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime.now(),
        lastDate: DateTime(DateTime.now().month + 6));
    if (picked != null && picked != selectedDate)
      setState(() {
        selectedDate = picked;
      });
  }
</code>```

When i try to run this code i get the given error:

```<code>Unhandled Exception: 'package:flutter/src/material/date_picker.dart': Failed assertion: line 226 pos 5: '!lastDate.isBefore(firstDate)': lastDate 0008-01-01 00:00:00.000 must be on or after firstDate 2022-02-09 00:00:00.000.
E/flutter ( 1931): #0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39)
E/flutter ( 1931): #1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
</code>```

答:
Your lastDate input DateTime(DateTime.now().month + 6)) is incorrect.

Since DateTime.now().month + 6 will produce an int, DateTime(DateTime.now().month + 6)) will be the year DateTime.now().month + 6.

Change that line to:

lastDate: DateTime(DateTime.now().year, DateTime.now().month + 6, DateTime.now().day));

Or use the .add function for DateTime class:

DateTime.now().add(const Duration(days: 180));

Body:
I need to set the calendar limit to next 6 months from now. the code i tried to run is given below:

Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime.now(),
        lastDate: DateTime(DateTime.now().month + 6));
    if (picked != null && picked != selectedDate)
      setState(() {
        selectedDate = picked;
      });
  }

When i try to run this code i get the given error:

Unhandled Exception: 'package:flutter/src/material/date_picker.dart': Failed assertion: line 226 pos 5: '!lastDate.isBefore(firstDate)': lastDate 0008-01-01 00:00:00.000 must be on or after firstDate 2022-02-09 00:00:00.000.
E/flutter ( 1931): #0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39)
E/flutter ( 1931): #1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)


问:
error: no matching function for call to 'Node::Node()' - second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...)
I've defined a structure like this:

```<code>struct Node
{
   int32_t a;
   int32_t b;
   double c;
   double d;

   Node (int32_t a, int32_t b, double c)
   {
     this->a = a;
     this->b = b;
     this->c = c;
     this->d = 0.0;
   }
};
</code>```

I'm implementing a map of map like this:

```<code>unordered_map<UInt32,unordered_map<int32_t,Node>> data;
</code>```

Upon using the below code. I'm receiving error error: no matching function for call to 'Node::Node()' second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...)

```<code>data[instId][id].d += (value);
</code>```

Please help out why I'm receiving error. I've also tried using auto& tree = data[instId]; tree[id].d += (value);

(PS: Pseudo code is mentioned)

答: It is because that unordered_map<int32_t,Node> tries to call the constructor Node() with no argument, and because you defined the constructor with three argument, Node() is deleted. Consider adding Node()=default; inside the class definition.

Body:
I've defined a structure like this:

struct Node
{
   int32_t a;
   int32_t b;
   double c;
   double d;

   Node (int32_t a, int32_t b, double c)
   {
     this->a = a;
     this->b = b;
     this->c = c;
     this->d = 0.0;
   }
};

I'm implementing a map of map like this:

unordered_map<UInt32,unordered_map<int32_t,Node>> data;

Upon using the below code. I'm receiving error error: no matching function for call to 'Node::Node()' second(std::forward<_Args2>(std::get<_Indexes2>(__tuple2))...)

data[instId][id].d += (value);

Please help out why I'm receiving error. I've also tried using auto& tree = data[instId]; tree[id].d += (value);

(PS: Pseudo code is mentioned)


问:
Spring Boot problems scanning packages in dependency
I'm working on an application we'll call MyApp.  Previously each application at my workplace had its own set of standard services and repositories; what I'm trying to do is move those services and repositories to a JAR we'll call MyServices hosted on GitHub packages that applications can import, so that when changes are made to services, the parent applications can simply update the JAR version rather than each copying and pasting the changes in.

I created a test environment in MyServices that works fine.  The problems come when I try to import MyServices into MyApp and run it.  I just can't figure out how to correctly scan the services with Spring.  I'm getting many errors for nearly all of my services such as:

Field userRepository in com.mycompany.myservices.backend.security.LoginSuccessHandler required a bean of type 'com.mycompany.myservices.backend.data.repositories.UserRepository' that could not be found., when UserRepository definitely is defined in the package, or:

Error creating bean with name 'com.mycompany.myApp.ui.views.admin.LoginView': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mycompany.myservices.backend.data.services.UserService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {} when UserService does 100% exist, or others claiming that:

Parameter 0 of constructor in com.mycompany.myservices.backend.data.AppDB required a bean of type 'org.springframework.data.mongodb.core.MongoTemplate' that could not be found., when I do actually have a MongoTemplate bean defined in the main myApp package.  It seems like Spring isn't scanning things in the correct order, and I'm not sure how to fix it.

Here's my Application.java:

```<code>@SpringBootApplication(
        exclude = {ErrorMvcAutoConfiguration.class, SecurityAutoConfiguration.class,
                MongoAutoConfiguration.class, MongoDataAutoConfiguration.class},
        scanBasePackages = {"com.mycompany.myservices.backend"})
@EnableMongoRepositories(basePackageClasses = { PrimaryMongoConfig.class, SecondaryMongoConfig.class })
@EntityScan(basePackageClasses = { User.class })

public class  Application extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }
}
</code>```

To reiterate, this setup works perfectly fine in applications that contain their own copies of the services.  It just isn't scanning correctly when they're in the JAR dependency, and I'm not sure why, since it should be scanned via the scanBasePackages.  Ideas?

答:
try add annotation @EnableJpaRepositories to you Application class:

```<code>@EnableJpaRepositories(basePackages =
    "your.package.of.repository"
)
</code>```

Body:
I'm working on an application we'll call MyApp.  Previously each application at my workplace had its own set of standard services and repositories; what I'm trying to do is move those services and repositories to a JAR we'll call MyServices hosted on GitHub packages that applications can import, so that when changes are made to services, the parent applications can simply update the JAR version rather than each copying and pasting the changes in.

I created a test environment in MyServices that works fine.  The problems come when I try to import MyServices into MyApp and run it.  I just can't figure out how to correctly scan the services with Spring.  I'm getting many errors for nearly all of my services such as:

Field userRepository in com.mycompany.myservices.backend.security.LoginSuccessHandler required a bean of type 'com.mycompany.myservices.backend.data.repositories.UserRepository' that could not be found., when UserRepository definitely is defined in the package, or:

Error creating bean with name 'com.mycompany.myApp.ui.views.admin.LoginView': Unsatisfied dependency expressed through constructor parameter 0; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'com.mycompany.myservices.backend.data.services.UserService' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {} when UserService does 100% exist, or others claiming that:

Parameter 0 of constructor in com.mycompany.myservices.backend.data.AppDB required a bean of type 'org.springframework.data.mongodb.core.MongoTemplate' that could not be found., when I do actually have a MongoTemplate bean defined in the main myApp package.  It seems like Spring isn't scanning things in the correct order, and I'm not sure how to fix it.

Here's my Application.java:

@SpringBootApplication(
        exclude = {ErrorMvcAutoConfiguration.class, SecurityAutoConfiguration.class,
                MongoAutoConfiguration.class, MongoDataAutoConfiguration.class},
        scanBasePackages = {"com.mycompany.myservices.backend"})
@EnableMongoRepositories(basePackageClasses = { PrimaryMongoConfig.class, SecondaryMongoConfig.class })
@EntityScan(basePackageClasses = { User.class })

public class  Application extends SpringBootServletInitializer {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Application.class);
    }
}

To reiterate, this setup works perfectly fine in applications that contain their own copies of the services.  It just isn't scanning correctly when they're in the JAR dependency, and I'm not sure why, since it should be scanned via the scanBasePackages.  Ideas?

Body:
try add annotation @EnableJpaRepositories to you Application class:

@EnableJpaRepositories(basePackages =
    "your.package.of.repository"
)


问:
Java Selenium driver.close() on iPhone Safari does not work
I'm a beginner in selenium automation and I'm trying perform automation tests of our website on iPhone Safari.

These tests should involve browser actions such as clicking an element and then closing the new opened Safari tab.

I managed to perform a click on the element and the new tab was opened successfully, the problem is that for some reason, closing the new tab with driver.close() is not working (no errors been thrown). The above was performed successfully on Desktop browsers such as Chrome and Firefox and on Galaxy Chrome.

The attached code was executed via BrowserStack.
At first, I suspected that the problem was on their side,  but after a short communication with them we've found that the problem happens when running selenium automation on a local iPhone device as well and regardless to BrowserStack.

Can anyone assist me ?

Thanks!

            DesiredCapabilities caps = new DesiredCapabilities();
            caps.setCapability("browserName", "iPhone");
            caps.setCapability("device", "iPhone XS");
            caps.setCapability("realMobile", "true");
            caps.setCapability("os_version", "14");
            caps.setCapability("name", "iphone");

            caps.setCapability("browserstack.safari.enablePopups", "true");
            caps.setCapability("browserstack.safari.allowAllCookies", "true");
            caps.setCapability("nativeWebTap", true);

            WebDriver driver = new RemoteWebDriver(new URL(URL), caps);

            driver.get("https://m.imdb.com/");

            Thread.sleep(3000);
            System.out.println("original window URL: " + driver.getCurrentUrl());
            String originalWindow = driver.getWindowHandle();

            driver.findElement(By.xpath("//*[@title='Facebook']")).click();

            Thread.sleep(5000);

            for (String windowHandle : driver.getWindowHandles()) {
                if(!originalWindow.contentEquals(windowHandle)) {
                    driver.switchTo().window(windowHandle);
                    break;
                }
            }

            System.out.println("new window URL: " + driver.getCurrentUrl());

            Thread.sleep(5000);

            driver.close();

            Thread.sleep(3000);
            System.out.println("after close window URL: " + driver.getCurrentUrl());
            driver.quit();```

答: You can try to switch native context and close the tab: https://gist.github.com/arvind1998/2249362084d9e67cdff265898a2ab2b7</p>


问:
Exponentiate regression results in huxtable
I'm putting together some tables with results from a series of Cox Proportional Hazards Models. I'd like to exponentiate the coefficients so the tables display the Hazard Ratios rather than the raw beta values. Does anyone know of a way to do this with huxtable? It's my preferred package for building regression tables. I've done some googling and can't find a solution.</p>

答:
You can use the tidy_args argument to huxreg:

library(huxtable)
library(survival)

test1 <- list(time=c(4,3,1,1,2,2,3),
              status=c(1,1,1,0,1,1,0),
              x=c(0,2,1,1,1,0,0),
              sex=c(0,0,0,0,1,1,1))
mod <- coxph(Surv(time, status) ~ x + strata(sex), test1)
```
```huxreg(mod)
                           ─────────────────────────────────────────────────
                                                              (1)
                                                   ─────────────────────────
                             x                                      0.802
                                                                   (0.822)
                                                   ─────────────────────────
                             N                                      5.000
                             R2                                     0.144
                             logLik                                -3.328
                             AIC                                    8.655
                           ─────────────────────────────────────────────────
                             *** p < 0.001; ** p < 0.01; * p < 0.05.

Column names: names, model1

huxreg(mod, tidy_args = list(exponentiate = TRUE))
                           ─────────────────────────────────────────────────
                                                              (1)
                                                   ─────────────────────────
                             x                                      2.231
                                                                   (0.822)
                                                   ─────────────────────────
                             N                                      5.000
                             R2                                     0.144
                             logLik                                -3.328
                             AIC                                    8.655
                           ─────────────────────────────────────────────────
                             *** p < 0.001; ** p < 0.01; * p < 0.05.

Column names: names, model1
```
<p><code>tidy(mod, exponentiate = TRUE)</code> appears to exponentiate the coefficients but not the standard errors, which is presumably a bug in <code>broom</code> and worth reporting? Confidence intervals appear correct, though, so you can do:</p>
```huxreg(mod, tidy_args = list(exponentiate = TRUE),
       error_format = "[{conf.low}-{conf.high}]", ci_level = 0.95)
                           ─────────────────────────────────────────────────
                                                              (1)
                                                   ─────────────────────────
                             x                                      2.231
                                                            [0.445-11.180]
                                                   ─────────────────────────
                             N                                      5.000
                             R2                                     0.144
                             logLik                                -3.328
                             AIC                                    8.655
                           ─────────────────────────────────────────────────
                             *** p < 0.001; ** p < 0.01; * p < 0.05.

Column names: names, model1
```

Body:
You can use the tidy_args argument to huxreg:

library(huxtable)
library(survival)

test1 <- list(time=c(4,3,1,1,2,2,3),
              status=c(1,1,1,0,1,1,0),
              x=c(0,2,1,1,1,0,0),
              sex=c(0,0,0,0,1,1,1))
mod <- coxph(Surv(time, status) ~ x + strata(sex), test1)

huxreg(mod)
                           ─────────────────────────────────────────────────
                                                              (1)
                                                   ─────────────────────────
                             x                                      0.802
                                                                   (0.822)
                                                   ─────────────────────────
                             N                                      5.000
                             R2                                     0.144
                             logLik                                -3.328
                             AIC                                    8.655
                           ─────────────────────────────────────────────────
                             *** p < 0.001; ** p < 0.01; * p < 0.05.

Column names: names, model1

huxreg(mod, tidy_args = list(exponentiate = TRUE))
                           ─────────────────────────────────────────────────
                                                              (1)
                                                   ─────────────────────────
                             x                                      2.231
                                                                   (0.822)
                                                   ─────────────────────────
                             N                                      5.000
                             R2                                     0.144
                             logLik                                -3.328
                             AIC                                    8.655
                           ─────────────────────────────────────────────────
                             *** p < 0.001; ** p < 0.01; * p < 0.05.

Column names: names, model1

tidy(mod, exponentiate = TRUE) appears to exponentiate the coefficients but not the standard errors, which is presumably a bug in broom and worth reporting? Confidence intervals appear correct, though, so you can do:

huxreg(mod, tidy_args = list(exponentiate = TRUE),
       error_format = "[{conf.low}-{conf.high}]", ci_level = 0.95)
                           ─────────────────────────────────────────────────
                                                              (1)
                                                   ─────────────────────────
                             x                                      2.231
                                                            [0.445-11.180]
                                                   ─────────────────────────
                             N                                      5.000
                             R2                                     0.144
                             logLik                                -3.328
                             AIC                                    8.655
                           ─────────────────────────────────────────────────
                             *** p < 0.001; ** p < 0.01; * p < 0.05.

Column names: names, model1


问:
Using date_add () with date_trunc() in presto
Does anyone know what the below query will return?

```<code>"date_add"('month', -1, "date_trunc"('month', "date_add"('day', -1, current_date)))
</code>```

Assuming that current date is 5 Feb 2022, then my guess is that:

"date_add"('day', -1, current_date) will return 4 Feb 2022
"date_trunc"('month', "date_add"('day', -1, current_date)) will return 1 Feb 2022

Finally,  "date_add"('month', -1, "date_trunc"('month', "date_add"('day', -1, current_date))) will return 1 Jan 2022

答:
This transformation returns first day of previous month if initial date is not the first day of the month. For the first day it returns first day of two month ago

```<code>select current_date                                               as initial_date,
       "date_add"('day', -1, current_date)                        as second_date, --initial minus 1 day
       "date_trunc"('month', "date_add"('day', -1, current_date)) as third_date,  --second_date truncated to -01
       "date_add"('month', -1, "date_trunc"('month', "date_add"('day', -1, current_date))) as final_result --third date - 1 month
</code>```

Result:

```<code>initial_date  second_date  third_date  final_result
2022-02-09    2022-02-08   2022-02-01  2022-01-01 --1st of 1 mth back
</code>```

Test with 1st day of the month:

```<code>select date '2022-02-01'                                               as initial_date,
       "date_add"('day', -1, date '2022-02-01')                        as second_date, --initial minus 1 day
       "date_trunc"('month', "date_add"('day', -1, date '2022-02-01')) as third_date,  --second_date truncated to -01
       "date_add"('month', -1, "date_trunc"('month', "date_add"('day', -1, date '2022-02-01'))) as final_result --third date - 1 month
</code>```

Result:

```<code>initial_date  second_date  third_date  final_result
2022-02-01    2022-01-31   2022-01-01  2021-12-01 --this is 2 mth back
</code>```

Body:
Does anyone know what the below query will return?

"date_add"('month', -1, "date_trunc"('month', "date_add"('day', -1, current_date)))

Assuming that current date is 5 Feb 2022, then my guess is that:

"date_add"('day', -1, current_date) will return 4 Feb 2022
"date_trunc"('month', "date_add"('day', -1, current_date)) will return 1 Feb 2022

Finally,  "date_add"('month', -1, "date_trunc"('month', "date_add"('day', -1, current_date))) will return 1 Jan 2022

Body:
This transformation returns first day of previous month if initial date is not the first day of the month. For the first day it returns first day of two month ago

select current_date                                               as initial_date,
       "date_add"('day', -1, current_date)                        as second_date, --initial minus 1 day
       "date_trunc"('month', "date_add"('day', -1, current_date)) as third_date,  --second_date truncated to -01
       "date_add"('month', -1, "date_trunc"('month', "date_add"('day', -1, current_date))) as final_result --third date - 1 month

Result:

initial_date  second_date  third_date  final_result
2022-02-09    2022-02-08   2022-02-01  2022-01-01 --1st of 1 mth back

Test with 1st day of the month:

select date '2022-02-01'                                               as initial_date,
       "date_add"('day', -1, date '2022-02-01')                        as second_date, --initial minus 1 day
       "date_trunc"('month', "date_add"('day', -1, date '2022-02-01')) as third_date,  --second_date truncated to -01
       "date_add"('month', -1, "date_trunc"('month', "date_add"('day', -1, date '2022-02-01'))) as final_result --third date - 1 month

Result:

initial_date  second_date  third_date  final_result
2022-02-01    2022-01-31   2022-01-01  2021-12-01 --this is 2 mth back


问:
Linq Except not giving desired results in C#, datatable
I have two DataTables. I applied the Except operator as follows,
and got either unfiltered or undesired results.

```<code>resultDataTable = dtA.AsEnumerable().Except(dtB.AsEnumerable()).CopyToDataTable();
</code>```

Could anyone please kindly explain to me why Except(dtB.AsEnumerable()) is not the way to put it?

Note:
Both DataTables are plain simple with just one column.

dtA contains a dozen rows of strings.

dtB contains thousands of rows of strings.

I also tried the same syntax with another use case the set operator, Intersect. This does not work either.

resultDataTable2 =dtA.AsEnumerable().Intersect(dtB.AsEnumerable()).CopyToDataTable();

答:
Except will use default comparer ie. it will compare references.

I think you are expecting to filter result and comparison is based on members.

I will recommend you to implement your own IEqualityComparer to compare two objects based on member.

e.g.

resultDataTable = dtA.AsEnumerable().Except(dtB.AsEnumerable(), new TestComparer()).CopyToDataTable();

class TestComparer : IEqualityComparer<MyTestClass>
{
    public bool Equals(MyTestClass b1, MyTestClass b2)
    {
        if (b2 == null && b1 == null)
           return true;
        else if (b1 == null || b2 == null)
           return false;
        else if(b1.Prop1 == b2.Prop1 && b1.Prop2 == b2.Prop2) // ToDo add more check based on class
            return true;
        else
            return false;
    }

    public int GetHashCode(MyTestClass)
    {
        int hCode = MyTestClass.Height ^ MyTestClass.Length ^ ....; // Add more based on class properties
        return hCode.GetHashCode();
    }
}

```

Doc
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.except?view=net-6.0#system-linq-enumerable-except-1(system-collections-generic-ienumerable((-0))-system-collections-generic-ienumerable((-0))-system-collections-generic-iequalitycomparer((-0)))

Body:
I have two DataTables. I applied the Except operator as follows,
and got either unfiltered or undesired results.

resultDataTable = dtA.AsEnumerable().Except(dtB.AsEnumerable()).CopyToDataTable();

Could anyone please kindly explain to me why Except(dtB.AsEnumerable()) is not the way to put it?

Note:
Both DataTables are plain simple with just one column.

dtA contains a dozen rows of strings.

dtB contains thousands of rows of strings.

I also tried the same syntax with another use case the set operator, Intersect. This does not work either.

resultDataTable2 =dtA.AsEnumerable().Intersect(dtB.AsEnumerable()).CopyToDataTable();

Body:
Except will use default comparer ie. it will compare references.

I think you are expecting to filter result and comparison is based on members.

I will recommend you to implement your own IEqualityComparer to compare two objects based on member.

e.g.

resultDataTable = dtA.AsEnumerable().Except(dtB.AsEnumerable(), new TestComparer()).CopyToDataTable();

class TestComparer : IEqualityComparer<MyTestClass>
{
    public bool Equals(MyTestClass b1, MyTestClass b2)
    {
        if (b2 == null && b1 == null)
           return true;
        else if (b1 == null || b2 == null)
           return false;
        else if(b1.Prop1 == b2.Prop1 && b1.Prop2 == b2.Prop2) // ToDo add more check based on class
            return true;
        else
            return false;
    }

    public int GetHashCode(MyTestClass)
    {
        int hCode = MyTestClass.Height ^ MyTestClass.Length ^ ....; // Add more based on class properties
        return hCode.GetHashCode();
    }
}

Doc
https://learn.microsoft.com/en-us/dotnet/api/system.linq.enumerable.except?view=net-6.0#system-linq-enumerable-except-1(system-collections-generic-ienumerable((-0))-system-collections-generic-ienumerable((-0))-system-collections-generic-iequalitycomparer((-0)))


问:
how to override the "A value is required." while validating a datetime format in asp.net mvc view?
I am checking a datetime field in mvc view for datetime format like this:

```<code>        If contactToValidate.LastUpdated = Nothing OrElse Not IsDate(contactToValidate.LastUpdated) OrElse CType(contactToValidate.LastUpdated, DateTime) = DateTime.MinValue Then
             _validationDictionary.AddError("AddErrorValue", "Date Format is not Correct!")
        End If
</code>```

but , if the input for LastUpdated in View , left blank, beside my own error ("Date Format is not Correct!") , the default error message is shown: A value is required.
I believe this is what mvc framework automatically checked for datatype conversions, but as I'm checking the LastUpdated textbox for null and datetime format, I dont want this error message to be shown. I just want my own. How can I do that?
Thanks

答:
I belive what you're looking for is this

```<code>ViewData.ModelState.AddModelError("FieldName", "Date Format is not Correct!");
</code>```

This will force <%=Html.ValidationMessage("FieldName") %> to show your error message.

Edit : I just checked and this will not actually solve the problem. You should refer to Craig Stuntz's answer about non-nullable type and IDataErrorInfo and then you can add your own error message for the empty field.

OwnerDisplayName: Nihil

ContentLicense: CC BY-SA 2.5

Body:
I am checking a datetime field in mvc view for datetime format like this:

        If contactToValidate.LastUpdated = Nothing OrElse Not IsDate(contactToValidate.LastUpdated) OrElse CType(contactToValidate.LastUpdated, DateTime) = DateTime.MinValue Then
             _validationDictionary.AddError("AddErrorValue", "Date Format is not Correct!")
        End If

but , if the input for LastUpdated in View , left blank, beside my own error ("Date Format is not Correct!") , the default error message is shown: A value is required.
I believe this is what mvc framework automatically checked for datatype conversions, but as I'm checking the LastUpdated textbox for null and datetime format, I dont want this error message to be shown. I just want my own. How can I do that?
Thanks

Body:
I belive what you're looking for is this

ViewData.ModelState.AddModelError("FieldName", "Date Format is not Correct!");

This will force <%=Html.ValidationMessage("FieldName") %> to show your error message.

Edit : I just checked and this will not actually solve the problem. You should refer to Craig Stuntz's answer about non-nullable type and IDataErrorInfo and then you can add your own error message for the empty field.

OwnerDisplayName: cagdas

LastEditorDisplayName: cagdas


问:
Modify all values in a dictionary
Code goes below:

```<code>d = {'a':0, 'b':0, 'c':0, 'd':0}  #at the beginning, all the values are 0.
s = 'cbad'  #a string
indices = map(s.index, d.keys())  #get every key's index in s, i.e., a-2, b-1, c-0, d-3
#then set the values to keys' index
d = dict(zip(d.keys(), indices))  #this is how I do it, any better way?
print d  #{'a':2, 'c':0, 'b':1, 'd':3}
</code>```

Any other way to do that?

PS. the code above is just a simple one to demonstrate my question.

答:
another one liner:</p>

```<code>dict([(k,s.index(k)) for (k,v) in d.items()])
</code>```

Title: Modify all values in a dictionary

Body:
Code goes below:

d = {'a':0, 'b':0, 'c':0, 'd':0}  #at the beginning, all the values are 0.
s = 'cbad'  #a string
indices = map(s.index, d.keys())  #get every key's index in s, i.e., a-2, b-1, c-0, d-3
#then set the values to keys' index
d = dict(zip(d.keys(), indices))  #this is how I do it, any better way?
print d  #{'a':2, 'c':0, 'b':1, 'd':3}

Any other way to do that?

PS. the code above is just a simple one to demonstrate my question.

Body:
another one liner:

dict([(k,s.index(k)) for (k,v) in d.items()])


问:
After the Spring boot source code is compiled, it starts to report an error in debug mode
I am trying to analyze the source code of spring boot.

I compiled the source code of spring boot 2.2.9 RELEASE, and no errors were reported. And use this version as a dependency of my test project, and the test project can be started normally in IDEA.

But when I start the project in debug mode in IDEA it produces an error.

```<code>Exception in thread "main" java.lang.NoClassDefFoundError: kotlin/collections/AbstractMutableMap
        at java.base/java.lang.ClassLoader.defineClass1(Native Method)
        at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
        at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:151)
        at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:825)
        at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:723)
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:646)
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:604)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:168)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
        at kotlinx.coroutines.debug.internal.DebugProbesImpl.<clinit>(DebugProbesImpl.kt:30)
        at kotlinx.coroutines.debug.AgentPremain.<clinit>(AgentPremain.kt:26)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:564)
        at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:513)
        at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:525)
    Caused by: java.lang.ClassNotFoundException: kotlin.collections.AbstractMutableMap
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:606)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:168)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
        ... 17 more
    *** java.lang.instrument ASSERTION FAILED ***: "result" with message agent load/premain call failed at ./open/src/java.instrument/share/native/libinstrument/JPLISAgent.c line: 422
    FATAL ERROR in native method: processing of -javaagent failed, processJavaStart failed
    Disconnected from the target VM, address: '127.0.0.1:64553', transport: 'socket'

    Process finished with exit code 1
</code>```

I've looked at many resources online, but no one seems to have encountered a similar error.

I've tried multiple variations of this, but none of them seem to work. Any ideas?

Thanks in advance.

答:
This has been fixed in IntelliJ IDEA 2021.3 in the scope of https://youtrack.jetbrains.com/issue/KTIJ-15750

Feel free to upgrade your installation

Body:
I am trying to analyze the source code of spring boot.

I compiled the source code of spring boot 2.2.9 RELEASE, and no errors were reported. And use this version as a dependency of my test project, and the test project can be started normally in IDEA.

But when I start the project in debug mode in IDEA it produces an error.

Exception in thread "main" java.lang.NoClassDefFoundError: kotlin/collections/AbstractMutableMap
        at java.base/java.lang.ClassLoader.defineClass1(Native Method)
        at java.base/java.lang.ClassLoader.defineClass(ClassLoader.java:1016)
        at java.base/java.security.SecureClassLoader.defineClass(SecureClassLoader.java:151)
        at java.base/jdk.internal.loader.BuiltinClassLoader.defineClass(BuiltinClassLoader.java:825)
        at java.base/jdk.internal.loader.BuiltinClassLoader.findClassOnClassPathOrNull(BuiltinClassLoader.java:723)
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClassOrNull(BuiltinClassLoader.java:646)
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:604)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:168)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
        at kotlinx.coroutines.debug.internal.DebugProbesImpl.<clinit>(DebugProbesImpl.kt:30)
        at kotlinx.coroutines.debug.AgentPremain.<clinit>(AgentPremain.kt:26)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:564)
        at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndStartAgent(InstrumentationImpl.java:513)
        at java.instrument/sun.instrument.InstrumentationImpl.loadClassAndCallPremain(InstrumentationImpl.java:525)
    Caused by: java.lang.ClassNotFoundException: kotlin.collections.AbstractMutableMap
        at java.base/jdk.internal.loader.BuiltinClassLoader.loadClass(BuiltinClassLoader.java:606)
        at java.base/jdk.internal.loader.ClassLoaders$AppClassLoader.loadClass(ClassLoaders.java:168)
        at java.base/java.lang.ClassLoader.loadClass(ClassLoader.java:522)
        ... 17 more
    *** java.lang.instrument ASSERTION FAILED ***: "result" with message agent load/premain call failed at ./open/src/java.instrument/share/native/libinstrument/JPLISAgent.c line: 422
    FATAL ERROR in native method: processing of -javaagent failed, processJavaStart failed
    Disconnected from the target VM, address: '127.0.0.1:64553', transport: 'socket'

    Process finished with exit code 1

I've looked at many resources online, but no one seems to have encountered a similar error.

I've tried multiple variations of this, but none of them seem to work. Any ideas?

Thanks in advance.


问:
Add fields in Serializer dynamically
I have a View in which I receive the request and it returns the serialized data

views.py

```<code>class AllotmentReportsView(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request):
        sfields = request.GET['sfields']           #I can get the fields in params
        serializer = AllotReportSerializer(items, many=True)
        return Response(serializer.data, status=status.HTTP_201_CREATED)
</code>```

serializer.py

```<code>class AllotReportSerializer(serializers.ModelSerializer):

    send_from_warehouse = serializers.SlugRelatedField(read_only=True, slug_field='name')
    transport_by = serializers.SlugRelatedField(read_only=True, slug_field='name')
    sales_order = AllotSOSerializer(many=False)
    flows = AllotFlowsSerializer(many=True)

    class Meta:
        model = Allotment
        fields = ( 'transaction_no', 'dispatch_date', 'sales_order',
                   'is_delivered', 'send_from_warehouse', 'transport_by',
                   'flows', )
</code>```

Instead of defining the fields in serializer can I pass the fields dynamically from the view sfields and pass them to the serializer ?

答:
It is not necessary to describe fields in ModelSerializer class. Django will generate it automatically according model information:

```<code>class AllotReportSerializer(serializers.ModelSerializer):

    class Meta:
        model = Allotment
        fields = ( 'transaction_no', 'dispatch_date', 'sales_order',
                   'is_delivered', 'send_from_warehouse', 'transport_by',
                   'flows', )
</code>```

is enough

If you want to add fields that not exists in model, I guess it is possible with meta classes and setattr() function. But that is looking meaningless. Also you need to add logic how to dynamically set field type and parameters.

Title: Add fields in Serializer dynamically

Body:
I have a View in which I receive the request and it returns the serialized data

views.py

class AllotmentReportsView(APIView):
    permission_classes = (permissions.IsAuthenticated,)

    def get(self, request):
        sfields = request.GET['sfields']           #I can get the fields in params
        serializer = AllotReportSerializer(items, many=True)
        return Response(serializer.data, status=status.HTTP_201_CREATED)

serializer.py

class AllotReportSerializer(serializers.ModelSerializer):

    send_from_warehouse = serializers.SlugRelatedField(read_only=True, slug_field='name')
    transport_by = serializers.SlugRelatedField(read_only=True, slug_field='name')
    sales_order = AllotSOSerializer(many=False)
    flows = AllotFlowsSerializer(many=True)

    class Meta:
        model = Allotment
        fields = ( 'transaction_no', 'dispatch_date', 'sales_order',
                   'is_delivered', 'send_from_warehouse', 'transport_by',
                   'flows', )

Instead of defining the fields in serializer can I pass the fields dynamically from the view sfields and pass them to the serializer ?

Body:
It is not necessary to describe fields in ModelSerializer class. Django will generate it automatically according model information:

class AllotReportSerializer(serializers.ModelSerializer):

    class Meta:
        model = Allotment
        fields = ( 'transaction_no', 'dispatch_date', 'sales_order',
                   'is_delivered', 'send_from_warehouse', 'transport_by',
                   'flows', )

is enough

If you want to add fields that not exists in model, I guess it is possible with meta classes and setattr() function. But that is looking meaningless. Also you need to add logic how to dynamically set field type and parameters.


问:
In what scenario bagging can be used over boosting?
I am new to data science and so far i have learnt that bagging only reduces high variance but boosting reduces both variance and bias and thus increasing the accuracy for both train and test cases.

I understand the functioning of both.  Seems like in terms of accuracy boosting always performs better than bagging.  Please correct me if i am wrong.

Is there any parameter that makes bagging or bagging based algorithms better than boosting - be it in terms of memory or speed or complex data handling or any other parameter.

答: The goals for bagging and boosting are quite different. Bagging is an ensemble technique that tries to reduce variance so one should use it in the case of low bias but high variance, E.g. KNN with low neighbour count or Fully grown decision tree. Boosting on the other hand tries reducing the bias and hence it can handle problems of high bias but low variance, E.g. Shallow Decision Tree.</p>


问:
Problem not reading GET in frindly url in PHP
If you look at the YouTube site when you search, you will see that there is a URL result and then method.

For example:

```<code>https://www.youtube.com/results?search_query=s
</code>```

My .htaccess file code:

```<code>Options +FollowSymLinks
RewriteEngine on

RewriteRule  post/(.*)/ index.php?id=$1
RewriteRule post/(.*) index.php?id=$1
</code>```

I want to put post/122 on that page for paging, for example, and I want method to be added here.

But this is where the new problem begins. Because the Get function is no longer read.

URLs are tests !!

答:
you will need the QSA flag for the rewrite rule then it will append the original query string into the new uri

```<code>Options +FollowSymLinks
RewriteEngine on

RewriteRule  post/(.*)/ index.php?id=$1 [QSA]
RewriteRule post/(.*) index.php?id=$1 [QSA]
</code>```

see https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#RewriteRule

Body:
If you look at the YouTube site when you search, you will see that there is a URL result and then method.

For example:

https://www.youtube.com/results?search_query=s

My .htaccess file code:

Options +FollowSymLinks
RewriteEngine on

RewriteRule  post/(.*)/ index.php?id=$1
RewriteRule post/(.*) index.php?id=$1

I want to put post/122 on that page for paging, for example, and I want method to be added here.

But this is where the new problem begins. Because the Get function is no longer read.

URLs are tests !!

Body:
you will need the QSA flag for the rewrite rule then it will append the original query string into the new uri

Options +FollowSymLinks
RewriteEngine on

RewriteRule  post/(.*)/ index.php?id=$1 [QSA]
RewriteRule post/(.*) index.php?id=$1 [QSA]

see https://httpd.apache.org/docs/2.4/mod/mod_rewrite.html#RewriteRule


问:
Weird response printed by Network Inspector of Bumble Bee Android Studio
Updated Android Studio to Bumble Bee and wanted to use Network Inspector. Response is no longer plain text. It works well on Network Profiler of Arctic Fox (previous version of Android Studio). I tried to look at update docs but could not find anything in this direction. Is there some setting that needs to be changed?

Android Studio Bumblebee | 2021.1.1 Patch 1

答:
I had the same problem after updating Android Studio to Bumble Bee.
Please set acceptable encodings in the request header. ("Accept-Encoding", "identity")
It works for me.</p>


问:
DBGRID Columns Title Color
I am trying to change the color of a Title cell in a particular column of a DBGRID component in Delphi XE6. I used to paint column title when the grid was sorted by that certain column.

```<code>DBGRID1.Columns[1].Title.Color := clBlue;
</code>```

Is this possible? Or is there a better way how to highlight sorted column?

答:
Well , If I understand your question ,all you need to do is to change the DBGrid
DrawingStyle properity to gdsGradient & then change the gradentEndColor & gradentStartColor to be the same color ..

Title: DBGRID Columns Title Color

Body:
I am trying to change the color of a Title cell in a particular column of a DBGRID component in Delphi XE6. I used to paint column title when the grid was sorted by that certain column.

DBGRID1.Columns[1].Title.Color := clBlue;

Is this possible? Or is there a better way how to highlight sorted column?


问:
Splitting very large string separated with comma and i need to split 50 items only per row
im having very big string on 1st row.so 1st row contains lots of items with comma like below

12345,54322,44444,222222222,444444,121,333,44444,........

I just need to split this till 50 items in every row. lets assume there are 700 items separated with comma and I want to keep till 50 items only in 1st row and then next 50 in 2nd row and so on.

I tried with the below code which splits till 50 for sure but im not sure if this will works going forward. so need help on this

```<code>OutData = Split(InpData, ",")(50)
MsgBox OutData
</code>```

答:
You can do this in many more ways, but one would be to replace every nth comma. For example through Regular Expressions:

```<code>Sub Test()

Dim s As String: s = "1,2,3,4,5,6,7,8,9,10,11"
Dim n As Long: n = 2
Dim arr() As String

With CreateObject("vbscript.regexp")
    .Global = True
    .Pattern = "([^,]*(?:,[^,]*){" & n - 1 & "}),"
    arr = Split(.Replace(s, "$1|"), "|")
End With

End Sub
</code>```

The pattern used means:

( - Open 1st capture group;

[^,]* - Match 0+ (Greedy) characters other than comma;

(?: - Open a nested non-capture group;

,[^,]* - Match a comma and again 0+ characters other than comma;

){1} - Close the non-capture group and match n-1 times (1 time in the given example);

), - Close the capture group and match a literal comma.

Replace every match with the content of the 1st capture group and a character you know is not in the full string so we can split on that character. See an online demo

I suppose you can do whatever you like with the resulting array. You probably want to transpose it into the worksheet.

Body:
im having very big string on 1st row.so 1st row contains lots of items with comma like below

12345,54322,44444,222222222,444444,121,333,44444,........

I just need to split this till 50 items in every row. lets assume there are 700 items separated with comma and I want to keep till 50 items only in 1st row and then next 50 in 2nd row and so on.

I tried with the below code which splits till 50 for sure but im not sure if this will works going forward. so need help on this

OutData = Split(InpData, ",")(50)
MsgBox OutData

Body:
You can do this in many more ways, but one would be to replace every nth comma. For example through Regular Expressions:

Sub Test()

Dim s As String: s = "1,2,3,4,5,6,7,8,9,10,11"
Dim n As Long: n = 2
Dim arr() As String

With CreateObject("vbscript.regexp")
    .Global = True
    .Pattern = "([^,]*(?:,[^,]*){" & n - 1 & "}),"
    arr = Split(.Replace(s, "$1|"), "|")
End With

End Sub

The pattern used means:

( - Open 1st capture group;

[^,]* - Match 0+ (Greedy) characters other than comma;

(?: - Open a nested non-capture group;

,[^,]* - Match a comma and again 0+ characters other than comma;

){1} - Close the non-capture group and match n-1 times (1 time in the given example);

), - Close the capture group and match a literal comma.

Replace every match with the content of the 1st capture group and a character you know is not in the full string so we can split on that character. See an online demo

I suppose you can do whatever you like with the resulting array. You probably want to transpose it into the worksheet.


问:
REACT - Hook make infinite loop
i have a problem with an hooks.

When i make

```<code>     export default function Checkout() {
  const { readRemoteFile } = usePapaParse();
  const [parsedCsvData, setParsedCsvData] = useState([]);

  const handleReadRemoteFile = file => {
    readRemoteFile(file, {
      complete: (results) => {
        setParsedCsvData(results.data);
          },
    });
    };
    handleReadRemoteFile(CSVsource);
    }
</code>```

I have an infinite loop but when i make

```<code>     export default function Checkout() {
  const { readRemoteFile } = usePapaParse();
  const [parsedCsvData, setParsedCsvData] = useState([]);

  const handleReadRemoteFile = file => {
    readRemoteFile(file, {
      complete: (results) => {
        console.log(results.data);
          },
    });
    };
    handleReadRemoteFile(CSVsource);
    }
</code>```

I have'nt the problem.

Have you an idea ?
Thank's Yann.

答:
While the component code you posted is still incomplete (CSVsource is undefined, there's no return), I think the problem is visible now:

You're running handleReadRemoteFile(CSVsource) on every render (because you're calling it directly). When the file is read, you are setting parsedCsvData, which (because state updates and prop updates trigger a rerender) renders the component again, triggering handleReadRemoteFile once again...

So what's the solution?

Data fetching is a classical example of using the useEffect hook. The following code should do what you want

```<code>const { readRemoteFile } = usePapaParse();
const [parsedCsvData, setParsedCsvData] = useState([]);

useEffect(()=>{
  readRemoteFile(CSVSource, {
    complete: results => setParsedCsvData(results.data);
  });
}, [CSVsource]); // rerun this whenever CSVSource changes.
</code>```

Please read up on the useEffect hook in the React docs.

Note: there's one problem with the code I posted above. When the component is unmounted while the CSV is still loading, you will get an error "state update on unmounted component" as soon as the loading finished. To mitigate this, use the return function of useEffect in combination with a local variable.

So the final code looks like this:

```<code>useEffect(()=>{
  let stillMounted = true;
  readRemoteFile(CSVSource, {
    complete: results => {
       if(!stillMounted) return; // prevent update on unmounted component
       setParsedCsvData(results.data);
    }
  });
  return ()=>stillMounted = false; // this function is ran before the effect is ran again and on unmount
}, [CSVsource]);
</code>```

Title: REACT - Hook make infinite loop

Body:
i have a problem with an hooks.

When i make

     export default function Checkout() {
  const { readRemoteFile } = usePapaParse();
  const [parsedCsvData, setParsedCsvData] = useState([]);

  const handleReadRemoteFile = file => {
    readRemoteFile(file, {
      complete: (results) => {
        setParsedCsvData(results.data);
          },
    });
    };
    handleReadRemoteFile(CSVsource);
    }

I have an infinite loop but when i make

     export default function Checkout() {
  const { readRemoteFile } = usePapaParse();
  const [parsedCsvData, setParsedCsvData] = useState([]);

  const handleReadRemoteFile = file => {
    readRemoteFile(file, {
      complete: (results) => {
        console.log(results.data);
          },
    });
    };
    handleReadRemoteFile(CSVsource);
    }

I have'nt the problem.

Have you an idea ?
Thank's Yann.

Body:
While the component code you posted is still incomplete (CSVsource is undefined, there's no return), I think the problem is visible now:

You're running handleReadRemoteFile(CSVsource) on every render (because you're calling it directly). When the file is read, you are setting parsedCsvData, which (because state updates and prop updates trigger a rerender) renders the component again, triggering handleReadRemoteFile once again...

So what's the solution?

Data fetching is a classical example of using the useEffect hook. The following code should do what you want

const { readRemoteFile } = usePapaParse();
const [parsedCsvData, setParsedCsvData] = useState([]);

useEffect(()=>{
  readRemoteFile(CSVSource, {
    complete: results => setParsedCsvData(results.data);
  });
}, [CSVsource]); // rerun this whenever CSVSource changes.

Please read up on the useEffect hook in the React docs.

Note: there's one problem with the code I posted above. When the component is unmounted while the CSV is still loading, you will get an error "state update on unmounted component" as soon as the loading finished. To mitigate this, use the return function of useEffect in combination with a local variable.

So the final code looks like this:

useEffect(()=>{
  let stillMounted = true;
  readRemoteFile(CSVSource, {
    complete: results => {
       if(!stillMounted) return; // prevent update on unmounted component
       setParsedCsvData(results.data);
    }
  });
  return ()=>stillMounted = false; // this function is ran before the effect is ran again and on unmount
}, [CSVsource]);


问:
Is it any possibility to create login in .NET Maui?
I am looking for any possibility to create a login in .NET Maui Desktop App. The identity provider should be IdentityServer. Is it any sample how to do it? I tried with oidc client, but failed because of redirect uri.</p>

答: Following the example for Xamarin Authentication and Authorization should work for maui. If there is a redirect uri issue it could be you haven't registered it in IdentityServer</p>


问:
Wordpress Footer is shown in the middle of the page
Ich have a problem with my custom wordpress page.
I want to use the default header and footer.
This issue only happens on safari. On Chrome it works fine!

The footer is shown in the middle of the page and not at the end of the page.
Do you have any suggestion?

Here is my code.

```<code>        <!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fahrzeugkunde - TLF</title>
    <link rel="stylesheet" href="index.css">
    <link rel="stylesheet" href="Modal.css">
</head>

<body>
    <div>
        <?php require($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
        get_header(); ?>
    </div>
    <main class="feuerwehr-body">
        <div class="feuerwehr-flexContainer">
            <div class="feuerwehr-imageContainer">
                <img class="feuerwehr-image" src="../images/TLF/GA2.JPG" alt="GA2" usemap="#image-mapGA2">
                <map name="image-mapGA2">
                    <area class="area" shape="rect" coords=" 1885, 1611, 2101, 2130 " alt="placeholder" onclick="openInfo('Feuerlöscher', 'Das ist ein Feuerlöscher')">

                </map>
            </div>

            <div class="feuerwehr-imageContainer">
                <img class="feuerwehr-image" src="../images/TLF/GA4.JPG" alt="GA4" usemap="#image-mapGA4">
                <map name="image-mapGA4">
                    <area class="area" shape="rect" coords=" 97, 525, 1340, 790 " alt="placeholder" onclick="openInfo('Feuerlöscher', 'Das ist ein Feuerlöscher')">
                </map>
            </div>
            <div class="feuerwehr-imageContainer">
                <img class="feuerwehr-image" src="../images/TLF/GA6.JPG" alt="GA6" usemap="#image-mapGA6">
                <map name="image-mapGA6">
                    <area class="area" shape="rect" coords=" 199, 642, 366, 1829 " alt="placeholder" onclick="openInfo('Feuerlöscher', 'Das ist ein Feuerlöscher')">

                </map>
            </div>

            <div id="myModal" class="Modal is-hidden is-visuallyHidden">
                <!-- Modal content -->
                <div class="Modal-content" id="modal-image-container">
                    <div class="modal-image" id="modal-image">

                    </div>
                    <div style="display: flex; justify-content: end;">
                        <button class="custom-button custom-button--inline" id="sig-cancellationBtnImage">Zurück</button>
                    </div>
                </div>
            </div>
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script src="jquery.rwdImageMaps.min.js"></script>
        <script>
            $(document).ready(function(e) {
                $('img[usemap]').rwdImageMaps();
            });
        </script>
        <script src="Modal.js"></script>
        <script src="index.js"></script>
    </main>
    <div style="display: none">
        <?php get_footer(); ?>
    </div>

</html>
</code>```

答:
The get_footer() wordpress method add a html template code to your page : https://developer.wordpress.org/reference/functions/get_footer/

The call should be INSIDE html tags (same with get_header()). Maybe chrome is ok with that but safari seems to be more sensitive.

Anyway, the wordpress load a lot of css and js files and we cannot figure what style is applying on your page in your post.

Body:
Ich have a problem with my custom wordpress page.
I want to use the default header and footer.
This issue only happens on safari. On Chrome it works fine!

The footer is shown in the middle of the page and not at the end of the page.
Do you have any suggestion?

Here is my code.

        <!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fahrzeugkunde - TLF</title>
    <link rel="stylesheet" href="index.css">
    <link rel="stylesheet" href="Modal.css">

        <?php require($_SERVER['DOCUMENT_ROOT'] . '/wp-load.php');
        get_header(); ?>

                <map name="image-mapGA2">
                    <area class="area" shape="rect" coords=" 1885, 1611, 2101, 2130 " alt="placeholder" onclick="openInfo('Feuerlöscher', 'Das ist ein Feuerlöscher')">

                </map>

                <map name="image-mapGA4">
                    <area class="area" shape="rect" coords=" 97, 525, 1340, 790 " alt="placeholder" onclick="openInfo('Feuerlöscher', 'Das ist ein Feuerlöscher')">
                </map>

                <map name="image-mapGA6">
                    <area class="area" shape="rect" coords=" 199, 642, 366, 1829 " alt="placeholder" onclick="openInfo('Feuerlöscher', 'Das ist ein Feuerlöscher')">

                </map>

                        <button class="custom-button custom-button--inline" id="sig-cancellationBtnImage">Zurück</button>

        <?php get_footer(); ?>


问:
jquery: $(window).scrollTop() but no $(window).scrollBottom()
I want to place an element to the bottom of the page whenever the user scrolls the page. It's like "fixed position" but I can't use "position: fixed" css as many of my clients' browser can't support that.

I noticed jquery can get current viewport's top position, but how can I get the bottom of the scroll viewport?

So I am asking how to know: $(window).scrollBottom()

答:
i try that code and it work

 // scroll top
 scroll(){
    let x:any= document.getElementById('chat')
    x.scrollTop = 9000;
  }
  // scroll buttom
  scrollrev(){
    let x:any= document.getElementById('chat')
    x.scrollTop = -9000;
  }```


问:
Code required on enter in timeMeasureEnd block if an agent has to pass without passing through it's corresponding timeMeasureStart Anylogic
I would like to time different segments of my model where some agents go, but not all. However, all agents no matter if they went through the timeMeasureStart or not, will have to pass by its corresponding timeMeasureEnd. How to proceed without getting the error of The agent has not been through a corresponding TimeMeasureStart object ?

答:
Instead of timeMeasureStart and timeMeasureEnd blocks, you can just add variables inside your agent called startTime, endTime and cycleTime of type double.

Then, at the end of the process flow, you can type agent.cycleTime=agent.endTime-agent.startTime;. You will have the time in system for each agent. And you have the freedom to choose which agents' information to keep and which ones to discard.


问:
Replace for loop that indexes two arrays and applies a function on each row
I have a for-loop that works on two values and I would like to apply it in a faster way or vectorise it if possible. My original for-loop looks something like this

```<code>import numpy as np

x = [1,2,3]
y = [0,0,0]

for i in range(len(x)):

    # index value in each element
    xi = x[i]
    yi = y[i]

    # apply function some bivariate function
    print(np.sum(xi,yi))
</code>```

I was thinking maybe I could use the list approach but the output came out as below.

```<code>x = [1,2,3]
y = [0,0,0]

[np.sum(i, j) for i in x for j in y]
</code>```
```<code># output
[1, 1, 1, 2, 2, 2, 3, 3, 3]
</code>```

What are better methods to replace the initial for-loop statement? My actual function is not a sum as in the initial example, that is just a dummy function.

答:
IIUC, use zip

```<code>>>> [np.sum(i, j) for i, j in zip(x, y)]
[1, 2, 3]
</code>```

Body:
I have a for-loop that works on two values and I would like to apply it in a faster way or vectorise it if possible. My original for-loop looks something like this

import numpy as np

x = [1,2,3]
y = [0,0,0]

for i in range(len(x)):

    # index value in each element
    xi = x[i]
    yi = y[i]

    # apply function some bivariate function
    print(np.sum(xi,yi))

I was thinking maybe I could use the list approach but the output came out as below.

x = [1,2,3]
y = [0,0,0]

[np.sum(i, j) for i in x for j in y]

# output
[1, 1, 1, 2, 2, 2, 3, 3, 3]

What are better methods to replace the initial for-loop statement? My actual function is not a sum as in the initial example, that is just a dummy function.

Body:
IIUC, use zip

>>> [np.sum(i, j) for i, j in zip(x, y)]
[1, 2, 3]


问:
Data download functionality for API response Angular
I have an API response where I'm getting data as comma separated values and not as JSON objects. I need to export this data into CSV file. Can someone please suggest a method to do this?</p>

答:
You could parse your data to a JSON-object:

```<code>  const apiData: string = 'value1,value2,value3';
  const data: string[] = apiData.split(',');
</code>```

And then you could use a combination of xlsx and fileSaver

Pseudocode:

```<code>    const worksheet: xlsx.WorkSheet = xlsx.utils.json_to_sheet(data);
    const workbook: xlsx.WorkBook = {
      Sheets: { [worksheetName]: worksheet },
      SheetNames: [worksheetName]
    };

    const buffer = xlsx.write(workbook, { 'csv', type: 'array' });
    const blob = new Blob([buffer], { type: 'text/comma-separated-values' });

    fileSaver.saveAs(blob, 'filename.csv');

</code>```

Body:
You could parse your data to a JSON-object:

  const apiData: string = 'value1,value2,value3';
  const data: string[] = apiData.split(',');

And then you could use a combination of xlsx and fileSaver

Pseudocode:

    const worksheet: xlsx.WorkSheet = xlsx.utils.json_to_sheet(data);
    const workbook: xlsx.WorkBook = {
      Sheets: { [worksheetName]: worksheet },
      SheetNames: [worksheetName]
    };

    const buffer = xlsx.write(workbook, { 'csv', type: 'array' });
    const blob = new Blob([buffer], { type: 'text/comma-separated-values' });

    fileSaver.saveAs(blob, 'filename.csv');


问:
Choosing from an array many
```<code>$first  = 1.22;
$second = 1.55;
$third  = 1.77;
$fourth = 1.3;
$fifth = 1.5;
$sixth = 1.2;
$seventh = 1.4;
$eighth = 1.8;
$ninghth = 1.9;
$tenth = 1.24;

$array  = array($first, $second, $third,$fourth, $fifth, $sixth, $seventh, $eighth, $ninghth, $tenth);
echo $array[mt_rand(0, count($array) - 1)]*$array[mt_rand(0, count($array) - 1)];
</code>```

This works but i need it to show me what variables were multiplied and also, assign a text value on them.

答:
If you have a multi dimensional array where the text is the first item and the value the second item and you want to show which text and value are multiplied, you might use for example:

```<code>$games = [["First", 1.14], ["2nd", 1.18], ["3rd", 1.22]];
$rand1 = array_rand($games);
$rand2 = array_rand($games);
$val1 = $games[$rand1][1];
$val2 = $games[$rand2][1];

echo sprintf(
    "The product of '%s' (%f) and '%s' (%f) is %f",
    $games[$rand1][0], $val1, $games[$rand2][0], $val2, $val1 * $val2
);
</code>```

The output has the form of

```<code>The product of '2nd' (1.180000) and 'First' (1.140000) is 1.345200
</code>```

See a PHP demo.

Title: Choosing from an array many

Body:
$first  = 1.22;
$second = 1.55;
$third  = 1.77;
$fourth = 1.3;
$fifth = 1.5;
$sixth = 1.2;
$seventh = 1.4;
$eighth = 1.8;
$ninghth = 1.9;
$tenth = 1.24;

$array  = array($first, $second, $third,$fourth, $fifth, $sixth, $seventh, $eighth, $ninghth, $tenth);
echo $array[mt_rand(0, count($array) - 1)]*$array[mt_rand(0, count($array) - 1)];

This works but i need it to show me what variables were multiplied and also, assign a text value on them.

Body:
If you have a multi dimensional array where the text is the first item and the value the second item and you want to show which text and value are multiplied, you might use for example:

$games = [["First", 1.14], ["2nd", 1.18], ["3rd", 1.22]];
$rand1 = array_rand($games);
$rand2 = array_rand($games);
$val1 = $games[$rand1][1];
$val2 = $games[$rand2][1];

echo sprintf(
    "The product of '%s' (%f) and '%s' (%f) is %f",
    $games[$rand1][0], $val1, $games[$rand2][0], $val2, $val1 * $val2
);

The output has the form of

The product of '2nd' (1.180000) and 'First' (1.140000) is 1.345200

See a PHP demo.


问:
Monaco-editor automatic language detection doesn't work
I followed this answer on how to let monaco automatically detect the language of your file:

const model = monaco.editor.createModel(fileContent, undefined, filePath/* full path to the file */);
editor.setModel(model);
```

The content of the file does show up in the editor, but there's no syntax highlighting, just white text. I also tried replacing filePath with fileName (base name of the file), however, it still doesn't work. Is there a fix to this?

答:
The monaco.editor.createModel function third parameter must be a Uri, not a simple string.
You can create a Uri from a filename, as specified in the answer you linked :

const model = monaco.editor.createModel(fileContent, undefined, monaco.Uri.file(fileName));
editor.setModel(model);
```

Body:
I followed this answer on how to let monaco automatically detect the language of your file:

const model = monaco.editor.createModel(fileContent, undefined, filePath/* full path to the file */);
editor.setModel(model);

The content of the file does show up in the editor, but there's no syntax highlighting, just white text. I also tried replacing filePath with fileName (base name of the file), however, it still doesn't work. Is there a fix to this?


问:
How to implement shortcuts in an application
I am building a home application and want to be able to put shortcuts on the main screen,  just like how the default home applications do it.  Can anyone help me with this.  If not then can someone atleast point me towards some resources that will help me with this.</p>

答:
I am not sure exactly what you want since your question seems a bit broad. However, one tip would be to take a look at the source code for the launcher.

Link to old launcher source code

Link to new launcher source code

Or take a look at launcher plus:

http://code.google.com/p/android-launcher-plus/

Edit: kernel.org was hacked.
Link to old launcher code - new link

Link to new launcher code - new link


问:
How to set Date limit to 6 months from current date Flutter?
I need to set the calendar limit to next 6 months from now. the code i tried to run is given below:

```<code>Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime.now(),
        lastDate: DateTime(DateTime.now().month + 6));
    if (picked != null && picked != selectedDate)
      setState(() {
        selectedDate = picked;
      });
  }
</code>```

When i try to run this code i get the given error:

```<code>Unhandled Exception: 'package:flutter/src/material/date_picker.dart': Failed assertion: line 226 pos 5: '!lastDate.isBefore(firstDate)': lastDate 0008-01-01 00:00:00.000 must be on or after firstDate 2022-02-09 00:00:00.000.
E/flutter ( 1931): #0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39)
E/flutter ( 1931): #1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)
</code>```

答:
A clean way to add something to a DateTime is:

```<code>DateTime myDate = DateTime.now();
DateTime myDateWithSixMonthsAdded = myDate.add(Duration(days: 180));
</code>```

Add 180 days since Duration does not have a months parameter.

Body:
I need to set the calendar limit to next 6 months from now. the code i tried to run is given below:

Future<void> _selectDate(BuildContext context) async {
    final DateTime? picked = await showDatePicker(
        context: context,
        initialDate: selectedDate,
        firstDate: DateTime.now(),
        lastDate: DateTime(DateTime.now().month + 6));
    if (picked != null && picked != selectedDate)
      setState(() {
        selectedDate = picked;
      });
  }

When i try to run this code i get the given error:

Unhandled Exception: 'package:flutter/src/material/date_picker.dart': Failed assertion: line 226 pos 5: '!lastDate.isBefore(firstDate)': lastDate 0008-01-01 00:00:00.000 must be on or after firstDate 2022-02-09 00:00:00.000.
E/flutter ( 1931): #0      _AssertionError._doThrowNew (dart:core-patch/errors_patch.dart:46:39)
E/flutter ( 1931): #1      _AssertionError._throwNew (dart:core-patch/errors_patch.dart:36:5)

Body:
A clean way to add something to a DateTime is:

DateTime myDate = DateTime.now();
DateTime myDateWithSixMonthsAdded = myDate.add(Duration(days: 180));

Add 180 days since Duration does not have a months parameter.


问:
How to copy Youtube text by using pyautogui?
```<code>import pyautogui

pyautogui.moveTo(x=100,y=100,duration=10)

keyDown = ('cntrl')

pyautogui.press('c')
</code>```

step 1 :#importing pyautogui module.
step 2:#moving mouse to the youtube text i want to copy
step 3:#pressing control to copy the text
step 4:#pressing c to copy the text.
In simple words I dont want to do my work of copying youtube title to text file,I wanna automate it,cause its work from free intership.

答:
if you are looking to get text from a page, I strongly recommend looking into pytesseract's image to text conversion.

It's super easy, here is an example of how it's used combining PyAutoGui and Tesseract OCR

Here I am just trying to get the string from a screenshot from a specific region on the screen.

```<code>#Looking for the part on the screen I want to convert, you can predefine this.
findCount = pyautogui.locateOnScreen(os.path.join(curPath, 'asset', 'control.png'), confidence=0.9)

#Finding center of the area located
control_ = pyautogui.center(findCount)

#Taking a screenshot, the OS.path is just setting the path of the director, you can use an absolute path, I am then creating the region from the center of the located image.
pyautogui.screenshot(os.path.join(curPath, 'asset', 'controlValue.png'), region=(int(int(control_[0])-80), int(int(control_[1])-40), 200, 70))

#I am now opening the image
img = Image.open(os.path.join(curPath, 'asset', 'controlValue.png'))

#Converting the image to string
result = pytesseract.image_to_string(img)

#Printing results
print(result)
</code>```

Here is a link to the windows pytesseract installer and the OCR executable:

https://pypi.org/project/pytesseract/
https://github.com/UB-Mannheim/tesseract/wiki

Also at the top of your code, you need to define the OCR executable in order for this to work:

pytesseract.pytesseract.tesseract_cmd = r"$Your installation path from the UB-Mannheim installer, or whereever tesseract.exe is installed."

Body:
import pyautogui

pyautogui.moveTo(x=100,y=100,duration=10)

keyDown = ('cntrl')

pyautogui.press('c')

step 1 :#importing pyautogui module.
step 2:#moving mouse to the youtube text i want to copy
step 3:#pressing control to copy the text
step 4:#pressing c to copy the text.
In simple words I dont want to do my work of copying youtube title to text file,I wanna automate it,cause its work from free intership.

Body:
if you are looking to get text from a page, I strongly recommend looking into pytesseract's image to text conversion.

It's super easy, here is an example of how it's used combining PyAutoGui and Tesseract OCR

Here I am just trying to get the string from a screenshot from a specific region on the screen.

#Looking for the part on the screen I want to convert, you can predefine this.
findCount = pyautogui.locateOnScreen(os.path.join(curPath, 'asset', 'control.png'), confidence=0.9)

#Finding center of the area located
control_ = pyautogui.center(findCount)

#Taking a screenshot, the OS.path is just setting the path of the director, you can use an absolute path, I am then creating the region from the center of the located image.
pyautogui.screenshot(os.path.join(curPath, 'asset', 'controlValue.png'), region=(int(int(control_[0])-80), int(int(control_[1])-40), 200, 70))

#I am now opening the image
img = Image.open(os.path.join(curPath, 'asset', 'controlValue.png'))

#Converting the image to string
result = pytesseract.image_to_string(img)

#Printing results
print(result)

Here is a link to the windows pytesseract installer and the OCR executable:

https://pypi.org/project/pytesseract/
https://github.com/UB-Mannheim/tesseract/wiki

Also at the top of your code, you need to define the OCR executable in order for this to work:

pytesseract.pytesseract.tesseract_cmd = r"$Your installation path from the UB-Mannheim installer, or whereever tesseract.exe is installed."


问:
Navbar disappears after scrollIntoView() use on mobile view
Problem: NavBar disappears after scrollIntoView() used on mobile view.

Related JS

```<code>function disableScroll() {
  window.addEventListener('DOMMouseScroll', preventDefault, false); // older FF
  window.addEventListener(wheelEvent, preventDefault, wheelOpt); // modern desktop
  window.addEventListener('touchmove', preventDefault, wheelOpt); // mobile
  window.addEventListener('keydown', preventDefaultForScrollKeys, false);
}

function enableScroll() {
  window.removeEventListener('DOMMouseScroll', preventDefault, false);
  window.removeEventListener(wheelEvent, preventDefault, wheelOpt);
  window.removeEventListener('touchmove', preventDefault, wheelOpt);
  window.removeEventListener('keydown', preventDefaultForScrollKeys, false);
}

function scroll_to_chapters() {
    const chapters = document.getElementsByClassName("chapter_list")[0];
    if (nav.classList.contains("nav-active")) {
        navLinks.forEach((link) => {
            if (link.style.animation) {
                link.style.animation = '';
            }
        });
        enableScroll();
        burger.classList.toggle('toggle');
        nav.classList.toggle('nav-active');
    }
    chapters.scrollIntoView({ block: 'start',  behavior: 'smooth' })
}

const navSlide = ()=> {
    burger.addEventListener('click', ()=> {
        //Toggle NavBar
        nav.classList.toggle('nav-active');
        //Animate Links
        navLinks.forEach((link, index)=> {
            if (link.style.animation) {
                enableScroll();
                link.style.animation = '';
            }
            else {
                disableScroll();
                link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 0.5}s`;
            }
        });
        burger.classList.toggle('toggle');
    });
}
</code>```

I'm not quite sure but there might be a problem with the disabling and enabling scrolling. I didn't want mobile users to be able to scroll while the navbar menus are opened.

Navbar HTML

```<code><div class="wrapper">
    <div class="fix">
        <header>
            <div class="container">
                <nav>
                <a href="/" data-attr="img"><img src="{% static 'img/northernlogo.png' %}" class="logo" alt="logo"></a>
                <ul class="nav-links">
                    <li><a href="/">Home</a></li>
                    <li><a href="/" onclick="scroll_to_chapters();return false;">Chapters</a></li>
                    <li><a href="/about">About</a></li>
                    <li><a href="/links">Links</a></li>
                </ul>
                <div class="burger">
                    <div class="line1"></div>
                    <div class="line2"></div>
                    <div class="line3"></div>
                </div>
                </nav>
            </div>
        </header>
    </div>
</div>
</code>```

Related CSS

```<code>.container {
    width: 100%;
    margin: 0 0;
}

.container::after {
    content: '';
    display: grid;
    clear: both;
}

.burger {
    display: none;
    margin-top: 20px;
    cursor: pointer;
}

.burger div {
    width: 25px;
    height: 3px;
    background: #EEEEEE;
    margin: 5px;
    transition: all 0.3s ease;
}

@media only screen and (max-width: 800px) {
    .wrapper {
        overflow: hidden;
        position: relative;
    }
    .nav-links {
        -webkit-box-shadow: inset 0 0.5em 1.5em -0.5em black;
        position: absolute;
        right: 0;
        height: 100%;
        top: 70px;
        background-color: #3a345c;
        z-index: 99;
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 100%;
        transform: translateX(100%);
        transition: transform 0.5s ease-in;
    }
    .nav-links li {
        opacity: 0;
        padding-bottom: 50px;
        padding-top: 50px;
    }

    .nav-links li a {
        font-size: 20px;
        font-weight: bold;
    }

    .burger {
        display: block;
    }
}
</code>```

Picture of the Error

Before
After

How to Reproduce

Open the website on mobile view. Open the navbar from the home menu and click chapters. It'll take you to the chapters but now the navbar is gone.

Editor's note:

The accepted answer features a self-contained reproducible example.

答:
I do not know what is wrong with scrollIntoView, but I remark that when I move the chapiters parts to be a direct child of body, that problem disapear.

However, there is a way to do that same behavior without any js code:

In your CSS code, add scroll-behavior: smooth; to the root.

Add an id to the chapiter :

Turn the href attribut of chapiter link in to : an page#id link :

You can find a doc on scroll-behavior href="https://developer.mozilla.org/en-US/docs/Web/CSS/scroll-behavior" rel="nofollow noreferrer">here.

Body:
Problem: NavBar disappears after scrollIntoView() used on mobile view.

Related JS

function disableScroll() {
  window.addEventListener('DOMMouseScroll', preventDefault, false); // older FF
  window.addEventListener(wheelEvent, preventDefault, wheelOpt); // modern desktop
  window.addEventListener('touchmove', preventDefault, wheelOpt); // mobile
  window.addEventListener('keydown', preventDefaultForScrollKeys, false);
}

function enableScroll() {
  window.removeEventListener('DOMMouseScroll', preventDefault, false);
  window.removeEventListener(wheelEvent, preventDefault, wheelOpt);
  window.removeEventListener('touchmove', preventDefault, wheelOpt);
  window.removeEventListener('keydown', preventDefaultForScrollKeys, false);
}

function scroll_to_chapters() {
    const chapters = document.getElementsByClassName("chapter_list")[0];
    if (nav.classList.contains("nav-active")) {
        navLinks.forEach((link) => {
            if (link.style.animation) {
                link.style.animation = '';
            }
        });
        enableScroll();
        burger.classList.toggle('toggle');
        nav.classList.toggle('nav-active');
    }
    chapters.scrollIntoView({ block: 'start',  behavior: 'smooth' })
}

const navSlide = ()=> {
    burger.addEventListener('click', ()=> {
        //Toggle NavBar
        nav.classList.toggle('nav-active');
        //Animate Links
        navLinks.forEach((link, index)=> {
            if (link.style.animation) {
                enableScroll();
                link.style.animation = '';
            }
            else {
                disableScroll();
                link.style.animation = `navLinkFade 0.5s ease forwards ${index / 7 + 0.5}s`;
            }
        });
        burger.classList.toggle('toggle');
    });
}

I'm not quite sure but there might be a problem with the disabling and enabling scrolling. I didn't want mobile users to be able to scroll while the navbar menus are opened.

Navbar HTML

Home

Chapters

About

Links

Related CSS

.container {
    width: 100%;
    margin: 0 0;
}

.container::after {
    content: '';
    display: grid;
    clear: both;
}

.burger {
    display: none;
    margin-top: 20px;
    cursor: pointer;
}

.burger div {
    width: 25px;
    height: 3px;
    background: #EEEEEE;
    margin: 5px;
    transition: all 0.3s ease;
}

@media only screen and (max-width: 800px) {
    .wrapper {
        overflow: hidden;
        position: relative;
    }
    .nav-links {
        -webkit-box-shadow: inset 0 0.5em 1.5em -0.5em black;
        position: absolute;
        right: 0;
        height: 100%;
        top: 70px;
        background-color: #3a345c;
        z-index: 99;
        display: flex;
        flex-direction: column;
        align-items: center;
        width: 100%;
        transform: translateX(100%);
        transition: transform 0.5s ease-in;
    }
    .nav-links li {
        opacity: 0;
        padding-bottom: 50px;
        padding-top: 50px;
    }

    .nav-links li a {
        font-size: 20px;
        font-weight: bold;
    }

    .burger {
        display: block;
    }
}

Picture of the Error

Before
After

How to Reproduce

Open the website on mobile view. Open the navbar from the home menu and click chapters. It'll take you to the chapters but now the navbar is gone.

Editor's note:

The accepted answer features a self-contained reproducible example.

Body:
I do not know what is wrong with scrollIntoView, but I remark that when I move the chapiters parts to be a direct child of body, that problem disapear.

However, there is a way to do that same behavior without any js code:

In your CSS code, add scroll-behavior: smooth; to the root.

Add an id to the chapiter : <div id="chap_id" class="chapter_list">

Turn the href attribut of chapiter link in to : an page#id link : <a href="page_chapters#chap_id">

You can find a doc on scroll-behavior here.


问:
Virtual webcam feature not available after building OBS-Studio from latest source code on Windows 10
I tried building OBS Studio from latest source code. I am able to build successfully by following

https://github.com/obsproject/obs-studio/wiki/Install-Instructions#windows-build-directions

I am able to run final build produced at obs-studio\build\rundir\Debug\bin\64bit\obs64 but I am not seeing option to enabling Virtual Webcam at right bottom buttons below Start Streaming.

Here are files generated by build process

```<code>alok@LAPTOP-DG8ME7Q5:/mnt/c/Users/alokm/obs-studio$ tree build/plugins/win-dshow/Debug/
build/plugins/win-dshow/Debug/
├── win-dshow.dll
├── win-dshow.exp
├── win-dshow.lib
└── win-dshow.pdb

alok@LAPTOP-DG8ME7Q5:/mnt/c/Users/alokm/obs-studio$ tree build/rundir/Debug/obs-plugins/64bit/
build/rundir/Debug/obs-plugins/64bit/
├── coreaudio-encoder.dll
├── coreaudio-encoder.pdb
├── decklink-captions.dll
├── decklink-captions.pdb
├── decklink-ouput-ui.dll
├── decklink-ouput-ui.pdb
├── enc-amf.dll
├── enc-amf.pdb
├── frontend-tools.dll
├── frontend-tools.pdb
├── image-source.dll
├── image-source.pdb
├── obs-ffmpeg.dll
├── obs-ffmpeg.pdb
├── obs-filters.dll
├── obs-filters.pdb
├── obs-outputs.dll
├── obs-outputs.pdb
├── obs-qsv11.dll
├── obs-qsv11.pdb
├── obs-text.dll
├── obs-text.pdb
├── obs-transitions.dll
├── obs-transitions.pdb
├── obs-vst.dll
├── obs-vst.pdb
├── obs-x264.dll
├── obs-x264.pdb
├── rtmp-services.dll
├── rtmp-services.pdb
├── text-freetype2.dll
├── text-freetype2.pdb
├── win-capture.dll
├── win-capture.pdb
├── win-decklink.dll
├── win-decklink.pdb
├── win-dshow.dll
├── win-dshow.pdb
├── win-mf.dll
├── win-mf.pdb
├── win-wasapi.dll
└── win-wasapi.pdb
</code>```

What is wrong from my side so I am not seeing button to enable Virtual Webcam?

答:
This must be set to build the Virtual Camera features while building.
This is mentioned as optional in the wiki.

VIRTUALCAM_GUID - Set to any random GUID value.
Use any GUID generator : GUID Generator

Refer : https://obsproject.com/wiki/Install-Instructions

After generating obs.exe/obs64.exe you have to install the virtual camera,

To install an OBS Virtual Camera:

In the obs-studio installation directory
(for Visual Studio builds, this is '[build dir]/rundir/[build type]'),
run data\obs-plugins\win-dshow\virtualcam-install.bat as administrator.

Don't forget to uninstall your build's virtual camera before cleaning/deleting your build files.

If you already have a standard OBS Studio installation, you will need to uninstall its Virtual Camera first,

To uninstall an OBS Virtual Camera:

Close any applications that were using the OBS Virtual Camera.

In the obs-studio installation directory, run data\obs-plugins\win-dshow\virtualcam-uninstall.bat as administrator.

if still not enabled and if your machine is 64bit, do the below change
filename :  ..obs-studio\plugins\win-dshow\dshow-plugin.cpp
function : obs_module_load

change the argument for the function vcam_installed(false) to vcam_installed(true)

This change will let the application check 64bit registry entry.

Body:
I tried building OBS Studio from latest source code. I am able to build successfully by following

https://github.com/obsproject/obs-studio/wiki/Install-Instructions#windows-build-directions

I am able to run final build produced at obs-studio\build\rundir\Debug\bin\64bit\obs64 but I am not seeing option to enabling Virtual Webcam at right bottom buttons below Start Streaming.

Here are files generated by build process

alok@LAPTOP-DG8ME7Q5:/mnt/c/Users/alokm/obs-studio$ tree build/plugins/win-dshow/Debug/
build/plugins/win-dshow/Debug/
├── win-dshow.dll
├── win-dshow.exp
├── win-dshow.lib
└── win-dshow.pdb

alok@LAPTOP-DG8ME7Q5:/mnt/c/Users/alokm/obs-studio$ tree build/rundir/Debug/obs-plugins/64bit/
build/rundir/Debug/obs-plugins/64bit/
├── coreaudio-encoder.dll
├── coreaudio-encoder.pdb
├── decklink-captions.dll
├── decklink-captions.pdb
├── decklink-ouput-ui.dll
├── decklink-ouput-ui.pdb
├── enc-amf.dll
├── enc-amf.pdb
├── frontend-tools.dll
├── frontend-tools.pdb
├── image-source.dll
├── image-source.pdb
├── obs-ffmpeg.dll
├── obs-ffmpeg.pdb
├── obs-filters.dll
├── obs-filters.pdb
├── obs-outputs.dll
├── obs-outputs.pdb
├── obs-qsv11.dll
├── obs-qsv11.pdb
├── obs-text.dll
├── obs-text.pdb
├── obs-transitions.dll
├── obs-transitions.pdb
├── obs-vst.dll
├── obs-vst.pdb
├── obs-x264.dll
├── obs-x264.pdb
├── rtmp-services.dll
├── rtmp-services.pdb
├── text-freetype2.dll
├── text-freetype2.pdb
├── win-capture.dll
├── win-capture.pdb
├── win-decklink.dll
├── win-decklink.pdb
├── win-dshow.dll
├── win-dshow.pdb
├── win-mf.dll
├── win-mf.pdb
├── win-wasapi.dll
└── win-wasapi.pdb

What is wrong from my side so I am not seeing button to enable Virtual Webcam?