问:
How to use LogonUser properly to impersonate domain user from workgroup client
ASP.NET: Impersonate against a domain on VMWare

This question is what I am asking, but the answer does not provide details on how the _token is derived. It seems to only use WindowsIdentity.GetCurrent().Token so there's no impersonation happening.

Can I impersonate a user on a different Active Directory domain in .NET?

This next question has conflicting answers, with the accepted one bearing a comment "I'm beginning to suspect that my problem lies elsewhere."  Not helpful.

LogonUser works only for my domain

This next question seems to imply it is not possible, but it deals with 2 domains so I am not sure if it is relevant.

My real question is:

Is it possible? And if so,

How? or Where did I go wrong?

What I have tried so far is, using the code from http://msdn.microsoft.com/en-us/library/chf6fbt4%28v=VS.80%29.aspx

```<code>bool returnValue = LogonUser(user, domain, password,
            LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT,
            ref tokenHandle);
// after this point, returnValue = false
</code>```

The Win32 error is

Logon failure: unknown user name or bad password

答:
The problem I encountered was when my workstation was on one domain, but I needed to authenticate to a server on a different domain:

ERROR: "Exception impersonating user, error code: 1326"

SOLUTION: Added LOGON32_LOGON_NEW_CREDENTIALS as a fallback to Impersonate/LogonUser()

Impersonation.cs

```<code>using System;
using System.Runtime.InteropServices;
using System.Security.Principal;

namespace TestDBAccess
{
    public class Impersonation : IDisposable
    {
        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern bool LogonUser(String Username, String Domain, String Password, int LogonType, int LogonProvider, out IntPtr Token);
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public extern static bool CloseHandle(IntPtr handle);

        public const int LOGON32_PROVIDER_DEFAULT = 0;
        public const int LOGON32_LOGON_INTERACTIVE = 2;
        public const int LOGON32_LOGON_NETWORK = 3;
        public const int LOGON32_LOGON_BATCH = 4;
        public const int LOGON32_LOGON_SERVICE = 5;
        public const int LOGON32_LOGON_UNLOCK = 7;
        public const int LOGON32_LOGON_NETWORK_CLEARTEXT = 8;
        public const int LOGON32_LOGON_NEW_CREDENTIALS = 9;

        private WindowsImpersonationContext impersonationContext = null;
        private IntPtr userHandle = IntPtr.Zero;

        public Impersonation(string user, string domain, string password)
        {
            // Extract domain/username from user string
            string[] principal = user.Split('\\');
            if (principal.Length == 2)
            {
                domain = principal[0];
                user = principal[1];
            }
            if (string.IsNullOrEmpty(domain))
                domain = GetDefaultDomain();

            // Call LogonUser to get a token for the user
            bool loggedOn =
                LogonUser(user, domain, password, LOGON32_LOGON_INTERACTIVE,
                    LOGON32_PROVIDER_DEFAULT, out userHandle);
            if (!loggedOn)
            {
                int ierr = Marshal.GetLastWin32Error();
                if (ierr == 1326)
                {
                    loggedOn =
                        LogonUser(user, domain, password, LOGON32_LOGON_NEW_CREDENTIALS,
                            LOGON32_PROVIDER_DEFAULT, out userHandle);
                }
                if (!loggedOn)
                    throw new Exception("Exception impersonating user, error code: " + Marshal.GetLastWin32Error());
            }

            // Begin impersonating the user
            impersonationContext = WindowsIdentity.Impersonate(userHandle);
        }

        public static string GetDefaultDomain ()
        {
            return System.Environment.UserDomainName;
        }

        public void Dispose()
        {
            // Clean up
            if (impersonationContext != null)
                impersonationContext.Undo();

            if (userHandle != IntPtr.Zero)
                CloseHandle(userHandle);
        }
    }
}
</code>```

ExampleClient.cs

```<code>Impersonation Impersonation = null;
try
{
    Impersonation = new Impersonation(username, null, password);
    LogMsg("Attempting to connect to (" + dbInstance.instance + ")...");
    using (SqlConnection connection = new SqlConnection(connString))
    {
        connection.Open();
        string sql = edtTestSql.Text;
        LogMsg("Attempting to query (" + sql + ")...");
        using (SqlCommand command = new SqlCommand(sql, connection))
        {
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                    LogMsg("next row: " + DumpRow(reader));
            }
        }
    }
}
catch (Exception ex)
{
    LogMsg(ex.Message);
}
finally
{
    if (Impersonation != null)
        Impersonation.Dispose();
}
</code>```

Body:
ASP.NET: Impersonate against a domain on VMWare

This question is what I am asking, but the answer does not provide details on how the _token is derived. It seems to only use WindowsIdentity.GetCurrent().Token so there's no impersonation happening.

Can I impersonate a user on a different Active Directory domain in .NET?

This next question has conflicting answers, with the accepted one bearing a comment "I'm beginning to suspect that my problem lies elsewhere."  Not helpful.

LogonUser works only for my domain

This next question seems to imply it is not possible, but it deals with 2 domains so I am not sure if it is relevant.

My real question is:

Is it possible? And if so,

How? or Where did I go wrong?

What I have tried so far is, using the code from http://msdn.microsoft.com/en-us/library/chf6fbt4%28v=VS.80%29.aspx

bool returnValue = LogonUser(user, domain, password,
            LOGON32_LOGON_NETWORK, LOGON32_PROVIDER_DEFAULT,
            ref tokenHandle);
// after this point, returnValue = false

The Win32 error is

Logon failure: unknown user name or bad password

Body:
The problem I encountered was when my workstation was on one domain, but I needed to authenticate to a server on a different domain:

ERROR: "Exception impersonating user, error code: 1326"

SOLUTION: Added LOGON32_LOGON_NEW_CREDENTIALS as a fallback to Impersonate/LogonUser()

Impersonation.cs

using System;
using System.Runtime.InteropServices;
using System.Security.Principal;

namespace TestDBAccess
{
    public class Impersonation : IDisposable
    {
        [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
        public static extern bool LogonUser(String Username, String Domain, String Password, int LogonType, int LogonProvider, out IntPtr Token);
        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public extern static bool CloseHandle(IntPtr handle);

        public const int LOGON32_PROVIDER_DEFAULT = 0;
        public const int LOGON32_LOGON_INTERACTIVE = 2;
        public const int LOGON32_LOGON_NETWORK = 3;
        public const int LOGON32_LOGON_BATCH = 4;
        public const int LOGON32_LOGON_SERVICE = 5;
        public const int LOGON32_LOGON_UNLOCK = 7;
        public const int LOGON32_LOGON_NETWORK_CLEARTEXT = 8;
        public const int LOGON32_LOGON_NEW_CREDENTIALS = 9;

        private WindowsImpersonationContext impersonationContext = null;
        private IntPtr userHandle = IntPtr.Zero;

        public Impersonation(string user, string domain, string password)
        {
            // Extract domain/username from user string
            string[] principal = user.Split('\\');
            if (principal.Length == 2)
            {
                domain = principal[0];
                user = principal[1];
            }
            if (string.IsNullOrEmpty(domain))
                domain = GetDefaultDomain();

            // Call LogonUser to get a token for the user
            bool loggedOn =
                LogonUser(user, domain, password, LOGON32_LOGON_INTERACTIVE,
                    LOGON32_PROVIDER_DEFAULT, out userHandle);
            if (!loggedOn)
            {
                int ierr = Marshal.GetLastWin32Error();
                if (ierr == 1326)
                {
                    loggedOn =
                        LogonUser(user, domain, password, LOGON32_LOGON_NEW_CREDENTIALS,
                            LOGON32_PROVIDER_DEFAULT, out userHandle);
                }
                if (!loggedOn)
                    throw new Exception("Exception impersonating user, error code: " + Marshal.GetLastWin32Error());
            }

            // Begin impersonating the user
            impersonationContext = WindowsIdentity.Impersonate(userHandle);
        }

        public static string GetDefaultDomain ()
        {
            return System.Environment.UserDomainName;
        }

        public void Dispose()
        {
            // Clean up
            if (impersonationContext != null)
                impersonationContext.Undo();

            if (userHandle != IntPtr.Zero)
                CloseHandle(userHandle);
        }
    }
}

ExampleClient.cs

Impersonation Impersonation = null;
try
{
    Impersonation = new Impersonation(username, null, password);
    LogMsg("Attempting to connect to (" + dbInstance.instance + ")...");
    using (SqlConnection connection = new SqlConnection(connString))
    {
        connection.Open();
        string sql = edtTestSql.Text;
        LogMsg("Attempting to query (" + sql + ")...");
        using (SqlCommand command = new SqlCommand(sql, connection))
        {
            using (SqlDataReader reader = command.ExecuteReader())
            {
                while (reader.Read())
                    LogMsg("next row: " + DumpRow(reader));
            }
        }
    }
}
catch (Exception ex)
{
    LogMsg(ex.Message);
}
finally
{
    if (Impersonation != null)
        Impersonation.Dispose();
}


来源: stackexchange

问:
Using ILogger<T> without constructor injection
I have my registration and constructor setup to use logging via Microsoft.Extensions.Logging as follows,

public MyService(ILogger<MyService> logger) {}

What I'd like to do, though, is use services.AddSingleton() in my Startup.cs to avoid using constructor injection.  The reason is that it will otherwise require modifying all unit tests to Mock the logger when testing the service.

I believe there's a way to register the specific instance of ILogger in the ServiceCollection, but I cannot sort out the syntax required.

Thanks!

答:
In unit tests you should not be using a DI container.

If you were, then you're writing an integration test, not a unit test.

In unit tests, generally speaking, the arrange part of the test should set-up your SUT by directly invoking SUT's constructor and passing-in test/mock/stub versions of its dependencies.

In unit tests, ideally you should supply an entire testing-implementation of the entire Microsoft.Extensions.Logging.ILoggerProvider interface (and related classes) which will allow you to assert that specific log output messages were written, or to redirect ILogger and ILogger<T> output to your test's own output.

Unfortunately this isn't in-box (and Microsoft won't release their own), but there are many popular libraries for this:

https://github.com/martincostello/xunit-logging

https://github.com/alefranz/MELT

Alternatively, if your tests aren't concerned with asserting ILogger usage and/or if you don't want your SUT's own log output written to your test output, then use NullLoggerFactory or NullLogger<T>.Instance in your arrange section to create a stub ILogger<T> that doesn't do anything.

Like this:

```<code>using Microsoft.Extensions.Logging.Abstractions;

// [...]

[Fact]
public void MyService_should_do_something()
{
    // Arrange:

    IArbitraryDependency dep         = new StubArbitraryDependency();
#if FULL_MOON_TONIGHT
    ILogger<MyService>   nullLogger  = NullLoggerFactory.Instance.CreateLogger<MyService>();
#else
    ILogger<MyService>   nullLogger  = NullLogger<MyService>.Instance();
#endif

    MyService systemUnderTest = new MyService(
        arbitraryDependency: dep,
        logger             : nullLogger
    );

    // Act:

    systemUnderTest.DoSomething();

    // Assert:
    // [...]
}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
In unit tests you should not be using a DI container.

If you were, then you're writing an integration test, not a unit test.

In unit tests, generally speaking, the arrange part of the test should set-up your SUT by directly invoking SUT's constructor and passing-in test/mock/stub versions of its dependencies.

In unit tests, ideally you should supply an entire testing-implementation of the entire Microsoft.Extensions.Logging.ILoggerProvider interface (and related classes) which will allow you to assert that specific log output messages were written, or to redirect ILogger and ILogger<T> output to your test's own output.

Unfortunately this isn't in-box (and Microsoft won't release their own), but there are many popular libraries for this:

https://github.com/martincostello/xunit-logging

https://github.com/alefranz/MELT

Alternatively, if your tests aren't concerned with asserting ILogger usage and/or if you don't want your SUT's own log output written to your test output, then use NullLoggerFactory or NullLogger<T>.Instance in your arrange section to create a stub ILogger<T> that doesn't do anything.

Like this:

using Microsoft.Extensions.Logging.Abstractions;

// [...]

[Fact]
public void MyService_should_do_something()
{
    // Arrange:

    IArbitraryDependency dep         = new StubArbitraryDependency();
#if FULL_MOON_TONIGHT
    ILogger<MyService>   nullLogger  = NullLoggerFactory.Instance.CreateLogger<MyService>();
#else
    ILogger<MyService>   nullLogger  = NullLogger<MyService>.Instance();
#endif

    MyService systemUnderTest = new MyService(
        arbitraryDependency: dep,
        logger             : nullLogger
    );

    // Act:

    systemUnderTest.DoSomething();

    // Assert:
    // [...]
}


问:
Error (Xcode): 'Flutter/Flutter.h' file not found
Spent an hour trying to debug this error with stack overflow and GitHub. Any help appreciated. I tried the deleting iOS file and doing flutter clean and stuff.</p>
```<code>Error (Xcode): 'Flutter/Flutter.h' file not found
/Users/ME/Desktop/fitnessapp/ios/Runner/GeneratedPluginRegistrant.h:9:8

Error (Xcode): failed to emit precompiled header
'/Users/ME/Library/Developer/Xcode/DerivedData/Runner-gzhzlsjpfyzcnebymqrpzjndrlbm/Build/Intermediates.noindex/PrecompiledHeaders/Runner-Bridging-Header-swift
_10LJ9PKPTMFQI-clang_1OUD1W5Q54EHI.pch' for bridging header'/Users/ME/Desktop/fitnessapp/ios/Runner/Runner-Bridging-Header.h'

Could not build the application for the simulator.
Error launching application on iPhone 13 Pro.
</code>```

答:
You could try to do this:

Backup Runner folder

Delete the ios folder

Go to a terminal and execute flutter create . in the flutter project folder

Paste your Runner folder back into the ios folder

pod deintegrate in the ios folder

pod install also in the ios folder

flutter clean in the flutter project folder

flutter pub get

flutter run

Please note that if you use firebase you need to re-insert the GoogleService-Info.plist file

Hope it helps, but if it still does not make sure you are in stable channel

Body:
Spent an hour trying to debug this error with stack overflow and GitHub. Any help appreciated. I tried the deleting iOS file and doing flutter clean and stuff.

Error (Xcode): 'Flutter/Flutter.h' file not found
/Users/ME/Desktop/fitnessapp/ios/Runner/GeneratedPluginRegistrant.h:9:8

Error (Xcode): failed to emit precompiled header
'/Users/ME/Library/Developer/Xcode/DerivedData/Runner-gzhzlsjpfyzcnebymqrpzjndrlbm/Build/Intermediates.noindex/PrecompiledHeaders/Runner-Bridging-Header-swift
_10LJ9PKPTMFQI-clang_1OUD1W5Q54EHI.pch' for bridging header'/Users/ME/Desktop/fitnessapp/ios/Runner/Runner-Bridging-Header.h'

Could not build the application for the simulator.
Error launching application on iPhone 13 Pro.


问:
Device input event using libevdev in C++
I am trying to get the touch event from Raspberry Pi Touchscreen. I made it work using FT5406 driver in python and evtest in C. However, I want to write code for this in C++. I notice libevdev is very useful in C, but when I call it in C++, like

```<code>#include <libevdev/libevdev.h>
</code>```

it will always give me

```<code>Fatal error: libevdev/libevdev.h: No such file or directory
</code>```

I manually install libevdev and save it under the path of my code and provide complete path of that library, but the same thing happens.

I also try the method according to link, the problem is still here.

I already installed the corresponding package:

```<code>sudo apt-get install libevdev-dev
sudo apt-get install libudev-dev
</code>```

Is anyone can help me out???

答:
Just had this same problem.  Just find the proper path to the header file.

```<code>sudo find / -name libevdev.h
</code>```

Then include the path starting from the include directory.  Mine was:

```<code>/usr/include/libevdev-1.0/libevdev/libevdev.h
</code>```

So my include line was:

```<code>#include <libevdev-1.0/libevdev/libevdev.h>
</code>```

Body:
I am trying to get the touch event from Raspberry Pi Touchscreen. I made it work using FT5406 driver in python and evtest in C. However, I want to write code for this in C++. I notice libevdev is very useful in C, but when I call it in C++, like

#include <libevdev/libevdev.h>

it will always give me

Fatal error: libevdev/libevdev.h: No such file or directory

I manually install libevdev and save it under the path of my code and provide complete path of that library, but the same thing happens.

I also try the method according to link, the problem is still here.

I already installed the corresponding package:

sudo apt-get install libevdev-dev
sudo apt-get install libudev-dev

Is anyone can help me out???

Body:
Just had this same problem.  Just find the proper path to the header file.

sudo find / -name libevdev.h

Then include the path starting from the include directory.  Mine was:

/usr/include/libevdev-1.0/libevdev/libevdev.h

So my include line was:

#include <libevdev-1.0/libevdev/libevdev.h>


问:
How to take an input while using a command in discord.py
So I want to make a program that permits members by giving them roles for some amount of time

This is my current code

PLEASE NOTE I HAVE GOT THE SOLUTION THANKS TO @curlybracesenjoyer AND IF YOU ARE LOOKING FOR THE CODE SCROLL DOWN AND SEE THE NEW CODE .....TY

**OLD CODE**
**FOR NEW CODE PLEASE SEE THE ANSWERS WHERE I HAVE POSTED THE ANSWER MYSELF**
import discord
import os
import time
from discord.ext import commands
from discord.ext.commands import Bot
from discord.utils import get

x=0.0#want to use it for float input
y=0.0#want to covert x from hours to seconds

bot = commands.Bot(command_prefix=";")

@bot.command('role')
@commands.has_permissions(administrator=True) #permissions
async def role(ctx, user : discord.Member, *, role : discord.Role):
  if role.position > ctx.author.top_role.position: #if the role is above users top role it sends error
    return await ctx.send('**:x: | That role is above your top role!**')
  await ctx.channel.send('Enter time in hours')
  #problem
  #i want to take in x as float input
  #and i want to convert x into seconds and store into y
  await user.add_roles(role) #adds role if not already has it
  await ctx.send(f"Added {role} to {user.mention}")
  time.sleep()#i want to use y here
  await user.remove_roles(role) #removes the role if user already has
  await ctx.send(f"Removed {role} from {user.mention}")

bot.run(os.getenv('TOKEN'))
```

答:
Before moving on the answer, I wanted to mention a few things :

We could be using variables attached to bot (instance) so we don't have to use global which is considered a bad practice

We should be using more verbose variable names than x and y

Just having a sleep is very bad, because it is blocking the entire functioning of the bot

In asynchronous programming, a blocking call is essentially all the parts of the function that are not await. Do not despair, however, because not all forms of blocking are bad! Using blocking calls is inevitable, but you must work to make sure that you don’t excessively block functions. Remember, if you block for too long then your bot will freeze since it has not stopped the function’s execution at that point to do other things.

A common source of blocking for too long is something like time.sleep(). Don’t do that. Use asyncio.sleep() instead. Similar to this example:

# bad
time.sleep(10)

# good
await asyncio.sleep(10)
```
<p>Just waiting for a timing to end is also a bad idea because of how volatile it is, say if you're bot goes offline then the user gets to keep that role forever.<br />
Don't worry too much, you can fix some of those later.</p>
<p>Answer :</p>
<p>To get an floating point number from the same user that has invoked the command, this has to be done :</p>
<pre class="lang-py prettyprint-override"><code>@bot.command()
async def foo(ctx):
    def check(m):
        if m.author == ctx.author and m.channel == ctx.channel:
            try:
                float(m.content)
                return True
            except ValueError:
                return False
        return False

    await ctx.send("Tell me the hours")
    res = await bot.wait_for("message", check=check)
    bot.seconds = float(res.content) * 3600
    await ctx.send(f"The seconds are {bot.seconds}")
    # This bot.seconds can be accessed in everywhere
</code>```

result

Body:
Before moving on the answer, I wanted to mention a few things :

We could be using variables attached to bot (instance) so we don't have to use global which is considered a bad practice

We should be using more verbose variable names than x and y

Just having a sleep is very bad, because it is blocking the entire functioning of the bot

In asynchronous programming, a blocking call is essentially all the parts of the function that are not await. Do not despair, however, because not all forms of blocking are bad! Using blocking calls is inevitable, but you must work to make sure that you don’t excessively block functions. Remember, if you block for too long then your bot will freeze since it has not stopped the function’s execution at that point to do other things.

A common source of blocking for too long is something like time.sleep(). Don’t do that. Use asyncio.sleep() instead. Similar to this example:

# bad
time.sleep(10)

# good
await asyncio.sleep(10)

Just waiting for a timing to end is also a bad idea because of how volatile it is, say if you're bot goes offline then the user gets to keep that role forever.

Don't worry too much, you can fix some of those later.

Answer :

To get an floating point number from the same user that has invoked the command, this has to be done :

@bot.command()
async def foo(ctx):
    def check(m):
        if m.author == ctx.author and m.channel == ctx.channel:
            try:
                float(m.content)
                return True
            except ValueError:
                return False
        return False

    await ctx.send("Tell me the hours")
    res = await bot.wait_for("message", check=check)
    bot.seconds = float(res.content) * 3600
    await ctx.send(f"The seconds are {bot.seconds}")
    # This bot.seconds can be accessed in everywhere

result


问:
TypeScript: How to use "...arguments" in class constructor to pass down all args into another function?
test.js:

```<code>export class MyClass {
  constructor () {
    this.init(...arguments);
  }
  init(arg, opts) {
    console.log(arg, opts);
  }
}
</code>```

The above is perfectly valid JavaScript ES6 code. In TypeScript, you'd define the argument types:

test.ts:

```<code>export class MyClass {
  constructor () {
    this.init(...arguments);  // this no worky
  }
  init(arg: string, opts: Object) {
    console.log(arg, opts);
  }
}
</code>```

But the typescript version has a problem with this.init(...arguments);. It complains (local var) arguments: IArguments A spread argument must either have a tuple type or be passed to a rest parameter.ts(2556).

How do I pass down "all arguments no matter what" down to the sub function, while avoiding the ugly apply(this, args) construct?

I know I could specifically name all parameters, given that there are 2 here, but let's assume in my real application, both constructor() and init() must be able to accept a huge amount of parameters. Even if all parameters were known, it's tedious and verbose to repeat all parameters and their types in typescript, over and over, in each cascading sub function call level, when you already know they will only be passed down and handled by sub function init() anyway.

It was suggested that this Spreading an array in a typescript function: Error TS2556 already answers this question. So I tried this:

test2.ts:

```<code>export class MyClass {
  constructor (...args: any[]) {
    this.init(...args);  // STILL throws the TS2556 error
  }
  init(arg: string, opts: Object) {
    console.log(arg, opts);
  }
}
</code>```

It still throws the TS2556 error.

答:
The problem is that there's not enough information for TypeScript to be sure about the correctness of the types: arguments is not properly typed, and ...args: any[] is explicitly saying "an array with some number of whatever". You have to add this information by yourself, and you can do this with the built-in Parameters helper:

```<code>constructor (...args: Parameters<MyClass["init"]>) {
  this.init(...args);
}
</code>```

Try it.

Body:
test.js:

export class MyClass {
  constructor () {
    this.init(...arguments);
  }
  init(arg, opts) {
    console.log(arg, opts);
  }
}

The above is perfectly valid JavaScript ES6 code. In TypeScript, you'd define the argument types:

test.ts:

export class MyClass {
  constructor () {
    this.init(...arguments);  // this no worky
  }
  init(arg: string, opts: Object) {
    console.log(arg, opts);
  }
}

But the typescript version has a problem with this.init(...arguments);. It complains (local var) arguments: IArguments A spread argument must either have a tuple type or be passed to a rest parameter.ts(2556).

How do I pass down "all arguments no matter what" down to the sub function, while avoiding the ugly apply(this, args) construct?

I know I could specifically name all parameters, given that there are 2 here, but let's assume in my real application, both constructor() and init() must be able to accept a huge amount of parameters. Even if all parameters were known, it's tedious and verbose to repeat all parameters and their types in typescript, over and over, in each cascading sub function call level, when you already know they will only be passed down and handled by sub function init() anyway.

It was suggested that this Spreading an array in a typescript function: Error TS2556 already answers this question. So I tried this:

test2.ts:

export class MyClass {
  constructor (...args: any[]) {
    this.init(...args);  // STILL throws the TS2556 error
  }
  init(arg: string, opts: Object) {
    console.log(arg, opts);
  }
}

It still throws the TS2556 error.

Body:
The problem is that there's not enough information for TypeScript to be sure about the correctness of the types: arguments is not properly typed, and ...args: any[] is explicitly saying "an array with some number of whatever". You have to add this information by yourself, and you can do this with the built-in Parameters helper:

constructor (...args: Parameters<MyClass["init"]>) {
  this.init(...args);
}

Try it.


问:
Open webp file with Pillow
On an Anaconda set up, I want to run following simple code:

from PIL import Image
img = Image.open('test.webp')
```
<p>This works on my Linux machine, but on Windows:</p>
```UserWarning: image file could not be identified because WEBP support not installed
  warnings.warn(message)
---------------------------------------------------------------------------
UnidentifiedImageError                    Traceback (most recent call last)
<ipython-input-3-79ee787a81b3> in <module>
----> 1 img = Image.open('test.webp')

~\miniconda3\lib\site-packages\PIL\Image.py in open(fp, mode, formats)
   3028     for message in accept_warnings:
   3029         warnings.warn(message)
-> 3030     raise UnidentifiedImageError(
   3031         "cannot identify image file %r" % (filename if filename else fp)
   3032     )

UnidentifiedImageError: cannot identify image file 'test.webp'
```

I do have the libwebp package installed, and libwebp.dll is present in the Library\bin directory of my Anaconda set up.

Any idea?

答:
The question is whether Anaconda actually builds Pillow with webp support. Looking on the anaconda website I couldn't determine this.

However, conda-forge does build Pillow with webp support, see here. So you might want to consider using that.

Title: Open webp file with Pillow

Body:
On an Anaconda set up, I want to run following simple code:

from PIL import Image
img = Image.open('test.webp')

This works on my Linux machine, but on Windows:

UserWarning: image file could not be identified because WEBP support not installed
  warnings.warn(message)
---------------------------------------------------------------------------
UnidentifiedImageError                    Traceback (most recent call last)
<ipython-input-3-79ee787a81b3> in <module>
----> 1 img = Image.open('test.webp')

~\miniconda3\lib\site-packages\PIL\Image.py in open(fp, mode, formats)
   3028     for message in accept_warnings:
   3029         warnings.warn(message)
-> 3030     raise UnidentifiedImageError(
   3031         "cannot identify image file %r" % (filename if filename else fp)
   3032     )

UnidentifiedImageError: cannot identify image file 'test.webp'

I do have the libwebp package installed, and libwebp.dll is present in the Library\bin directory of my Anaconda set up.

Any idea?


问:
Why do non-exhaustive guards cause irrefutable pattern match to fail?
I have this function in Haskell:

```<code>test :: (Eq a) => a -> a -> Maybe a
test a b
  | a == b = Just a
test _ _ = Nothing
</code>```

This is what I got when I tried the function with different inputs:

```<code>ghci>test 3 4
Nothing
ghci>test 3 3
Just 3
</code>```

According to Real World Haskell, the first pattern is irrefutable.  But it seems like test 3 4 doesn't fails the first pattern, and matches the second.  I expected some kind of error -- maybe 'non-exhaustive guards'.  So what is really going on here, and is there a way to enable compiler warnings in case this accidentally happens?

答:
The first pattern is indeed an "irrefutable pattern", however this does not mean that it will always choose the corresponding right hand side of your function. It is still subject to the guard which may fail as it does in your example.

To ensure all cases are covered, it is common to use otherwise to have a final guard which will always succeed.

```<code>test :: (Eq a) => a -> a -> Maybe a
test a b
  | a == b    = Just a
  | otherwise = Nothing
</code>```

Note that there is nothing magic about otherwise. It is defined in the Prelude as otherwise = True. However, it is idiomatic to use otherwise for the final case.

Having a compiler warn about non-exaustive guards would be impossible in the general case, as it would involve solving the halting problem, however there exist tools like Catch which attempt to do a better job than the compiler at determining whether all cases are covered or not in the common case.

ContentLicense: CC BY-SA 3.0

Body:
I have this function in Haskell:

test :: (Eq a) => a -> a -> Maybe a
test a b
  | a == b = Just a
test _ _ = Nothing

This is what I got when I tried the function with different inputs:

ghci>test 3 4
Nothing
ghci>test 3 3
Just 3

According to Real World Haskell, the first pattern is irrefutable.  But it seems like test 3 4 doesn't fails the first pattern, and matches the second.  I expected some kind of error -- maybe 'non-exhaustive guards'.  So what is really going on here, and is there a way to enable compiler warnings in case this accidentally happens?

Body:
The first pattern is indeed an "irrefutable pattern", however this does not mean that it will always choose the corresponding right hand side of your function. It is still subject to the guard which may fail as it does in your example.

To ensure all cases are covered, it is common to use otherwise to have a final guard which will always succeed.

test :: (Eq a) => a -> a -> Maybe a
test a b
  | a == b    = Just a
  | otherwise = Nothing

Note that there is nothing magic about otherwise. It is defined in the Prelude as otherwise = True. However, it is idiomatic to use otherwise for the final case.

Having a compiler warn about non-exaustive guards would be impossible in the general case, as it would involve solving the halting problem, however there exist tools like Catch which attempt to do a better job than the compiler at determining whether all cases are covered or not in the common case.


问:
Recursively finding elements of the chain
I want to recursively return the chain from the parent to the last kid of the family tree. I started with the code and don't know whats wrong with it:</p>
```<code>class Tree:
    def __init__(self,kid,parent = None):
        self.kid = kid
        self.parent = parent

    def parent_chain(self):
        if self.parent != None:
            self.parent_chain()
        else:
            return self.kid # If no parent

a = Tree('Adam')
b = Tree('Beda')
c = Tree('Ceda')

c.parent = b
b.parent = a

print(c.parent_chain()) # Want it to return Adam --> Beda --> Ceda
</code>```

答:
There are two issues with your code:

Whenever you're assembling the chain, you need to call .parent_chain() on the parent, not the node that you're currently at. Otherwise, you will call .parent_chain() on one node repeatedly, until you recurse past the recursion depth.

You're setting strings to be the values of the kid references. You probably want to store some sort of separate label. This doesn't directly affect what you're trying to do here, but it's almost certainly a mistake, and it will have an effect if you want to use the child pointers in any way (e.g. if you wanted to extend this code to read from parent to child).

Here is a code snippet that resolves these issues.

class Tree:
    def __init__(self, val, kid=None, parent=None):
        self.val = val
        self.kid = kid
        self.parent = parent

    def parent_chain(self):
        if self.parent:
            result = self.parent.parent_chain()
            result.append(self.val)
            return result
        else:
            return [self.val]

a = Tree('Adam')
b = Tree('Beda')
c = Tree('Ceda')

c.parent = b
b.parent = a

print(c.parent_chain()) # Prints ['Adam', 'Beda', 'Ceda']
```

Body:
I want to recursively return the chain from the parent to the last kid of the family tree. I started with the code and don't know whats wrong with it:

class Tree:
    def __init__(self,kid,parent = None):
        self.kid = kid
        self.parent = parent

    def parent_chain(self):
        if self.parent != None:
            self.parent_chain()
        else:
            return self.kid # If no parent

a = Tree('Adam')
b = Tree('Beda')
c = Tree('Ceda')

c.parent = b
b.parent = a

print(c.parent_chain()) # Want it to return Adam --> Beda --> Ceda


问:
How to train PPO using actions from matches already played?
The idea is to initially calibrate the neural network with some prior knowledge before releasing the algorithm to evolve on its own.
To make the question simpler, imagine that an agent can take 10 actions (discrete space). Instead of training the PPO algorithm to figure out by itself which actions are best for each state, I would like to perform a training by considering that some actions were performed in some states.
I'm using Stable Baselines with Gym.

I thought about creating an action wrapper like this:

```<code>class RandomActionWrapper(gym.ActionWrapper):
            def __init__(self, env):
            super(RandomActionWrapper, self).__init__(env)
            def action(self, action):
                a = self.env.action_space.sample()
                return a
</code>```

Ps: this wrapper is just a proof of concept, choosing random actions all the time, but the model just doesn't learn that way (I simulated many iterations in ridiculously simple to learn custom environments, something like: "action 2 always results in reward=1 while other actions result in reward=0).
Apparently the updates on the network are being made considering the actions that the model chose (the model always predicts actions by itself) while the rewards are being calculated based on the actions defined in my wrapper. This mismatch makes learning impossible.

答: As PPO is an on-policy method, there is a mismatch between my generated data and the algorithm’s cost function. There's no reason to insist on PPO here. I'll look into off-policy algorithms</p>

Body:
The idea is to initially calibrate the neural network with some prior knowledge before releasing the algorithm to evolve on its own.
To make the question simpler, imagine that an agent can take 10 actions (discrete space). Instead of training the PPO algorithm to figure out by itself which actions are best for each state, I would like to perform a training by considering that some actions were performed in some states.
I'm using Stable Baselines with Gym.

I thought about creating an action wrapper like this:

class RandomActionWrapper(gym.ActionWrapper):
            def __init__(self, env):
            super(RandomActionWrapper, self).__init__(env)
            def action(self, action):
                a = self.env.action_space.sample()
                return a

Ps: this wrapper is just a proof of concept, choosing random actions all the time, but the model just doesn't learn that way (I simulated many iterations in ridiculously simple to learn custom environments, something like: "action 2 always results in reward=1 while other actions result in reward=0).
Apparently the updates on the network are being made considering the actions that the model chose (the model always predicts actions by itself) while the rewards are being calculated based on the actions defined in my wrapper. This mismatch makes learning impossible.


问:
how to save data in Hive database when receiving data in the background?
I have an issue saving data to Hive when receiving Firebase Cloud Messaging (FCM) push notification data when the app is in the background.

I have a static method to set up hive like this

```<code>static Future<void> setUpHive() async {
    try {

      await Hive.initFlutter();

      if (!Hive.isBoxOpen("Box Name")) {
          await Hive.openBox("Box Name");
      }

    } catch (error) {
      print(error.toString());
    }
}
</code>```

I use that setUpHive static method in main function like this

```<code>Future<void> main() async {

  await HiveHelper.setUpHive();

  runApp(
    MyApp(),
  );
}
</code>```

when the app is in the background, and then it receives FCM message, then this code below will be called. after that I try change the data stored in the Hive box

```<code>Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
    // when receive FCM message when app is in the background, this block will be executed

    // set up the hive first
    await HiveHelper.setUpHive();

    // then I try to change the data stored in the Hive box
    final myBox = Hive.box("BOX NAME");
    myBox.put("key", 12345);
}
</code>```

it seems okay after receiving FCM background data, but when I fully close the app, and the main called again I have error when trying to open the box like this

```<code>   static Future<void> setUpHive() async {
        try {

          await Hive.initFlutter();

          if (!Hive.isBoxOpen("Box Name")) {
              await Hive.openBox("Box Name"); // Error in this line
          }

        } catch (error) {
          print(error.toString());
        }
    }
</code>```

the error is:

HiveError: This should not happen. Please open an issue on GitHub.
E/flutter (13142): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)]
Unhandled Exception: HiveError: This should not happen. Please open an
issue on GitHub. E/flutter (13142): #0      BinaryReaderImpl.readFrame
(package:hive/src/binary/binary_reader_impl.dart:250:7)
E/flutter

I try to find the solution, and I find similar issue from here about Using Hive DB in a Background Process and it is said

leisim:

Unfortunately, Hive does not support opening boxes in multiple
isolates. That means you can either close the box in the main isolate,
update it in your background isolate and reopen it in the main isolate
or you pass the data from the background to the main isolate and
perform the update there...

I am new in Flutter, and I don't understand what he said. please help :(

答:
You can try the following code. The basic idea is to send data from background isolate to main isolate.</p>
```<code>Future<void> backgroundMessageHandler(RemoteMessage msg){
  IsolateNameServer.lookupPortByName('main_port')?.send(msg);
}

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

  ReceivePort receivePort = ReceivePort();
  IsolateNameServer.registerPortWithName(receivePort.sendPort,'main_port');

  receivePort.listen((message) {
    if(message is RemoteMessage){
      //TODO: save your data in hive box
    }
  }

}
</code>```

Body:
I have an issue saving data to Hive when receiving Firebase Cloud Messaging (FCM) push notification data when the app is in the background.

I have a static method to set up hive like this

static Future<void> setUpHive() async {
    try {

      await Hive.initFlutter();

      if (!Hive.isBoxOpen("Box Name")) {
          await Hive.openBox("Box Name");
      }

    } catch (error) {
      print(error.toString());
    }
}

I use that setUpHive static method in main function like this

Future<void> main() async {

  await HiveHelper.setUpHive();

  runApp(
    MyApp(),
  );
}

when the app is in the background, and then it receives FCM message, then this code below will be called. after that I try change the data stored in the Hive box

Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
    // when receive FCM message when app is in the background, this block will be executed

    // set up the hive first
    await HiveHelper.setUpHive();

    // then I try to change the data stored in the Hive box
    final myBox = Hive.box("BOX NAME");
    myBox.put("key", 12345);
}

it seems okay after receiving FCM background data, but when I fully close the app, and the main called again I have error when trying to open the box like this

   static Future<void> setUpHive() async {
        try {

          await Hive.initFlutter();

          if (!Hive.isBoxOpen("Box Name")) {
              await Hive.openBox("Box Name"); // Error in this line
          }

        } catch (error) {
          print(error.toString());
        }
    }

the error is:

HiveError: This should not happen. Please open an issue on GitHub.
E/flutter (13142): [ERROR:flutter/lib/ui/ui_dart_state.cc(199)]
Unhandled Exception: HiveError: This should not happen. Please open an
issue on GitHub. E/flutter (13142): #0      BinaryReaderImpl.readFrame
(package:hive/src/binary/binary_reader_impl.dart:250:7)
E/flutter

I try to find the solution, and I find similar issue from here about Using Hive DB in a Background Process and it is said

leisim:

Unfortunately, Hive does not support opening boxes in multiple
isolates. That means you can either close the box in the main isolate,
update it in your background isolate and reopen it in the main isolate
or you pass the data from the background to the main isolate and
perform the update there...

I am new in Flutter, and I don't understand what he said. please help :(

Body:
You can try the following code. The basic idea is to send data from background isolate to main isolate.

Future<void> backgroundMessageHandler(RemoteMessage msg){
  IsolateNameServer.lookupPortByName('main_port')?.send(msg);
}

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

  ReceivePort receivePort = ReceivePort();
  IsolateNameServer.registerPortWithName(receivePort.sendPort,'main_port');

  receivePort.listen((message) {
    if(message is RemoteMessage){
      //TODO: save your data in hive box
    }
  }

}


问:
Sharepoint 2010 - Adding Sample data to User Field type
Hi StackOverflow members!

I have developing custom list in Visual Studio (trough XML). I created list definition (with content type) and added list instance to it.

Here is schema.xml of my list:

```<code><?xml version="1.0" encoding="utf-8"?>
<List xmlns:ows="Microsoft SharePoint" Title="Teams" EnableContentTypes="TRUE"  FolderCreation="FALSE" Direction="$Resources:Direction;" Url="Lists/Teams" BaseType="0" xmlns="http://schemas.microsoft.com/sharepoint/">
 <MetaData>
<ContentTypes>
  <ContentTypeRef ID="0x010089E3E6DB8C9B4B3FBB980447E313DE94" />
</ContentTypes>
<Fields>
  <Field Type="User" Name="Employee" DisplayName="Employee" Required="TRUE" ID="{7B18E941-BAAD-453A-895C-39579AB5A9F1}"  Group="Sample Group" />
  <Field Type="Boolean" Name="Manager" DisplayName="Manager" ID="{9FC927CC-45EB-4E9E-8F25-18AAEDF7DCAF}"  Group="Sample Group" />
</Fields>
<Views>
  <View BaseViewID="0" Type="HTML" MobileView="TRUE" TabularView="FALSE">
    <Toolbar Type="Standard" />
    <XslLink Default="TRUE">main.xsl</XslLink>
    <RowLimit Paged="TRUE">30</RowLimit>
    <ViewFields>
      <FieldRef  Name="Employee" />
      <FieldRef  Name="Manager" />
    </ViewFields>
    <Query>
      <OrderBy>
        <FieldRef Name="Modified" Ascending="FALSE"></FieldRef>
      </OrderBy>
    </Query>
    <ParameterBindings>
      <ParameterBinding Name="AddNewAnnouncement" Location="Resource(wss,addnewitem)" />
      <ParameterBinding Name="NoAnnouncements" Location="Resource(wss,noXinviewofY_LIST)" />
      <ParameterBinding Name="NoAnnouncementsHowTo" Location="Resource(wss,noXinviewofY_ONET_HOME)" />
    </ParameterBindings>
  </View>
  <View BaseViewID="1" Type="HTML" WebPartZoneID="Main" DisplayName="$Resources:core,objectiv_schema_mwsidcamlidC24;" DefaultView="TRUE" MobileView="TRUE" MobileDefaultView="TRUE" SetupPath="pages\viewpage.aspx" ImageUrl="/_layouts/images/generic.png" Url="AllItems.aspx">
    <Toolbar Type="Standard" />
    <XslLink Default="TRUE">main.xsl</XslLink>
    <RowLimit Paged="TRUE">30</RowLimit>
    <ViewFields>
      <FieldRef Name="LinkTitle"></FieldRef>
      <FieldRef  Name="Employee" />
      <FieldRef  Name="Manager" />
    </ViewFields>
    <Query>
      <OrderBy>
        <FieldRef Name="ID"></FieldRef>
      </OrderBy>
    </Query>
    <ParameterBindings>
      <ParameterBinding Name="NoAnnouncements" Location="Resource(wss,noXinviewofY_LIST)" />
      <ParameterBinding Name="NoAnnouncementsHowTo" Location="Resource(wss,noXinviewofY_DEFAULT)" />
    </ParameterBindings>
  </View>
</Views>
<Forms>
  <Form Type="DisplayForm" Url="DispForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
  <Form Type="EditForm" Url="EditForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
  <Form Type="NewForm" Url="NewForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
</Forms>
</code>```

and elements.xml with list template and content type:

```<code><?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
<!-- Do not change the value of the Name attribute below. If it does not match the folder name of the List Definition project item, an error will occur when the project is run. -->
<ListTemplate
    Name="TeamList"
    Type="10000"
    BaseType="0"
    OnQuickLaunch="TRUE"
    SecurityBits="11"
    Sequence="410"
    DisplayName="TeamList"
    Description="My List Definition"
    Image="/_layouts/images/itgen.png">

</ListTemplate>
<ContentType
    ID="0x010089E3E6DB8C9B4B3FBB980447E313DE94"
    Name="Team Member"
    Group="Sample Group"
    Description=""
    Version="0">
    <FieldRefs>
      <FieldRef ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" Name="Title" Hidden="TRUE" />
      <FieldRef ID="{7B18E941-BAAD-453A-895C-39579AB5A9F1}" />
      <FieldRef ID="{9FC927CC-45EB-4E9E-8F25-18AAEDF7DCAF}" />
    </FieldRefs>
</ContentType>

<Field Type="User" Name="Employee" DisplayName="Employee" Required="TRUE" ID="{7B18E941-BAAD-453A-895C-39579AB5A9F1}"  Group="Sample Group" />
<Field Type="Boolean" Name="Manager" DisplayName="Manager" ID="{9FC927CC-45EB-4E9E-8F25-18AAEDF7DCAF}"  Group="Sample Group" />

</Elements>
</code>```

The question is: how to add sample data to this list? Especially to field of type "User"?

I tried to add this code in list instance element like this:

```<code><ListInstance Title="TeamList"
            OnQuickLaunch="TRUE"
            TemplateType="10000"
            Url="Lists/TeamList"
            Description="TeamList">
  <Data>
      <Rows>
          <Row>
              <Field Name="Employee">CONTOSO\joses</Field>
              <Field Name="Manager">true</Field>
          </Row>
      </Rows>
  </Data>
</code>```

but, error occures: Error occurred in deployment step 'Activate Features': At least one field type in not installed properly. Any help for makeing it work with dialog would be very appreciated.

答:
A User field is a special type of Lookup field. As such, the text value is represented in the format of ID;#TextValue. And really, it is only the ID that is important. The Value is largely ignored. This can be a problem because while the username will always be the same, the ID that represents that user will change from site collection to site collection.

Your row XML should look something like this:

```<code><Data>
  <Rows>
      <Row>
          <Field Name="Employee">99;#CONTOSO\joses</Field>
          <Field Name="Manager">true</Field>
      </Row>
  </Rows>
</Data>
</code>```

You said that this is being deployed to an existing site, so you can browse to the User Information page for CONTOSO\joses. The ID will be in the URL's query string. But be aware that even if the feature works in this site, there is no guarantee that the feature will work in other site collections.

To avoid this problem, instead of seeding a list instance using XML, I will generally use a Feature Receiver to pre-populate lists with User fields. I prefer EnsureUser because it will add the user to the site if the user does not already exist.

Body:
Hi StackOverflow members!

I have developing custom list in Visual Studio (trough XML). I created list definition (with content type) and added list instance to it.

Here is schema.xml of my list:

<?xml version="1.0" encoding="utf-8"?>
<List xmlns:ows="Microsoft SharePoint" Title="Teams" EnableContentTypes="TRUE"  FolderCreation="FALSE" Direction="$Resources:Direction;" Url="Lists/Teams" BaseType="0" xmlns="http://schemas.microsoft.com/sharepoint/">
 <MetaData>
<ContentTypes>
  <ContentTypeRef ID="0x010089E3E6DB8C9B4B3FBB980447E313DE94" />
</ContentTypes>
<Fields>
  <Field Type="User" Name="Employee" DisplayName="Employee" Required="TRUE" ID="{7B18E941-BAAD-453A-895C-39579AB5A9F1}"  Group="Sample Group" />
  <Field Type="Boolean" Name="Manager" DisplayName="Manager" ID="{9FC927CC-45EB-4E9E-8F25-18AAEDF7DCAF}"  Group="Sample Group" />
</Fields>
<Views>
  <View BaseViewID="0" Type="HTML" MobileView="TRUE" TabularView="FALSE">
    <Toolbar Type="Standard" />
    <XslLink Default="TRUE">main.xsl</XslLink>
    <RowLimit Paged="TRUE">30</RowLimit>
    <ViewFields>
      <FieldRef  Name="Employee" />
      <FieldRef  Name="Manager" />
    </ViewFields>
    <Query>
      <OrderBy>
        <FieldRef Name="Modified" Ascending="FALSE"></FieldRef>
      </OrderBy>
    </Query>
    <ParameterBindings>
      <ParameterBinding Name="AddNewAnnouncement" Location="Resource(wss,addnewitem)" />
      <ParameterBinding Name="NoAnnouncements" Location="Resource(wss,noXinviewofY_LIST)" />
      <ParameterBinding Name="NoAnnouncementsHowTo" Location="Resource(wss,noXinviewofY_ONET_HOME)" />
    </ParameterBindings>
  </View>
  <View BaseViewID="1" Type="HTML" WebPartZoneID="Main" DisplayName="$Resources:core,objectiv_schema_mwsidcamlidC24;" DefaultView="TRUE" MobileView="TRUE" MobileDefaultView="TRUE" SetupPath="pages\viewpage.aspx" ImageUrl="/_layouts/images/generic.png" Url="AllItems.aspx">
    <Toolbar Type="Standard" />
    <XslLink Default="TRUE">main.xsl</XslLink>
    <RowLimit Paged="TRUE">30</RowLimit>
    <ViewFields>
      <FieldRef Name="LinkTitle"></FieldRef>
      <FieldRef  Name="Employee" />
      <FieldRef  Name="Manager" />
    </ViewFields>
    <Query>
      <OrderBy>
        <FieldRef Name="ID"></FieldRef>
      </OrderBy>
    </Query>
    <ParameterBindings>
      <ParameterBinding Name="NoAnnouncements" Location="Resource(wss,noXinviewofY_LIST)" />
      <ParameterBinding Name="NoAnnouncementsHowTo" Location="Resource(wss,noXinviewofY_DEFAULT)" />
    </ParameterBindings>
  </View>
</Views>
<Forms>
  <Form Type="DisplayForm" Url="DispForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
  <Form Type="EditForm" Url="EditForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
  <Form Type="NewForm" Url="NewForm.aspx" SetupPath="pages\form.aspx" WebPartZoneID="Main" />
</Forms>

and elements.xml with list template and content type:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">

<ListTemplate
    Name="TeamList"
    Type="10000"
    BaseType="0"
    OnQuickLaunch="TRUE"
    SecurityBits="11"
    Sequence="410"
    DisplayName="TeamList"
    Description="My List Definition"
    Image="/_layouts/images/itgen.png">

</ListTemplate>
<ContentType
    ID="0x010089E3E6DB8C9B4B3FBB980447E313DE94"
    Name="Team Member"
    Group="Sample Group"
    Description=""
    Version="0">
    <FieldRefs>
      <FieldRef ID="{fa564e0f-0c70-4ab9-b863-0177e6ddd247}" Name="Title" Hidden="TRUE" />
      <FieldRef ID="{7B18E941-BAAD-453A-895C-39579AB5A9F1}" />
      <FieldRef ID="{9FC927CC-45EB-4E9E-8F25-18AAEDF7DCAF}" />
    </FieldRefs>
</ContentType>

<Field Type="User" Name="Employee" DisplayName="Employee" Required="TRUE" ID="{7B18E941-BAAD-453A-895C-39579AB5A9F1}"  Group="Sample Group" />
<Field Type="Boolean" Name="Manager" DisplayName="Manager" ID="{9FC927CC-45EB-4E9E-8F25-18AAEDF7DCAF}"  Group="Sample Group" />

</Elements>

The question is: how to add sample data to this list? Especially to field of type "User"?

I tried to add this code in list instance element like this:

<ListInstance Title="TeamList"
            OnQuickLaunch="TRUE"
            TemplateType="10000"
            Url="Lists/TeamList"
            Description="TeamList">
  <Data>
      <Rows>
          <Row>
              <Field Name="Employee">CONTOSO\joses</Field>
              <Field Name="Manager">true</Field>
          </Row>
      </Rows>
  </Data>

but, error occures: Error occurred in deployment step 'Activate Features': At least one field type in not installed properly. Any help for makeing it work with dialog would be very appreciated.

Body:
A User field is a special type of Lookup field. As such, the text value is represented in the format of ID;#TextValue. And really, it is only the ID that is important. The Value is largely ignored. This can be a problem because while the username will always be the same, the ID that represents that user will change from site collection to site collection.

Your row XML should look something like this:

<Data>
  <Rows>
      <Row>
          <Field Name="Employee">99;#CONTOSO\joses</Field>
          <Field Name="Manager">true</Field>
      </Row>
  </Rows>
</Data>

You said that this is being deployed to an existing site, so you can browse to the User Information page for CONTOSO\joses. The ID will be in the URL's query string. But be aware that even if the feature works in this site, there is no guarantee that the feature will work in other site collections.

To avoid this problem, instead of seeding a list instance using XML, I will generally use a Feature Receiver to pre-populate lists with User fields. I prefer EnsureUser because it will add the user to the site if the user does not already exist.


问:
A setState on a component causes an infinite loop
I have my App.js that cause an infinite loop:

```<code>function App() {
  const [sessionUuid, setSessionUuid] = useState('')

  return (
    <div className="App">
      <Header setSessionUuid={setSessionUuid}/>
      <Routes>
        <Route path='/about' element={<About />} />
        <Route path="/" element={<Home />} />
        <Route path="/wine" element={<Wine sessionUuid={sessionUuid} />} />
      </Routes>
      <Footer />
    </div>
  );
}

</code>```

The Header component presents a login or a logout button, depending if a user is logged on. Only if the user do a login or a logout, the component trigger the setSessionUuid function.

```<code>    useEffect(() => {
        if (user !== '')
            setSessionUuid(user.sessionUuid)
        else
            setSessionUuid('')
    }, [user, setSessionUuid])

</code>```

This causes an infinite rendering on the App component.

I found this workaround on stackoverflow, Wrap the setSessionUuid function in a wrapperSetParentState = useCallback function, and pass the wrapperSetParentState to the login component. but it doesn't solve the problem, and the infinite rendering remained

```<code>  const wrapperSetParentState = useCallback(val => {
    setSessionUuid(val);
  }, [setSessionUuid]);
</code>```

What I want to achieve, is that only the component on the route wine will be rendered differently depending on the value of sessionUuid

答:
Has been a nightmare, but I solved it and I want to share with everyone involved where the error was.

First of all, I create a sandbox that you can visit at https://codesandbox.io/s/bitter-water-jsblw?file=/src/App.js:367-374: as you can see, it run like a charme ;-) There is no need for strange things, useEffects or other unnecessary stuffs.

So, the error couldn't be there.

Then, I removed the only thing that was in my App.js and not in the sandbox. I didn't insert it in the initial message because .... it was there for months without problems and was quite invisible for me: Could any invisible thing create a problem? YES, IT CAN!

The instruction was

```<code>const langs = navigator.languages;  //["en-US", "zh-CN", "ja-JP"]
const userLanguageCode = langs[0].length > 2 ? langs[0].substring(0, 2) : langs;
i18n.changeLanguage(userLanguageCode);
</code>```

And, precisely, it was the i18n.changeLanguage(userLanguageCode); that created the problem. I deleted it and everything runs perfectly, as in the sandbox.

Thanks to everybody for the support, and I hope that this misadventure will offer food for thought for everyone.

Thank you again

Body:
I have my App.js that cause an infinite loop:

function App() {
  const [sessionUuid, setSessionUuid] = useState('')

  return (

      <Routes>
        <Route path='/about' element={<About />} />
        <Route path="/" element={<Home />} />
        <Route path="/wine" element={<Wine sessionUuid={sessionUuid} />} />
      </Routes>

  );
}

The Header component presents a login or a logout button, depending if a user is logged on. Only if the user do a login or a logout, the component trigger the setSessionUuid function.

    useEffect(() => {
        if (user !== '')
            setSessionUuid(user.sessionUuid)
        else
            setSessionUuid('')
    }, [user, setSessionUuid])

This causes an infinite rendering on the App component.

I found this workaround on stackoverflow, Wrap the setSessionUuid function in a wrapperSetParentState = useCallback function, and pass the wrapperSetParentState to the login component. but it doesn't solve the problem, and the infinite rendering remained

  const wrapperSetParentState = useCallback(val => {
    setSessionUuid(val);
  }, [setSessionUuid]);

What I want to achieve, is that only the component on the route wine will be rendered differently depending on the value of sessionUuid

Body:
Has been a nightmare, but I solved it and I want to share with everyone involved where the error was.

First of all, I create a sandbox that you can visit at https://codesandbox.io/s/bitter-water-jsblw?file=/src/App.js:367-374: as you can see, it run like a charme ;-) There is no need for strange things, useEffects or other unnecessary stuffs.

So, the error couldn't be there.

Then, I removed the only thing that was in my App.js and not in the sandbox. I didn't insert it in the initial message because .... it was there for months without problems and was quite invisible for me: Could any invisible thing create a problem? YES, IT CAN!

The instruction was

const langs = navigator.languages;  //["en-US", "zh-CN", "ja-JP"]
const userLanguageCode = langs[0].length > 2 ? langs[0].substring(0, 2) : langs;
i18n.changeLanguage(userLanguageCode);

And, precisely, it was the i18n.changeLanguage(userLanguageCode); that created the problem. I deleted it and everything runs perfectly, as in the sandbox.

Thanks to everybody for the support, and I hope that this misadventure will offer food for thought for everyone.

Thank you again


问:
Save first word in files names in another file
I have a folder that has lots of files with the format name1_name2_xxxx.xlsx. I want to save name1 of each file in this folder in a new text file

I tried this but it's not working, any advice?

```<code>import os
for filename in os.listdir("/my_dir/")
    n=os.path.basename(filename)
    nn=n.split("_")
    nnn=n[1]
    print(n)
</code>```

答:
There is no need to use basename, you can just split the filename by "_" and take the first element in the array.

In addition, in order to create a file and write the first part of each filename to it, use with open.

Putting it all together:

```<code>import os

with open("first_part.txt", 'w') as result_file:
    for filename in os.listdir(“/my_dir/”):
        first_part = filename.split("_")[0]
        result_file.write(first_part + "\n")
</code>```

Body:
I have a folder that has lots of files with the format name1_name2_xxxx.xlsx. I want to save name1 of each file in this folder in a new text file

I tried this but it's not working, any advice?

import os
for filename in os.listdir("/my_dir/")
    n=os.path.basename(filename)
    nn=n.split("_")
    nnn=n[1]
    print(n)

Body:
There is no need to use basename, you can just split the filename by "_" and take the first element in the array.

In addition, in order to create a file and write the first part of each filename to it, use with open.

Putting it all together:

import os

with open("first_part.txt", 'w') as result_file:
    for filename in os.listdir(“/my_dir/”):
        first_part = filename.split("_")[0]
        result_file.write(first_part + "\n")


问:
iOS Swift Mi Scale 2 Bluetooth Get Weight
I am writing an app that can get weight measurement from Xiaomi mi scale 2. After reading all available uuid's, only "181B" connection, specifically "2A9C" characteristic (Body weight measurement in bluetooth gatt) gets notifications.

Value data is [2, 164, 178, 7, 1, 1, 2, 58, 56, 253, 255, 240, 60]. Only last two values vary, the rest is time and date, witch is not set currently (253, 255 are zeroes when the weight varies on the scale until it stabilizes).

Can someone help me get only persons weight, should i be getting data maybe in a different way, from other uuid's (like custom ones: 00001530-0000-3512-2118-0009AF100700, 00001542-0000-3512-2118-0009AF100700), and how do i retrieve them.

Correct answer by Paulw11: You need to look at bit 0 of the first byte to determine if the weight is in imperial or SI; the bit is 0 so the data is SI. The to get the weight, convert the last two bytes to a 16 bit integer (60*256+240 = 15,600) and multiply by 0.005 = 78kg

答:
I was using Mi Smart scale and i had the following byte array.

02-A4-B2-07-02-13-06-33-35-FD-FF-EC-09" received - 12.7 KG

02-A4-B2-07-02-13-06-3B-17-FD-FF-C8-3C"  - 77.8 KG

I used the last two bytes to get the weights in KG.

(09*256 + EC)/200 = 12.7

(3C*256+C8)/200 = 77.8

My byte array was 13 bytes long.

```<code>bytes 0 and 1: control bytes
bytes 2 and 3: year
byte 4: month
byte 5: day
byte 6: hours
byte 7: minutes
byte 8: seconds
bytes 9 and 10: impedance
bytes 11 and 12: weight (divide by 100 for pounds and catty, divide by 200 for kilograms)
</code>```

Body:
I was using Mi Smart scale and i had the following byte array.

02-A4-B2-07-02-13-06-33-35-FD-FF-EC-09" received - 12.7 KG

02-A4-B2-07-02-13-06-3B-17-FD-FF-C8-3C"  - 77.8 KG

I used the last two bytes to get the weights in KG.

(09*256 + EC)/200 = 12.7

(3C*256+C8)/200 = 77.8

My byte array was 13 bytes long.

bytes 0 and 1: control bytes
bytes 2 and 3: year
byte 4: month
byte 5: day
byte 6: hours
byte 7: minutes
byte 8: seconds
bytes 9 and 10: impedance
bytes 11 and 12: weight (divide by 100 for pounds and catty, divide by 200 for kilograms)


问:
Insert `··` prettier/prettier
I have a project that has both prettier and eslint installed. The problem is that when I save a file eslint automatically changes the format of the file and it seems some rules conflict with prettier. What is the solution?

This is prettier formatting:

When saved, the file changes to:

Also this is eslintrc file

```<code>{
  "parser": "@typescript-eslint/parser",
  "extends": [
    "plugin:react/recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:prettier/recommended",
    "prettier/@typescript-eslint"
  ],
  "rules": {
    "@typescript-eslint/explicit-function-return-type": "off",
    "@typescript-eslint/no-explicit-any": "off",
    "@typescript-eslint/ban-ts-ignore": "off",
    "@typescript-eslint/interface-name-prefix": "off",
    "@typescript-eslint/no-unused-vars": ["warn", { "argsIgnorePattern": "^_" }]
  },
  "overrides": [
    {
      "files": ["**/*.tsx"],
      "rules": {
        "react/prop-types": "off"
      }
    }
  ],
  "settings": {
    "react": {
      "version": "detect"
    }
  },
  "ignorePatterns": ["coverage/", "node_modules/", "src/serviceWorker.ts"]
}
</code>```

答:
.prettierrc

```<code>{
  "printWidth": 160
}
</code>```

Title: Insert `··` prettier/prettier

Body:
I have a project that has both prettier and eslint installed. The problem is that when I save a file eslint automatically changes the format of the file and it seems some rules conflict with prettier. What is the solution?

This is prettier formatting:

When saved, the file changes to:

Also this is eslintrc file

{
  "parser": "@typescript-eslint/parser",
  "extends": [
    "plugin:react/recommended",
    "plugin:@typescript-eslint/recommended",
    "plugin:prettier/recommended",
    "prettier/@typescript-eslint"
  ],
  "rules": {
    "@typescript-eslint/explicit-function-return-type": "off",
    "@typescript-eslint/no-explicit-any": "off",
    "@typescript-eslint/ban-ts-ignore": "off",
    "@typescript-eslint/interface-name-prefix": "off",
    "@typescript-eslint/no-unused-vars": ["warn", { "argsIgnorePattern": "^_" }]
  },
  "overrides": [
    {
      "files": ["**/*.tsx"],
      "rules": {
        "react/prop-types": "off"
      }
    }
  ],
  "settings": {
    "react": {
      "version": "detect"
    }
  },
  "ignorePatterns": ["coverage/", "node_modules/", "src/serviceWorker.ts"]
}

Body:
.prettierrc

{
  "printWidth": 160
}


问:
Paste from Range Object to Word document
How do I paste without pulling from the clipboard?

(The code examples are excerpts from Googling and recording.)

My VBA code populates a section of my document from a form. Before loading the next form, it copies that section's contents to an object.

The code goes on to further populate the document. When done, the user can choose the "Next Page" control which generates a new page.

I want to paste the object I saved to the beginning of that new page.

My code up to the point of the paste.

Sub waiverCopy()
    Dim objRange As Range
    'Capture first section of document (waiver with names etc. populated)
    Set objRange = ActiveDocument.Range(Start:=0, End:=ActiveDocument.Sections(1).Range.End)

    Debug.Print objRange               'DOES PRINT contents in immediate window

    ' continue populating rest of current page '
    Selection.EndKey Unit:=wdStory     'position to end of document (i.e. current page)

    Selection.InsertBreak Type:=wdPageBreak  'start new page

    ' Nothing of the myriad of things I've tried will paste the contents of objRange on new page

End Sub
```

答:
If you don´t want to use the clipboard, all you are missing is to insert the range object on the current Selection position (Selection.FormattedText = objRange) just after creating the Page Break.

```<code>Sub Copy()
    Dim objRange As Range
    'Capture first section of document (waiver with names etc. populated)
    Set objRange = ActiveDocument.Range(Start:=0, End:=ActiveDocument.Sections(1).Range.End - 1)

    ' continue populating rest of current page '
    Selection.EndKey Unit:=wdStory     'position to end of document (i.e. current page)

    Selection.InsertBreak Type:=wdPageBreak  'start new page

    Selection.FormattedText = objRange

    ' Don´t forget to clean memory
    Set objRange = Nothing
End Sub
</code>```

Please do not forget to clean memory with Set objRange = Nothing.

Body:
If you don´t want to use the clipboard, all you are missing is to insert the range object on the current Selection position (Selection.FormattedText = objRange) just after creating the Page Break.

Sub Copy()
    Dim objRange As Range
    'Capture first section of document (waiver with names etc. populated)
    Set objRange = ActiveDocument.Range(Start:=0, End:=ActiveDocument.Sections(1).Range.End - 1)

    ' continue populating rest of current page '
    Selection.EndKey Unit:=wdStory     'position to end of document (i.e. current page)

    Selection.InsertBreak Type:=wdPageBreak  'start new page

    Selection.FormattedText = objRange

    ' Don´t forget to clean memory
    Set objRange = Nothing
End Sub

Please do not forget to clean memory with Set objRange = Nothing.


问:
How do I reverse the sign in a django database query on matching rows?
I have a Django model that looks like this:

direction_choices = (
    ("up", "Up"),
    ("down", "Down"),
    ("left", "Left"),
    ("right", "Right"),
)

class Movement:
    direction = models.CharField(max_length=5, choices=direction_choices)
    distance = models.PositiveSmallIntegerField()
```
<p>Lets say the data in my database looks like this:</p>
```Movement(direction="up", 4)
Movement(direction="up", 6)
Movement(direction="down", 3)
Movement(direction="down", 1)
Movement(direction="left", 7)
Movement(direction="right", 4)
Movement(direction="left", 1)
Movement(direction="right", 8)
```
<p>I want to do a database query that will calculate the total distance moved in the Y axis.</p>
<p>In our example, it would be: <code>4+6-3-1 = 6</code></p>
<p>I can do something like:</p>
<pre class="lang-py prettyprint-override"><code>Movement.objects.all().filter(
    direction__in=("up", "down")
    ).aggregate(
        total=Sum('distance')
    )
</code>```

which gives me:

{'total': 16}
```

I'm not sure how to tell the database that "down" fields should be multiplied by -1 to have their signs reversed before adding up the total.

I know this is easy to do with Python with a for loop, or list comprehension. How would one have the database do this?

答:
You can aggregate with:

```<code>from django.db.models import Q, Value
from django.db.models.functions import Coalesce

Movement.objects.filter(
    direction__in=('up', 'down')
).aggregate(
    total=Coalesce(Sum('distance'<strong>, filter=Q(direction='up')</strong>), Value(0))
        - Coalesce(Sum('distance'<strong>, filter=Q(direction='down')</strong>), Value(0))
)</code>```

or you can work through annotation:

```<code>from django.db.models import <strong>Case</strong>, F, <strong>When</strong>

Movement.objects.filter(
    direction__in=('up', 'down')
)<strong>.alias(</strong>
    <strong>dir=Case(</strong>
        When(direction='down', then=-F('distance')),
        default=F('distance')
    <strong>)</strong>
<strong>)</strong>.aggregate(
    total=Sum('dir')
)</code>```

Body:
I have a Django model that looks like this:

direction_choices = (
    ("up", "Up"),
    ("down", "Down"),
    ("left", "Left"),
    ("right", "Right"),
)

class Movement:
    direction = models.CharField(max_length=5, choices=direction_choices)
    distance = models.PositiveSmallIntegerField()

Lets say the data in my database looks like this:

Movement(direction="up", 4)
Movement(direction="up", 6)
Movement(direction="down", 3)
Movement(direction="down", 1)
Movement(direction="left", 7)
Movement(direction="right", 4)
Movement(direction="left", 1)
Movement(direction="right", 8)

I want to do a database query that will calculate the total distance moved in the Y axis.

In our example, it would be: 4+6-3-1 = 6

I can do something like:

Movement.objects.all().filter(
    direction__in=("up", "down")
    ).aggregate(
        total=Sum('distance')
    )

which gives me:

{'total': 16}

I'm not sure how to tell the database that "down" fields should be multiplied by -1 to have their signs reversed before adding up the total.

I know this is easy to do with Python with a for loop, or list comprehension. How would one have the database do this?

Body:
You can aggregate with:

from django.db.models import Q, Value
from django.db.models.functions import Coalesce

Movement.objects.filter(
    direction__in=('up', 'down')
).aggregate(
    total=Coalesce(Sum('distance', filter=Q(direction='up')), Value(0))
        - Coalesce(Sum('distance', filter=Q(direction='down')), Value(0))
)

or you can work through annotation:

from django.db.models import Case, F, When

Movement.objects.filter(
    direction__in=('up', 'down')
).alias(
    dir=Case(
        When(direction='down', then=-F('distance')),
        default=F('distance')
    )
).aggregate(
    total=Sum('dir')
)


问:
Python - Show one image from an image array
I'm going through this tutorial on pytorch. https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html
And I've been able to show real images next to the fake ones that I have generated.

```<code># Grab a batch of real images from the dataloader
real_batch = next(iter(dataloader))

# Plot the real images
plt.figure(figsize=(15,15))
plt.subplot(1,2,1)
plt.axis("off")
plt.title("Real Images")
plt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device)[:64], padding=5, normalize=True).cpu(),(1,2,0)))

# Plot the fake images from the last epoch
plt.subplot(1,2,2)
plt.axis("off")
plt.title("Fake Images")
plt.imshow(np.transpose(img_list[-1],(1,2,0)))
plt.show()
</code>```

Which from my dataset results in this:

I was wondering how I can show one image from the fake images generated. I also want to show it as a 512 X 512 image if possible.

Edit:
The img_list[-1].shape is torch.Size([3, 530, 530]).

Edit2:

This part of the training shows that img_list is a list of images with each image being a group of sub-images (not being able to separate them). Is there a way I can edit this to make img_list an image of each fake image generated?

答:
Here is what I wanted:

```<code>noise = torch.randn(1, nz, 1, 1, device=device)
with torch.no_grad():
    newfake = netG(noise).detach().cpu()

plt.axis("off")
plt.imshow(np.transpose(newfake[0],(1,2,0)))
plt.show()
</code>```

As it generates a new image, with a new noise. The img_list was combining the generated images into one image.
However, this code still only generates 64 by 64 pixel images.

Body:
I'm going through this tutorial on pytorch. https://pytorch.org/tutorials/beginner/dcgan_faces_tutorial.html
And I've been able to show real images next to the fake ones that I have generated.

# Grab a batch of real images from the dataloader
real_batch = next(iter(dataloader))

# Plot the real images
plt.figure(figsize=(15,15))
plt.subplot(1,2,1)
plt.axis("off")
plt.title("Real Images")
plt.imshow(np.transpose(vutils.make_grid(real_batch[0].to(device)[:64], padding=5, normalize=True).cpu(),(1,2,0)))

# Plot the fake images from the last epoch
plt.subplot(1,2,2)
plt.axis("off")
plt.title("Fake Images")
plt.imshow(np.transpose(img_list[-1],(1,2,0)))
plt.show()

Which from my dataset results in this:

I was wondering how I can show one image from the fake images generated. I also want to show it as a 512 X 512 image if possible.

Edit:
The img_list[-1].shape is torch.Size([3, 530, 530]).

Edit2:

This part of the training shows that img_list is a list of images with each image being a group of sub-images (not being able to separate them). Is there a way I can edit this to make img_list an image of each fake image generated?

Body:
Here is what I wanted:

noise = torch.randn(1, nz, 1, 1, device=device)
with torch.no_grad():
    newfake = netG(noise).detach().cpu()

plt.axis("off")
plt.imshow(np.transpose(newfake[0],(1,2,0)))
plt.show()

As it generates a new image, with a new noise. The img_list was combining the generated images into one image.
However, this code still only generates 64 by 64 pixel images.


问:
How to stop a thread running in python
I am developing an application with Python. What I want to do is that the Thread works when I press Button 1, the Thread stops when I press Button 2.
How can I do this.

Here is my code:

```<code>from tkinter import *
import threading

def process():
    while True:
        print("Hello World")
processThread = threading.Thread(target=process)

def main():
    mainWindow = Tk()
    mainWindow.resizable(FALSE, FALSE)

    mainWindow.title("Text")
    mainWindow.geometry("500x250")

    recButton=Button(mainWindow)
    recButton.config(text="Button 1", font=("Arial", "13"), bg="red",fg="white", width="15", command=)
    recButton.place(x=15,y=10)

    stopButton=Button(mainWindow)
    stopButton.config(text="Button 2", font=("Calibri", "13"), bg="orange",fg="white", width="15", command=)
    stopButton.place(x=15,y=55)

    textBox = Text(mainWindow, height="14", width="37")
    textBox.place(x=180, y=10)

    mainWindow.mainloop()
mainThread = threading.Thread(target=main)
mainThread.start()
</code>```

答:
Probably the easiest way is to create a variable in the global scope that indicates if the thread should run;

```<code>runthread = True
</code>```

The thread should regularly check if this is still True. If not, it should simply return:

```<code>def process():
    while runthread:
        print("Hello World")
</code>```

All that the function linked to the stopButton now has to do is to set runthread to False.

```<code>def do_stop():
    global runthread
    runthread = False
</code>```

BTW, you don't have to go and create a separate thread for main.

Here is an example of a tkinter program running a separate thread;

```<code>"""Example tkinter script showing the use of a thread."""

import os
import sys
import threading
import time
import tkinter as tk
import tkinter.font as tkfont
import types

__version__ = "2022.02.02"
# Namespace for widgets that need to be accessed by callbacks.
widgets = types.SimpleNamespace()
# State that needs to be accessed by callbacks.
state = types.SimpleNamespace()

def create_widgets(root, w):
    """
    Create the window and its widgets.

    Arguments:
        root: the root window.
        w: SimpleNamespace to store widgets.
    """
    # General commands and bindings
    root.wm_title("tkinter threading v" + __version__)
    root.columnconfigure(2, weight=1)
    root.rowconfigure(3, weight=1)
    root.resizable(False, False)
    # First row
    tk.Label(root, text="Thread status: ").grid(row=0, column=0, sticky="ew")
    w.runstatus = tk.Label(root, text="not running", width=12)
    w.runstatus.grid(row=0, column=1, sticky="ew")
    # Second row
    tk.Label(root, text="Timer: ").grid(row=1, column=0, sticky="ew")
    w.counter = tk.Label(root, text="0 s")
    w.counter.grid(row=1, column=1, sticky="ew")
    # Third row
    w.gobtn = tk.Button(root, text="Go", command=do_start)
    w.gobtn.grid(row=2, column=0, sticky="ew")
    w.stopbtn = tk.Button(root, text="Stop", command=do_stop, state=tk.DISABLED)
    w.stopbtn.grid(row=2, column=1, sticky="ew")

def initialize_state(s):
    """
    Initialize the global state.

    Arguments:
        s: SimpleNamespace to store application state.
    """
    s.worker = None
    s.run = False
    s.counter = 0

def worker():
    """
    Function that is run in a separate thread.

    This function *does* update tkinter widgets.  In Python 3, this should be
    safe if a tkinter is used that is built with threads.
    """
    # Initialization
    widgets.runstatus["text"] = "running"
    # Work
    while state.run:
        time.sleep(0.25)
        state.counter += 0.25
        widgets.counter["text"] = f"{state.counter:.2f} s"
    # Finalization
    state.counter = 0.0
    widgets.counter["text"] = f"{state.counter:g} s"
    widgets.runstatus["text"] = "not running"

def do_start():
    """Callback for the “Go” button"""
    widgets.gobtn["state"] = tk.DISABLED
    widgets.stopbtn["state"] = tk.NORMAL
    state.run = True
    state.worker = threading.Thread(target=worker)
    state.worker.start()

def do_stop():
    """Callback for the “Stop” button"""
    widgets.gobtn["state"] = tk.NORMAL
    widgets.stopbtn["state"] = tk.DISABLED
    state.run = False
    state.worker = None

# Main program starts here.
if __name__ == "__main__":
    # Detach from the command line on UNIX systems.
    if os.name == "posix":
        if os.fork():
            sys.exit()
    # Initialize global state
    initialize_state(state)
    # Create the GUI window.
    root = tk.Tk(None)
    # Set the font
    default_font = tkfont.nametofont("TkDefaultFont")
    default_font.configure(size=12)
    root.option_add("*Font", default_font)
    create_widgets(root, widgets)
    root.mainloop()
</code>```

Title: How to stop a thread running in python

Body:
I am developing an application with Python. What I want to do is that the Thread works when I press Button 1, the Thread stops when I press Button 2.
How can I do this.

Here is my code:

from tkinter import *
import threading

def process():
    while True:
        print("Hello World")
processThread = threading.Thread(target=process)

def main():
    mainWindow = Tk()
    mainWindow.resizable(FALSE, FALSE)

    mainWindow.title("Text")
    mainWindow.geometry("500x250")

    recButton=Button(mainWindow)
    recButton.config(text="Button 1", font=("Arial", "13"), bg="red",fg="white", width="15", command=)
    recButton.place(x=15,y=10)

    stopButton=Button(mainWindow)
    stopButton.config(text="Button 2", font=("Calibri", "13"), bg="orange",fg="white", width="15", command=)
    stopButton.place(x=15,y=55)

    textBox = Text(mainWindow, height="14", width="37")
    textBox.place(x=180, y=10)

    mainWindow.mainloop()
mainThread = threading.Thread(target=main)
mainThread.start()

Body:
Probably the easiest way is to create a variable in the global scope that indicates if the thread should run;

runthread = True

The thread should regularly check if this is still True. If not, it should simply return:

def process():
    while runthread:
        print("Hello World")

All that the function linked to the stopButton now has to do is to set runthread to False.

def do_stop():
    global runthread
    runthread = False

BTW, you don't have to go and create a separate thread for main.

Here is an example of a tkinter program running a separate thread;

"""Example tkinter script showing the use of a thread."""

import os
import sys
import threading
import time
import tkinter as tk
import tkinter.font as tkfont
import types

__version__ = "2022.02.02"
# Namespace for widgets that need to be accessed by callbacks.
widgets = types.SimpleNamespace()
# State that needs to be accessed by callbacks.
state = types.SimpleNamespace()

def create_widgets(root, w):
    """
    Create the window and its widgets.

    Arguments:
        root: the root window.
        w: SimpleNamespace to store widgets.
    """
    # General commands and bindings
    root.wm_title("tkinter threading v" + __version__)
    root.columnconfigure(2, weight=1)
    root.rowconfigure(3, weight=1)
    root.resizable(False, False)
    # First row
    tk.Label(root, text="Thread status: ").grid(row=0, column=0, sticky="ew")
    w.runstatus = tk.Label(root, text="not running", width=12)
    w.runstatus.grid(row=0, column=1, sticky="ew")
    # Second row
    tk.Label(root, text="Timer: ").grid(row=1, column=0, sticky="ew")
    w.counter = tk.Label(root, text="0 s")
    w.counter.grid(row=1, column=1, sticky="ew")
    # Third row
    w.gobtn = tk.Button(root, text="Go", command=do_start)
    w.gobtn.grid(row=2, column=0, sticky="ew")
    w.stopbtn = tk.Button(root, text="Stop", command=do_stop, state=tk.DISABLED)
    w.stopbtn.grid(row=2, column=1, sticky="ew")

def initialize_state(s):
    """
    Initialize the global state.

    Arguments:
        s: SimpleNamespace to store application state.
    """
    s.worker = None
    s.run = False
    s.counter = 0

def worker():
    """
    Function that is run in a separate thread.

    This function *does* update tkinter widgets.  In Python 3, this should be
    safe if a tkinter is used that is built with threads.
    """
    # Initialization
    widgets.runstatus["text"] = "running"
    # Work
    while state.run:
        time.sleep(0.25)
        state.counter += 0.25
        widgets.counter["text"] = f"{state.counter:.2f} s"
    # Finalization
    state.counter = 0.0
    widgets.counter["text"] = f"{state.counter:g} s"
    widgets.runstatus["text"] = "not running"

def do_start():
    """Callback for the “Go” button"""
    widgets.gobtn["state"] = tk.DISABLED
    widgets.stopbtn["state"] = tk.NORMAL
    state.run = True
    state.worker = threading.Thread(target=worker)
    state.worker.start()

def do_stop():
    """Callback for the “Stop” button"""
    widgets.gobtn["state"] = tk.NORMAL
    widgets.stopbtn["state"] = tk.DISABLED
    state.run = False
    state.worker = None

# Main program starts here.
if __name__ == "__main__":
    # Detach from the command line on UNIX systems.
    if os.name == "posix":
        if os.fork():
            sys.exit()
    # Initialize global state
    initialize_state(state)
    # Create the GUI window.
    root = tk.Tk(None)
    # Set the font
    default_font = tkfont.nametofont("TkDefaultFont")
    default_font.configure(size=12)
    root.option_add("*Font", default_font)
    create_widgets(root, widgets)
    root.mainloop()


问:
Holt-winter model fit values
Hw to get model fit model for training period in holt winter method for Univariate time series. For future forecast I can use the following syntax but not sure what is syntax for training period.</p>
```<code>
                result = model.fit()
                start = len(df)
                end = len(df) + 6
                # Predictions for one-year against the test set

                fcast = result.forecast(start ,end)```
</code>```

答:
i got the answer it is
result.fittedvalues

Title: Holt-winter model fit values

Body:
Hw to get model fit model for training period in holt winter method for Univariate time series. For future forecast I can use the following syntax but not sure what is syntax for training period.

                result = model.fit()
                start = len(df)
                end = len(df) + 6
                # Predictions for one-year against the test set

                fcast = result.forecast(start ,end)```


答:
You should use " instead of “

To get the first item from a list use [0] and not [1]

You don't need os.path.basename, os.listdir() already returns just the files name as string.

Other than that it seems okay to me, now you just have to save it to a file:

```<code>import os
with open("names_file.txt", "w", encoding="utf-8") as f:
    for filename in os.listdir("/my_dir/")
        base_name = filename.split("_")[0]
        print(base_name)
        f.write(filename+"\n")
</code>```

Title: Save first word in files names in another file

Body:
You should use " instead of “

To get the first item from a list use [0] and not [1]

You don't need os.path.basename, os.listdir() already returns just the files name as string.

Other than that it seems okay to me, now you just have to save it to a file:

import os
with open("names_file.txt", "w", encoding="utf-8") as f:
    for filename in os.listdir("/my_dir/")
        base_name = filename.split("_")[0]
        print(base_name)
        f.write(filename+"\n")


问:
Calculate the duration from start date and end date in SQL
I am using SQL Server.

```<code>select DISTINCT caseNumber, dateStarted,dateStopped from patientView where dateStarted !='' and dateStopped != '';
</code>```

We get the following output,

CaseNumber
dateStarted
dateStopped

1
2022-01-01
2022-01-04

1
2022-01-05
2022-01-19

2
2022-01-03
2022-01-10

4
2022-01-05
2022-01-11

4
2022-01-13
2022-01-14

4
2022-01-21
2022-01-23

5
2022-01-15
2022-01-16

5
2022-01-17
2022-01-24

5
2022-01-24
2022-01-26

8
2022-01-17
2022-01-20

8
2022-01-21
2022-01-28

11
2022-01-18
2022-01-25

11
2022-01-26
2022-01-27

I want to calculate the duration for each caseNumber. For eg. caseNumber 1 has 2 rows and hence total duration would be 18days.

答:
It is not clear whether you want the sum of the durations for individual patientView records or the duration from the earliest start to the latest end. It is also not clear whether the stop date is inclusive or exclusive. Is 2022-01-01 to 2022-01-04 considered 3 days or 4 days?

Here is code that shows 4 different calculations:

```<code>DECLARE @patientView  TABLE (CaseNumber INT, dateStarted DATETIME, dateStopped DATETIME)
INSERT @patientView
VALUES
    (1,  '2022-01-01 ', '2022-01-04'),
    (1,  '2022-01-05 ', '2022-01-19'),
    (2,  '2022-01-03 ', '2022-01-10'),
    (4,  '2022-01-05 ', '2022-01-11'),
    (4,  '2022-01-13 ', '2022-01-14'),
    (4,  '2022-01-21 ', '2022-01-23'),
    (5,  '2022-01-15 ', '2022-01-16'),
    (5,  '2022-01-17 ', '2022-01-24'),
    (5,  '2022-01-24 ', '2022-01-26'),
    (8,  '2022-01-17 ', '2022-01-20'),
    (8,  '2022-01-21 ', '2022-01-28'),
    (11, '2022-01-18 ', '2022-01-25'),
    (11, '2022-01-26 ', '2022-01-27')

SELECT
    CaseNumber,
    SumDaysExclusive = SUM(DATEDIFF(day, dateStarted, dateStopped)),
    SumDaysInclusive = SUM(DATEDIFF(day, dateStarted, dateStopped) + 1),
    RangeDaysExclusive = DATEDIFF(day, MIN(dateStarted), MAX(dateStopped)),
    RangeDaysInclusive = DATEDIFF(day, MIN(dateStarted), MAX(dateStopped)) + 1
FROM @patientView
GROUP BY CaseNumber
ORDER BY CaseNumber

</code>```

Results:

CaseNumber
SumDaysExclusive
SumDaysInclusive
RangeDaysExclusive
RangeDaysInclusive

1
17
19
18
19

2
7
8
7
8

4
9
12
18
19

5
10
13
11
12

8
10
12
11
12

11
8
10
9
10

db<>fiddle

The test data above uses DATETIME types. (DATE would also work.) If you have dates stored as character data (not a good practice), you may need to add CAST or CONVERT statements.

Body:
I am using SQL Server.

select DISTINCT caseNumber, dateStarted,dateStopped from patientView where dateStarted !='' and dateStopped != '';

We get the following output,

CaseNumber
dateStarted
dateStopped

1
2022-01-01
2022-01-04

1
2022-01-05
2022-01-19

2
2022-01-03
2022-01-10

4
2022-01-05
2022-01-11

4
2022-01-13
2022-01-14

4
2022-01-21
2022-01-23

5
2022-01-15
2022-01-16

5
2022-01-17
2022-01-24

5
2022-01-24
2022-01-26

8
2022-01-17
2022-01-20

8
2022-01-21
2022-01-28

11
2022-01-18
2022-01-25

11
2022-01-26
2022-01-27

I want to calculate the duration for each caseNumber. For eg. caseNumber 1 has 2 rows and hence total duration would be 18days.

Body:
It is not clear whether you want the sum of the durations for individual patientView records or the duration from the earliest start to the latest end. It is also not clear whether the stop date is inclusive or exclusive. Is 2022-01-01 to 2022-01-04 considered 3 days or 4 days?

Here is code that shows 4 different calculations:

DECLARE @patientView  TABLE (CaseNumber INT, dateStarted DATETIME, dateStopped DATETIME)
INSERT @patientView
VALUES
    (1,  '2022-01-01 ', '2022-01-04'),
    (1,  '2022-01-05 ', '2022-01-19'),
    (2,  '2022-01-03 ', '2022-01-10'),
    (4,  '2022-01-05 ', '2022-01-11'),
    (4,  '2022-01-13 ', '2022-01-14'),
    (4,  '2022-01-21 ', '2022-01-23'),
    (5,  '2022-01-15 ', '2022-01-16'),
    (5,  '2022-01-17 ', '2022-01-24'),
    (5,  '2022-01-24 ', '2022-01-26'),
    (8,  '2022-01-17 ', '2022-01-20'),
    (8,  '2022-01-21 ', '2022-01-28'),
    (11, '2022-01-18 ', '2022-01-25'),
    (11, '2022-01-26 ', '2022-01-27')

SELECT
    CaseNumber,
    SumDaysExclusive = SUM(DATEDIFF(day, dateStarted, dateStopped)),
    SumDaysInclusive = SUM(DATEDIFF(day, dateStarted, dateStopped) + 1),
    RangeDaysExclusive = DATEDIFF(day, MIN(dateStarted), MAX(dateStopped)),
    RangeDaysInclusive = DATEDIFF(day, MIN(dateStarted), MAX(dateStopped)) + 1
FROM @patientView
GROUP BY CaseNumber
ORDER BY CaseNumber

Results:

CaseNumber
SumDaysExclusive
SumDaysInclusive
RangeDaysExclusive
RangeDaysInclusive

1
17
19
18
19

2
7
8
7
8

4
9
12
18
19

5
10
13
11
12

8
10
12
11
12

11
8
10
9
10

db<>fiddle

The test data above uses DATETIME types. (DATE would also work.) If you have dates stored as character data (not a good practice), you may need to add CAST or CONVERT statements.


问:
Need to write a find/replace script for items in a text file
I'm faced with a problem.  I have a text list of thousands of cities and their gps coordinates.  The format is:

```<code>City,longitude,latitude,Parent
</code>```

so an example might be:

```<code>Los Angeles,34.11N,118.41W,California
</code>```

The problem is that I need the long/lat to be in + and - values so the correct entry would be:

```<code>Los Angeles,34.11,-118.41,California
</code>```

So the script would be something like

Find "W" or "S" (west and south get the "-" symbol)

if you find either of those letters within the 2nd or 3rd "," insert a "-" symbol before the first number. (we don't want to affect the words in the 1st or 4th field)

then delete any letter from the long/lat field.

This could be done a zillion ways - excel, .bat file, something else?

If anyone could help with this I'd be very grateful.
Thanks

答:
Try this Batch file:</p>

```<code>@echo off
setlocal EnableDelayedExpansion
if exist thefile.tmp del thefile.tmp
for /F "tokens=1-4 delims=," %%a in (thefile.txt) do (
    set longitude=%%b
    set sign=!longitude:~-1!
    set longitude=!longitude:~0,-1!
    if /I !sign! == S set longitude=-!longitude!
    set latitude=%%c
    set sign=!latitude:~-1!
    set latitude=!latitude:~0,-1!
    if /I !sign! == W set latitude=-!latitude!
    echo %%a,!longitude!,!latitude!,%%d>> thefile.tmp
)
del thefile.txt
ren thefile.tmp thefile.txt
</code>```

Body:
I'm faced with a problem.  I have a text list of thousands of cities and their gps coordinates.  The format is:

City,longitude,latitude,Parent

so an example might be:

Los Angeles,34.11N,118.41W,California

The problem is that I need the long/lat to be in + and - values so the correct entry would be:

Los Angeles,34.11,-118.41,California

So the script would be something like

Find "W" or "S" (west and south get the "-" symbol)

if you find either of those letters within the 2nd or 3rd "," insert a "-" symbol before the first number. (we don't want to affect the words in the 1st or 4th field)

then delete any letter from the long/lat field.

This could be done a zillion ways - excel, .bat file, something else?

If anyone could help with this I'd be very grateful.
Thanks

Body:
Try this Batch file:

@echo off
setlocal EnableDelayedExpansion
if exist thefile.tmp del thefile.tmp
for /F "tokens=1-4 delims=," %%a in (thefile.txt) do (
    set longitude=%%b
    set sign=!longitude:~-1!
    set longitude=!longitude:~0,-1!
    if /I !sign! == S set longitude=-!longitude!
    set latitude=%%c
    set sign=!latitude:~-1!
    set latitude=!latitude:~0,-1!
    if /I !sign! == W set latitude=-!latitude!
    echo %%a,!longitude!,!latitude!,%%d>> thefile.tmp
)
del thefile.txt
ren thefile.tmp thefile.txt