问:
Python: overloading the `__call__` dunder method of a class that inherits Enum
Consider the following:

from enum import Enum

class A(int, Enum):

    def __new__(cls, value):
        def call(cls, value):
            print("HELLO 1" + str(value))

        self = super().__new__(cls, value)
        self.__call__ = call
        return self

    def __call__(cls, value):
        print("HELLO 2" + str(value))

class B(A):

    NULL  = 0
    BOB   = 1
    ALICE = 2

    def __call__(cls, value):
        print("HELLO 3" + str(value))

print("int: " + str(B(    1)))
print("str: " + str(B("BOB")))
```
<p>running this, you get:</p>
```int: B.BOB
Traceback (most recent call last):
  File "/obfuscated_path/playground.py", line 27, in <module>
    print("str: " + str(B("BOB")))
  File "/usr/lib/python3.10/enum.py", line 384, in __call__
    return cls.__new__(cls, value)
  File "/usr/lib/python3.10/enum.py", line 701, in __new__
    raise ve_exc
ValueError: 'BOB' is not a valid B
```

I don't understand why NONE of the alternative __call__ methods are actually called, and the parent's method (ie, EnumMeta.__call__()) is directly called instead.

How can I overload the __call__ method in a child class of Enum ?

答:
Thanks to the lovely folks in the Python discord channel (in #help-pancakes), I understood what the problem was.

In a nutshell, the problem was confusing Enum as a subclass of EnumMeta, when Enum is actually an instance of EnumMeta. Here, that means that when writing B("BOB"), even though it looks like you're calling the B.__new__ constructor, or that you're calling a classmethod-like B.__call__(), you're actually calling A.__call__() (in fact, __call__ is only ever used for instances).

Taking things one step further, you can consider the following

class MetaClassName(type):

    def __new__(cls, clsname, superclasses, attributedict):
        return super(MetaClassName, cls).__new__(cls,
            clsname,
            superclasses,
            attributedict,
        )

    def __call__(cls, value):
        print("MetaClassName.__call__(): " + str(cls))

class ClassName(metaclass=MetaClassName):

    def __new__(cls, value):
        print("ClassName.__new__(): " + str(cls))
        return int.__new__(cls, value + 1)

my_instance = ClassName(3)
print(my_instance)
```
<p>which prints:</p>
```MetaClassName.__call__(): <class '__main__.ClassName'>
None
```
<p>As you can see, <code>ClassName.__new__()</code> is never called. In the case of EnumMeta and Enum, the only reason why <code>Enum.__new__()</code> is even called is because <code>EnumMeta.__call__()</code> explicitly calls <code>cls.__new__(cls, value)</code>.</p>
<p>Additionally, in the case of Enum, <code>A.__new__()</code> is only called when instantiating the enum instances (one for NULL, one for BOB and one for ALICE), so trying to overload <code>Enum.__new__</code> using <code>A.__new__</code> or <code>B.__new__</code> in the hope of changing <code>B("BOB")</code>'s (failing) behavior is useless. What needs to change to allow <code>B("BOB")</code> to be valid syntax is the <code>Enum.__new__()</code> method itself.</p>
<p>What I did was (removing the stdlib comments to make my change more visible):</p>
<pre class="lang-py prettyprint-override"><code>def __fixed_new(cls, value):
    if type(value) is cls:
        return value
    try:
        return cls._value2member_map_[value]
    except KeyError:
        pass
    except TypeError:
        for member in cls._member_map_.values():
            if member._value_ == value:
                return member
    try:
        exc = None
        ######
        #NB: the following is literally the only line that changes compared to the standard enum.py file
        result = cls._missing_(value) if not isinstance(value, str) else cls[value]
        ######
    except Exception as e:
        exc = e
        result = None
    if isinstance(result, cls):
        return result
    else:
        ve_exc = ValueError("%r is not a valid %s" % (value, cls.__qualname__))
        if result is None and exc is None:
            raise ve_exc
        elif exc is None:
            exc = TypeError(
                    'error in %s._missing_: returned %r instead of None or a valid member'
                    % (cls.__name__, result)
                    )
        exc.__context__ = ve_exc
        raise exc

Enum.__new__ = __fixed_new
</code>```

With this change, any class inherit from enum can "construct new enum instances" (actually, call and get preconstructed enum values) from the corresponding string value, and the original snippet prints:

```<code>int: B.BOB
str: B.BOB
</code>```

Body:
Consider the following:

from enum import Enum

class A(int, Enum):

    def __new__(cls, value):
        def call(cls, value):
            print("HELLO 1" + str(value))

        self = super().__new__(cls, value)
        self.__call__ = call
        return self

    def __call__(cls, value):
        print("HELLO 2" + str(value))

class B(A):

    NULL  = 0
    BOB   = 1
    ALICE = 2

    def __call__(cls, value):
        print("HELLO 3" + str(value))

print("int: " + str(B(    1)))
print("str: " + str(B("BOB")))

running this, you get:

int: B.BOB
Traceback (most recent call last):
  File "/obfuscated_path/playground.py", line 27, in <module>
    print("str: " + str(B("BOB")))
  File "/usr/lib/python3.10/enum.py", line 384, in __call__
    return cls.__new__(cls, value)
  File "/usr/lib/python3.10/enum.py", line 701, in __new__
    raise ve_exc
ValueError: 'BOB' is not a valid B

I don't understand why NONE of the alternative __call__ methods are actually called, and the parent's method (ie, EnumMeta.__call__()) is directly called instead.

How can I overload the __call__ method in a child class of Enum ?

Body:
Thanks to the lovely folks in the Python discord channel (in #help-pancakes), I understood what the problem was.

In a nutshell, the problem was confusing Enum as a subclass of EnumMeta, when Enum is actually an instance of EnumMeta. Here, that means that when writing B("BOB"), even though it looks like you're calling the B.__new__ constructor, or that you're calling a classmethod-like B.__call__(), you're actually calling A.__call__() (in fact, __call__ is only ever used for instances).

Taking things one step further, you can consider the following

class MetaClassName(type):

    def __new__(cls, clsname, superclasses, attributedict):
        return super(MetaClassName, cls).__new__(cls,
            clsname,
            superclasses,
            attributedict,
        )

    def __call__(cls, value):
        print("MetaClassName.__call__(): " + str(cls))

class ClassName(metaclass=MetaClassName):

    def __new__(cls, value):
        print("ClassName.__new__(): " + str(cls))
        return int.__new__(cls, value + 1)

my_instance = ClassName(3)
print(my_instance)

which prints:

MetaClassName.__call__(): <class '__main__.ClassName'>
None

As you can see, ClassName.__new__() is never called. In the case of EnumMeta and Enum, the only reason why Enum.__new__() is even called is because EnumMeta.__call__() explicitly calls cls.__new__(cls, value).

Additionally, in the case of Enum, A.__new__() is only called when instantiating the enum instances (one for NULL, one for BOB and one for ALICE), so trying to overload Enum.__new__ using A.__new__ or B.__new__ in the hope of changing B("BOB")'s (failing) behavior is useless. What needs to change to allow B("BOB") to be valid syntax is the Enum.__new__() method itself.

What I did was (removing the stdlib comments to make my change more visible):

def __fixed_new(cls, value):
    if type(value) is cls:
        return value
    try:
        return cls._value2member_map_[value]
    except KeyError:
        pass
    except TypeError:
        for member in cls._member_map_.values():
            if member._value_ == value:
                return member
    try:
        exc = None
        ######
        #NB: the following is literally the only line that changes compared to the standard enum.py file
        result = cls._missing_(value) if not isinstance(value, str) else cls[value]
        ######
    except Exception as e:
        exc = e
        result = None
    if isinstance(result, cls):
        return result
    else:
        ve_exc = ValueError("%r is not a valid %s" % (value, cls.__qualname__))
        if result is None and exc is None:
            raise ve_exc
        elif exc is None:
            exc = TypeError(
                    'error in %s._missing_: returned %r instead of None or a valid member'
                    % (cls.__name__, result)
                    )
        exc.__context__ = ve_exc
        raise exc

Enum.__new__ = __fixed_new

With this change, any class inherit from enum can "construct new enum instances" (actually, call and get preconstructed enum values) from the corresponding string value, and the original snippet prints:

int: B.BOB
str: B.BOB


来源: stackexchange

问:
How would I stop a while loop after n amount of time?
how would I stop a while loop after 5 minutes if it does not achieve what I want it to achieve.

```<code>while true:
    test = 0
    if test == 5:
        break
    test = test - 1
</code>```

This code throws me in an endless loop.

答:
Try the following:

```<code>from datetime import datetime, timedelta

end_time = datetime.now() + timedelta(minutes=5)
while True:
    current_time = datetime.now()
    if current_time == end_time:
        break
</code>```

ContentLicense: CC BY-SA 3.0

Body:
how would I stop a while loop after 5 minutes if it does not achieve what I want it to achieve.

while true:
    test = 0
    if test == 5:
        break
    test = test - 1

This code throws me in an endless loop.

Body:
Try the following:

from datetime import datetime, timedelta

end_time = datetime.now() + timedelta(minutes=5)
while True:
    current_time = datetime.now()
    if current_time == end_time:
        break

ContentLicense: CC BY-SA 4.0


问:
Wavy shape with CSS
I'm trying to recreate this image with CSS:

I would not need it to repeat. This is what I started but it just has a straight line:

#wave {
  position: absolute;
  height: 70px;
  width: 600px;
  background: #e0efe3;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="wave"></div></code>```

答:
The idea I have is to use two divs. The first div will have the svg set as a background image and the second one will have the same background color as the svg.

Below is an example:

.card {
    display: grid;

    width: 256px;
}

.card > .first {
    padding: 32px 32px 48px 32px;
    background: url("data:image/svg+xml,%3Csvg id='Layer_1' data-name='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 91.61'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%236585c3;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M0,420.39a459.6,459.6,0,0,0,123.1,27c78.32,6,118.8-11.72,182.59-14.61,48.24-2.18,118.44,3.73,206.31,43.82V512H0Z' transform='translate(0 -420.39)'/%3E%3C/svg%3E") no-repeat;
    background-position: bottom;
}

.card > .second {
    padding: 0 32px 32px 32px;
    background-color: #6585C3;
    color: white;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="card">
    <div class="first">
        Lorem ipsum dolor sit amed
    </div>
    <div class="second">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
    </div>
</div></code>```

Title: Wavy shape with CSS

Body:
The idea I have is to use two divs. The first div will have the svg set as a background image and the second one will have the same background color as the svg.

Below is an example:

.card {
    display: grid;

    width: 256px;
}

.card > .first {
    padding: 32px 32px 48px 32px;
    background: url("data:image/svg+xml,%3Csvg id='Layer_1' data-name='Layer 1' xmlns='http://www.w3.org/2000/svg' viewBox='0 0 512 91.61'%3E%3Cdefs%3E%3Cstyle%3E.cls-1%7Bfill:%236585c3;%7D%3C/style%3E%3C/defs%3E%3Cpath class='cls-1' d='M0,420.39a459.6,459.6,0,0,0,123.1,27c78.32,6,118.8-11.72,182.59-14.61,48.24-2.18,118.44,3.73,206.31,43.82V512H0Z' transform='translate(0 -420.39)'/%3E%3C/svg%3E") no-repeat;
    background-position: bottom;
}

.card > .second {
    padding: 0 32px 32px 32px;
    background-color: #6585C3;
    color: white;
}

<div class="card">
    <div class="first">
        Lorem ipsum dolor sit amed
    </div>
    <div class="second">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris
    </div>
</div>


问:
How to get access token from httpcontext using owin and Mvc 5
I've got a IDP implemented in IdentityServer 4. My web app client(implemented in Mvc 5) authenticates with the IDP but now I need to get the access token from the request.
A way to do that in .Net Core is to use the Microsoft.AspNetCore.Authentication.AuthenticationTokenExtensions like so:

```<code>HttpContext.Authentication.GetTokenAsync("acccess_token")
</code>```

I would like to be able to do the same in my .net Mvc5 web app client but I can't find any nuget package or namespace that has a similar implementation. It is important to be able to do this in MVC5 and not .net Core. Anyone came across this before?

PS- Also worth to mention that I'm using OpenIdConnect

答:
I spent some type before I understood, we need to send a string as an argument of AuthenticateAsync which is used in AuthenticationType and SignInAsAuthenticationType.
I hilly recond to use CookieAuthenticationDefaults.AuthenticationType because it will save you from typos.</p>

Body:
I've got a IDP implemented in IdentityServer 4. My web app client(implemented in Mvc 5) authenticates with the IDP but now I need to get the access token from the request.
A way to do that in .Net Core is to use the Microsoft.AspNetCore.Authentication.AuthenticationTokenExtensions like so:

HttpContext.Authentication.GetTokenAsync("acccess_token")

I would like to be able to do the same in my .net Mvc5 web app client but I can't find any nuget package or namespace that has a similar implementation. It is important to be able to do this in MVC5 and not .net Core. Anyone came across this before?

PS- Also worth to mention that I'm using OpenIdConnect


问:
How to make a multiple update on mysql with string replace with value of another column
Hello i'm new in mysql and i have to run a multiple update on my table.
I have 700 records in the table and i have to update them all this way:

table example :
store_id: 1
store_email: storename@gmail.com

for single update i use

```<code>UPDATE stores SET email = '1@gmail.com' WHERE id = 1;
</code>```

i need to update all the emails and replace their name with their id, so it would be like this:

storename@gmail.com --> 1@gmail.com

storename@gmail.com --> 2@gmail.com

storename@gmail.com --> 3@gmail.com

those numers have to be the ID for each store.

Hope you can understand

Thanks for help.

P.S. i need to run it on magento 2

答:
you can use CONCAT() and RIGHT() function for manipulating strings like this:

```<code>UPDATE stores SET email = CONCAT(id, RIGHT(email, 9));
</code>```

The RIGHT('string', n) function extracts n characters (storemail = 9 chars in your case) from a string (starting from right).

Body:
Hello i'm new in mysql and i have to run a multiple update on my table.
I have 700 records in the table and i have to update them all this way:

table example :
store_id: 1
store_email: storename@gmail.com

for single update i use

UPDATE stores SET email = '1@gmail.com' WHERE id = 1;

i need to update all the emails and replace their name with their id, so it would be like this:

storename@gmail.com --> 1@gmail.com

storename@gmail.com --> 2@gmail.com

storename@gmail.com --> 3@gmail.com

those numers have to be the ID for each store.

Hope you can understand

Thanks for help.

P.S. i need to run it on magento 2

Body:
you can use CONCAT() and RIGHT() function for manipulating strings like this:

UPDATE stores SET email = CONCAT(id, RIGHT(email, 9));

The RIGHT('string', n) function extracts n characters (storemail = 9 chars in your case) from a string (starting from right).


问:
redirect() function not working for external URL in CodeIgniter
I want to redirect to www.yahoo.com from my codeIgniter application. I write code like this :
redirect("http://www.yahoo.com");

It is working fine in my local computer (Windows vista / WAMP) but when I upload to linux server it just show blank screen and not redirect.

答: you probably want header: header('location: http://www.yahoo.com');


问:
EF & Automapper. Update nested collections
I trying to update nested collection (Cities) of Country entity.

Just simple enitities and dto's:

```<code>// EF Models
public class Country
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<City> Cities { get; set; }
}

public class City
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int CountryId { get; set; }
    public int? Population { get; set; }

    public virtual Country Country { get; set; }
}

// DTo's
public class CountryData : IDTO
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<CityData> Cities { get; set; }
}

public class CityData : IDTO
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int CountryId { get; set; }
    public int? Population { get; set; }
}
</code>```

And code itself (tested in console app for the sake of simplicity):

```<code>        using (var context = new Context())
        {
            // getting entity from db, reflect it to dto
            var countryDTO = context.Countries.FirstOrDefault(x => x.Id == 1).ToDTO<CountryData>();

            // add new city to dto
            countryDTO.Cities.Add(new CityData
                                      {
                                          CountryId = countryDTO.Id,
                                          Name = "new city",
                                          Population = 100000
                                      });

            // change existing city name
            countryDTO.Cities.FirstOrDefault(x => x.Id == 4).Name = "another name";

            // retrieving original entity from db
            var country = context.Countries.FirstOrDefault(x => x.Id == 1);

            // mapping
            AutoMapper.Mapper.Map(countryDTO, country);

            // save and expecting ef to recognize changes
            context.SaveChanges();
        }
</code>```

This code throws exception:

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

even though entity after last mapping seems just fine and reflects all changes properly.

I've spent much time finding solution but got no result. Please help.

答:
I spent some time coming up with a better solution for AutoMapper 11+, since currently there is no solution for EF Core and mapping relationship collections without the use of AfterMap(). This isn't as efficient as it could be (requires multiple enumeration), but it saves a lot of templating in mapping a lot of child relationships and supports conditions if the source and destination collections are not of the same order:

// AutoMapper Profile
public class MyProfile : Profile
{
  protected override void Configure()
  {
    Mapper.CreateMap<CountryData, Country>()
      .ForMember(d => d.Id, opt => opt.MapFrom(x => x.Id))
      // relationship collections must be ignored, CountryDataMappingAction will take care of it
      .ForMember(d => d.Cities, opt => opt.Ignore())
      .AfterMap<CountryDataMappingAction>();
  }

  public class CountryDataMappingAction : BaseCollectionMapperAction<CountryData, Country>
  {
    public override void Process(CountryData source, Country destination, ResolutionContext context)
    {
      MapCollection(source.Cities, destination.Cities, (x, y) => x.Id == y.Id, context);
    }
  }
}
```
<pre class="lang-cs prettyprint-override"><code>public class BaseCollectionMapperAction<TSource, TDestination> : IMappingAction<TSource, TDestination>
{
    public void MapCollection<TCollectionSource, TCollectionDestination>(IEnumerable<TCollectionSource> sourceCollection, IEnumerable<TCollectionDestination> destCollection, Func<TCollectionSource, TCollectionDestination, bool> predicate, ResolutionContext context)
    {
        MapCollection(sourceCollection.ToList(), destCollection.ToList(), predicate, context);
    }

    public void MapCollection<TCollectionSource, TCollectionDestination>(IList<TCollectionSource> sourceList, IList<TCollectionDestination> destList, Func<TCollectionSource, TCollectionDestination, bool> predicate, ResolutionContext context)
    {
        for (var sourceIndex = 0; sourceIndex < sourceList.Count; sourceIndex++)
        {
            for (var destIndex = 0; sourceIndex < destList.Count; destIndex++)
            {
                var result = predicate(sourceList[sourceIndex], destList[destIndex]);
                if (result)
                {
                    destList[destIndex] = context.Mapper.Map(sourceList[sourceIndex], destList[destIndex]);
                    break;
                }
            }
        }
    }

    public virtual void Process(TSource source, TDestination destination, ResolutionContext context)
    {
        throw new NotImplementedException("You must provide a mapping implementation!");
    }
}
</code>```

Body:
I trying to update nested collection (Cities) of Country entity.

Just simple enitities and dto's:

// EF Models
public class Country
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<City> Cities { get; set; }
}

public class City
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int CountryId { get; set; }
    public int? Population { get; set; }

    public virtual Country Country { get; set; }
}

// DTo's
public class CountryData : IDTO
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual ICollection<CityData> Cities { get; set; }
}

public class CityData : IDTO
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int CountryId { get; set; }
    public int? Population { get; set; }
}

And code itself (tested in console app for the sake of simplicity):

        using (var context = new Context())
        {
            // getting entity from db, reflect it to dto
            var countryDTO = context.Countries.FirstOrDefault(x => x.Id == 1).ToDTO<CountryData>();

            // add new city to dto
            countryDTO.Cities.Add(new CityData
                                      {
                                          CountryId = countryDTO.Id,
                                          Name = "new city",
                                          Population = 100000
                                      });

            // change existing city name
            countryDTO.Cities.FirstOrDefault(x => x.Id == 4).Name = "another name";

            // retrieving original entity from db
            var country = context.Countries.FirstOrDefault(x => x.Id == 1);

            // mapping
            AutoMapper.Mapper.Map(countryDTO, country);

            // save and expecting ef to recognize changes
            context.SaveChanges();
        }

This code throws exception:

The operation failed: The relationship could not be changed because one or more of the foreign-key properties is non-nullable. When a change is made to a relationship, the related foreign-key property is set to a null value. If the foreign-key does not support null values, a new relationship must be defined, the foreign-key property must be assigned another non-null value, or the unrelated object must be deleted.

even though entity after last mapping seems just fine and reflects all changes properly.

I've spent much time finding solution but got no result. Please help.

Body:
I spent some time coming up with a better solution for AutoMapper 11+, since currently there is no solution for EF Core and mapping relationship collections without the use of AfterMap(). This isn't as efficient as it could be (requires multiple enumeration), but it saves a lot of templating in mapping a lot of child relationships and supports conditions if the source and destination collections are not of the same order:

// AutoMapper Profile
public class MyProfile : Profile
{
  protected override void Configure()
  {
    Mapper.CreateMap<CountryData, Country>()
      .ForMember(d => d.Id, opt => opt.MapFrom(x => x.Id))
      // relationship collections must be ignored, CountryDataMappingAction will take care of it
      .ForMember(d => d.Cities, opt => opt.Ignore())
      .AfterMap<CountryDataMappingAction>();
  }

  public class CountryDataMappingAction : BaseCollectionMapperAction<CountryData, Country>
  {
    public override void Process(CountryData source, Country destination, ResolutionContext context)
    {
      MapCollection(source.Cities, destination.Cities, (x, y) => x.Id == y.Id, context);
    }
  }
}

public class BaseCollectionMapperAction<TSource, TDestination> : IMappingAction<TSource, TDestination>
{
    public void MapCollection<TCollectionSource, TCollectionDestination>(IEnumerable<TCollectionSource> sourceCollection, IEnumerable<TCollectionDestination> destCollection, Func<TCollectionSource, TCollectionDestination, bool> predicate, ResolutionContext context)
    {
        MapCollection(sourceCollection.ToList(), destCollection.ToList(), predicate, context);
    }

    public void MapCollection<TCollectionSource, TCollectionDestination>(IList<TCollectionSource> sourceList, IList<TCollectionDestination> destList, Func<TCollectionSource, TCollectionDestination, bool> predicate, ResolutionContext context)
    {
        for (var sourceIndex = 0; sourceIndex < sourceList.Count; sourceIndex++)
        {
            for (var destIndex = 0; sourceIndex < destList.Count; destIndex++)
            {
                var result = predicate(sourceList[sourceIndex], destList[destIndex]);
                if (result)
                {
                    destList[destIndex] = context.Mapper.Map(sourceList[sourceIndex], destList[destIndex]);
                    break;
                }
            }
        }
    }

    public virtual void Process(TSource source, TDestination destination, ResolutionContext context)
    {
        throw new NotImplementedException("You must provide a mapping implementation!");
    }
}


Title: pivot wider not working with group_by in R

Body:
I have the following data set:

structure(list(ID = structure(c(1L, 2L, 9L, 10L, 11L, 12L, 14L,
15L, 16L, 19L, 20L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L,
31L, 32L, 33L, 35L, 36L, 37L, 38L, 39L, 40L, 42L, 43L, 46L, 47L,
48L, 49L, 50L, 51L, 52L, 53L, 55L, 56L, 57L, 58L, 60L, 61L, 62L,
66L, 67L, 68L, 71L, 72L, 73L, 74L, 75L, 81L, 84L, 85L, 93L, 95L,
96L, 104L, 107L, 109L, 116L, 126L, 133L, 135L, 138L, 139L, 146L,
150L, 154L, 164L, 165L, 1L, 2L, 9L, 10L, 11L, 12L, 14L, 15L,
16L, 19L, 20L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L,
32L, 33L, 35L, 36L, 37L, 38L, 39L, 40L, 42L, 43L, 46L, 47L, 48L,
49L, 50L, 51L, 52L, 53L, 55L, 56L, 57L, 58L, 60L, 61L, 62L, 66L,
67L, 68L, 71L, 72L, 73L, 74L, 75L, 81L, 84L, 85L, 93L, 95L, 96L,
104L, 107L, 109L, 116L, 126L, 133L, 135L, 138L, 139L, 146L, 150L,
154L, 164L, 165L, 1L, 2L, 9L, 10L, 11L, 12L, 14L, 15L, 16L, 19L,
20L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L, 32L, 33L,
35L, 36L, 37L, 38L, 39L, 40L, 42L, 43L, 46L, 47L, 48L, 49L, 50L,
51L, 52L, 53L, 55L, 56L, 57L, 58L, 60L, 61L, 62L, 66L, 67L, 68L,
71L, 72L, 73L, 74L, 75L, 81L, 84L, 85L, 93L, 95L, 96L, 104L,
107L, 109L, 116L, 126L, 133L, 135L, 138L, 139L, 146L, 150L, 154L,
164L, 165L), .Label = c("33714", "35377", "38623", "38806", "39593",
"39820", "39951", "40286", "40556", "40798", "40800", "40815",
"43762", "50848", "52183", "52461", "52577", "53202", "53320",
"53873", "54153", "54206", "54581", "55122", "55267", "55462",
"55612", "55920", "56022", "56307", "56420", "56679", "57405",
"57445", "57480", "57725", "57809", "58004", "58215", "58229",
"58503", "59326", "59327", "59344", "59361", "59865", "60099",
"60100", "60280", "60384", "60429", "60493", "60503", "60575",
"60603", "60664", "60846", "61415", "61656", "61749", "61883",
"62081", "62210", "62285", "62937", "62983", "63327", "63329",
"64081", "64328", "64418", "64507", "64596", "65178", "65250",
"65302", "65478", "65480", "65487", "65572", "65802", "65935",
"65974", "65975", "65978", "65991", "65995", "66013", "66154",
"66237", "66245", "66389", "66396", "66460", "66572", "66589",
"67174", "73230", "73525", "73539", "73677", "73942", "73953",
"74034", "74113", "74114", "74427", "74439", "74607", "74641",
"74657", "74794", "74800", "74836", "74942", "74952", "74962",
"74969", "74977", "74985", "74989", "75220", "75229", "75407",
"75653", "75732", "75735", "75757", "75895", "75898", "76381",
"76559", "76574", "76594", "76595", "76746", "76751", "76755",
"76759", "76775", "77088", "77091", "77099", "77134", "77188",
"77203", "77252", "77304", "77413", "77453", "77528", "77556",
"77585", "77668", "78262", "79724", "79730", "79850", "79977",
"80052", "80819", "80901", "80932", "81064", "81065", "81071",
"81098", "81142", "81175"), class = "factor"), Timepoint_yrs = c(0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L,
0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 0L, 1L, 1L, 2L, 2L, 2L, 1L, 2L,
2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 1L, 2L, 2L, 2L, 1L, 2L, 1L,
2L, 1L, 1L, 1L, 2L, 1L, 1L, 2L, 2L, 1L, 2L, 2L, 1L, 1L, 2L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 2L, 1L, 2L, 2L, 1L, 2L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 2L, 2L, 1L, 1L, 1L, 1L, 2L, 1L,
1L, 1L, 1L, 3L, 3L, 3L, 3L, 3L, 2L, 3L, 3L, 2L, 3L, 3L, 3L, 3L,
3L, 3L, 3L, 3L, 3L, 3L, 3L, 2L, 3L, 3L, 3L, 2L, 3L, 2L, 3L, 2L,
3L, 3L, 3L, 2L, 3L, 3L, 3L, 2L, 3L, 2L, 3L, 2L, 2L, 2L, 3L, 3L,
3L, 3L, 3L, 3L, 2L, 3L, 2L, 2L, 2L, 2L, 3L, 3L, 2L, 2L, 2L, 2L,
2L, 2L, 2L, 3L, 2L, 2L, 2L, 2L, 3L, 2L, 2L, 2L, 2L), Sex = c("Male",
"Female", "Male", "Male", "Male", "Male", "Male", "Male", "Male",
"Male", "Male", "Male", "Male", "Male", "Male", "Male", "Female",
"Female", "Male", "Female", "Male", "Female", "Female", "Male",
"Female", "Female", "Male", "Female", "Male", "Male", "Female",
"Female", "Male", "Male", "Male", "Female", "Female", "Female",
"Male", "Male", "Female", "Female", "Male", "Female", "Male",
"Male", "Male", "Female", "Female", "Female", "Male", "Male",
"Male", "Male", "Male", "Male", "Male", "Male", "Female", "Female",
"Female", "Female", "Female", "Male", "Male", "Female", "Male",
"Male", "Male", "Female", "Male", "Female", "Male", "Male", "Male",
"Female", "Male", "Male", "Male", "Male", "Male", "Male", "Male",
"Male", "Male", "Male", "Male", "Male", "Male", "Male", "Female",
"Female", "Male", "Female", "Male", "Female", "Female", "Male",
"Female", "Female", "Male", "Female", "Male", "Male", "Female",
"Female", "Male", "Male", "Male", "Female", "Female", "Female",
"Male", "Male", "Female", "Female", "Male", "Female", "Male",
"Male", "Male", "Female", "Female", "Female", "Male", "Male",
"Male", "Male", "Male", "Male", "Male", "Male", "Female", "Female",
"Female", "Female", "Female", "Male", "Male", "Female", "Male",
"Male", "Male", "Female", "Male", "Female", "Male", "Male", "Male",
"Female", "Male", "Male", "Male", "Male", "Male", "Male", "Male",
"Male", "Male", "Male", "Male", "Male", "Male", "Male", "Female",
"Female", "Male", "Female", "Male", "Female", "Female", "Male",
"Female", "Female", "Male", "Female", "Male", "Male", "Female",
"Female", "Male", "Male", "Male", "Female", "Female", "Female",
"Male", "Male", "Female", "Female", "Male", "Female", "Male",
"Male", "Male", "Female", "Female", "Female", "Male", "Male",
"Male", "Male", "Male", "Male", "Male", "Male", "Female", "Female",
"Female", "Female", "Female", "Male", "Male", "Female", "Male",
"Male", "Male", "Female", "Male", "Female", "Male", "Male"),
    Timepoint = c("bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
    "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
    "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
    "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
    "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
    "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
    "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl", "bl",
    "bl", "bl", "bl", "bl", "bl", "bl", "flu1", "flu1", "flu1",
    "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
    "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
    "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
    "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
    "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
    "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
    "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
    "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1",
    "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu1", "flu2",
    "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
    "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
    "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
    "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
    "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
    "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
    "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
    "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
    "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2", "flu2",
    "flu2"), mean_AD = c(0.0010333, 0.00105981, 0.00113736, 0.001108715,
    0.00104864, 0.00110772, 0.00109096, 0.00109855, 0.00104169,
    0.00112465, 0.001096525, 0.000985059, 0.001098955, 0.001069465,
    0.00105376, 0.00106878, 0.00110388, 0.00108702, 0.001162835,
    0.001070955, 0.0010971, 0.00111695, 0.001060525, 0.00108797,
    0.00103262, 0.001117605, 0.001061707, 0.001156365, 0.00104431,
    0.00109114, 0.001053765, 0.001045395, 0.00106441, 0.00108481,
    0.0011145, 0.001095115, 0.001099075, 0.001057, 0.001096125,
    0.00109696, 0.001064795, 0.00108024, 0.00102137, 0.001103185,
    0.00111948, 0.001110965, 0.00103784, 0.00104419, 0.00101302,
    0.00108785, 0.001098765, 0.001052415, 0.0010976, 0.001064385,
    0.001129705, 0.001076575, 0.001049785, 0.00103181, 0.001078155,
    0.001129015, 0.001024814, 0.00109171, 0.001007862, 0.001099885,
    0.00109162, 0.001060665, 0.00106572, 0.00106803, 0.00113409,
    0.001052505, 0.001138575, 0.00108723, 0.001046765, 0.001090765,
    0.001060205, 0.0010143, 0.001106365, 0.00113328, 0.001045545,
    0.001081185, 0.001102495, 0.00108775, 0.001055425, 0.001130705,
    0.00115777, 0.00105974, 0.001089395, 0.001069105, 0.001054605,
    0.00107229, 0.001128765, 0.001111455, 0.001111155, 0.001095955,
    0.001108905, 0.001077275, 0.00104525, 0.00111458, 0.001110655,
    0.001114555, 0.00110557, 0.001167755, 0.0010552, 0.00110002,
    0.00104991, 0.001069695, 0.001101185, 0.001066815, 0.00109388,
    0.001079455, 0.001097655, 0.001106855, 0.00108804, 0.001102495,
    0.001077445, 0.00104224, 0.001064015, 0.00110557, 0.00112483,
    0.001093865, 0.00105965, 0.001048305, 0.0010719, 0.001098505,
    0.001073105, 0.001049325, 0.001097175, 0.00111584, 0.001122035,
    0.001036422, 0.001016249, 0.001015195, 0.00110143, 0.001121325,
    0.001047755, 0.001063235, 0.001079355, 0.001086495, 0.001074005,
    0.00109106, 0.00103907, 0.0010907, 0.001101685, 0.001017475,
    0.00113138, 0.001086615, 0.001076375, 0.001088265, 0.00106309,
    0.00106822, 0.001052205, 0.001106125, 0.001060125, 0.00106945,
    0.001092695, 0.00107696, 0.001063425, 0.001116725, 0.00105891,
    0.001054205, 0.00109295, 0.00109387, 0.00101807, 0.001066195,
    0.001120295, 0.001111565, 0.001088595, 0.00102183, 0.0010934,
    0.00111935, 0.00105371, 0.00108314, 0.0011006, 0.001079585,
    0.001127775, 0.001140825, 0.00106203, 0.001118035, 0.00103535,
    0.00099512, 0.001078955, 0.00108867, 0.0010789, 0.001030445,
    0.00106243, 0.001028545, 0.00108679, 0.00105624, 0.001110145,
    0.00107318, 0.00106523, 0.001103515, 0.00112404, 0.001064455,
    0.001040425, 0.001059305, 0.00106362, 0.001079395, 0.00107183,
    0.0010652, 0.00106983, 0.00111722, 0.00114111, 0.001059649,
    0.001029902, 0.001062825, 0.001102155, 0.001122135, 0.00103623,
    0.00108648, 0.001081035, 0.001110075, 0.001039397, 0.001057715,
    0.0010338, 0.001071455, 0.001072065, 0.001032233, 0.00111996,
    0.00106407, 0.0010693, 0.001104395)), class = c("grouped_df",
"tbl_df", "tbl", "data.frame"), row.names = c(NA, -222L), groups = structure(list(
    ID = structure(c(1L, 2L, 9L, 10L, 11L, 12L, 14L, 15L, 16L,
    19L, 20L, 22L, 23L, 24L, 25L, 26L, 27L, 28L, 29L, 30L, 31L,
    32L, 33L, 35L, 36L, 37L, 38L, 39L, 40L, 42L, 43L, 46L, 47L,
    48L, 49L, 50L, 51L, 52L, 53L, 55L, 56L, 57L, 58L, 60L, 61L,
    62L, 66L, 67L, 68L, 71L, 72L, 73L, 74L, 75L, 81L, 84L, 85L,
    93L, 95L, 96L, 104L, 107L, 109L, 116L, 126L, 133L, 135L,
    138L, 139L, 146L, 150L, 154L, 164L, 165L), .Label = c("33714",
    "35377", "38623", "38806", "39593", "39820", "39951", "40286",
    "40556", "40798", "40800", "40815", "43762", "50848", "52183",
    "52461", "52577", "53202", "53320", "53873", "54153", "54206",
    "54581", "55122", "55267", "55462", "55612", "55920", "56022",
    "56307", "56420", "56679", "57405", "57445", "57480", "57725",
    "57809", "58004", "58215", "58229", "58503", "59326", "59327",
    "59344", "59361", "59865", "60099", "60100", "60280", "60384",
    "60429", "60493", "60503", "60575", "60603", "60664", "60846",
    "61415", "61656", "61749", "61883", "62081", "62210", "62285",
    "62937", "62983", "63327", "63329", "64081", "64328", "64418",
    "64507", "64596", "65178", "65250", "65302", "65478", "65480",
    "65487", "65572", "65802", "65935", "65974", "65975", "65978",
    "65991", "65995", "66013", "66154", "66237", "66245", "66389",
    "66396", "66460", "66572", "66589", "67174", "73230", "73525",
    "73539", "73677", "73942", "73953", "74034", "74113", "74114",
    "74427", "74439", "74607", "74641", "74657", "74794", "74800",
    "74836", "74942", "74952", "74962", "74969", "74977", "74985",
    "74989", "75220", "75229", "75407", "75653", "75732", "75735",
    "75757", "75895", "75898", "76381", "76559", "76574", "76594",
    "76595", "76746", "76751", "76755", "76759", "76775", "77088",
    "77091", "77099", "77134", "77188", "77203", "77252", "77304",
    "77413", "77453", "77528", "77556", "77585", "77668", "78262",
    "79724", "79730", "79850", "79977", "80052", "80819", "80901",
    "80932", "81064", "81065", "81071", "81098", "81142", "81175"
    ), class = "factor"), .rows = structure(list(c(1L, 75L, 149L
    ), c(2L, 76L, 150L), c(3L, 77L, 151L), c(4L, 78L, 152L),
        c(5L, 79L, 153L), c(6L, 80L, 154L), c(7L, 81L, 155L),
        c(8L, 82L, 156L), c(9L, 83L, 157L), c(10L, 84L, 158L),
        c(11L, 85L, 159L), c(12L, 86L, 160L), c(13L, 87L, 161L
        ), c(14L, 88L, 162L), c(15L, 89L, 163L), c(16L, 90L,
        164L), c(17L, 91L, 165L), c(18L, 92L, 166L), c(19L, 93L,
        167L), c(20L, 94L, 168L), c(21L, 95L, 169L), c(22L, 96L,
        170L), c(23L, 97L, 171L), c(24L, 98L, 172L), c(25L, 99L,
        173L), c(26L, 100L, 174L), c(27L, 101L, 175L), c(28L,
        102L, 176L), c(29L, 103L, 177L), c(30L, 104L, 178L),
        c(31L, 105L, 179L), c(32L, 106L, 180L), c(33L, 107L,
        181L), c(34L, 108L, 182L), c(35L, 109L, 183L), c(36L,
        110L, 184L), c(37L, 111L, 185L), c(38L, 112L, 186L),
        c(39L, 113L, 187L), c(40L, 114L, 188L), c(41L, 115L,
        189L), c(42L, 116L, 190L), c(43L, 117L, 191L), c(44L,
        118L, 192L), c(45L, 119L, 193L), c(46L, 120L, 194L),
        c(47L, 121L, 195L), c(48L, 122L, 196L), c(49L, 123L,
        197L), c(50L, 124L, 198L), c(51L, 125L, 199L), c(52L,
        126L, 200L), c(53L, 127L, 201L), c(54L, 128L, 202L),
        c(55L, 129L, 203L), c(56L, 130L, 204L), c(57L, 131L,
        205L), c(58L, 132L, 206L), c(59L, 133L, 207L), c(60L,
        134L, 208L), c(61L, 135L, 209L), c(62L, 136L, 210L),
        c(63L, 137L, 211L), c(64L, 138L, 212L), c(65L, 139L,
        213L), c(66L, 140L, 214L), c(67L, 141L, 215L), c(68L,
        142L, 216L), c(69L, 143L, 217L), c(70L, 144L, 218L),
        c(71L, 145L, 219L), c(72L, 146L, 220L), c(73L, 147L,
        221L), c(74L, 148L, 222L)), ptype = integer(0), class = c("vctrs_list_of",
    "vctrs_vctr", "list"))), row.names = c(NA, -74L), class = c("tbl_df",
"tbl", "data.frame"), .drop = TRUE))

Which looks like:

# A tibble: 222 x 5
# Groups:   ID [74]
   ID    Timepoint_yrs Sex    Timepoint mean_AD
   <fct>         <int> <chr>  <chr>       <dbl>
 1 33714             0 Male   bl        0.00103
 2 35377             0 Female bl        0.00106
 3 40556             0 Male   bl        0.00114
 4 40798             0 Male   bl        0.00111
 5 40800             0 Male   bl        0.00105
 6 40815             0 Male   bl        0.00111
 7 50848             0 Male   bl        0.00109
 8 52183             0 Male   bl        0.00110
 9 52461             0 Male   bl        0.00104
10 53320             0 Male   bl        0.00112
# ... with 212 more rows

I want to pivot mean_AD wider across Timepoint. However, I get this odd result of NA values in some columns:

DF_wide<- DF %>%
  pivot_wider(names_from = Timepoint, values_from = mean_AD)

# A tibble: 221 x 6
# Groups:   ID [74]
   ID    Timepoint_yrs Sex         bl  flu1  flu2
   <fct>         <int> <chr>    <dbl> <dbl> <dbl>
 1 33714             0 Male   0.00103    NA    NA
 2 35377             0 Female 0.00106    NA    NA
 3 40556             0 Male   0.00114    NA    NA
 4 40798             0 Male   0.00111    NA    NA
 5 40800             0 Male   0.00105    NA    NA
 6 40815             0 Male   0.00111    NA    NA
 7 50848             0 Male   0.00109    NA    NA
 8 52183             0 Male   0.00110    NA    NA
 9 52461             0 Male   0.00104    NA    NA
10 53320             0 Male   0.00112    NA    NA
# ... with 211 more rows

The original DF posted above was created with:

 DF %>%
  group_by(ID) %>%
  mutate(Timepoint_yrs = Age - min(Age)) %>%
  filter(Age < 35) %>%
  dplyr::select(ID, Timepoint_yrs, Sex, Timepoint, mean_AD)

Expected output missing the Timepoint_yrs: (If I remove the group_by and mutate code lines, the pivot_wider function works properly.)

# A tibble: 74 x 5
   ID    Sex         bl    flu1    flu2
   <fct> <chr>    <dbl>   <dbl>   <dbl>
 1 33714 Male   0.00103 0.00106 0.00106
 2 35377 Female 0.00106 0.00101 0.00107
 3 40556 Male   0.00114 0.00111 0.00105
 4 40798 Male   0.00111 0.00113 0.00111
 5 40800 Male   0.00105 0.00105 0.00106
 6 40815 Male   0.00111 0.00108 0.00107
 7 50848 Male   0.00109 0.00110 0.00109
 8 52183 Male   0.00110 0.00109 0.00108
 9 52461 Male   0.00104 0.00106 0.00106
10 53320 Male   0.00112 0.00113 0.00112
# ... with 64 more rows

I'm not sure why this is not working?

Body:
Maybe something like this?

library(dplyr)
library(tidyr)

DF %>%
  pivot_wider(
    id_cols = c(ID, Sex),
    names_from = Timepoint,
    values_from = mean_AD,
  ) %>%
  right_join(DF, by="ID") %>%
  select(ID, Sex=Sex.x, Timepoint_yrs, bl, flu1, flu2)

ID    Sex    Timepoint_yrs      bl    flu1    flu2
   <fct> <chr>          <int>   <dbl>   <dbl>   <dbl>
 1 33714 Male               0 0.00103 0.00106 0.00106
 2 33714 Male               1 0.00103 0.00106 0.00106
 3 33714 Male               3 0.00103 0.00106 0.00106
 4 35377 Female             0 0.00106 0.00101 0.00107
 5 35377 Female             1 0.00106 0.00101 0.00107
 6 35377 Female             3 0.00106 0.00101 0.00107
 7 40556 Male               0 0.00114 0.00111 0.00105
 8 40556 Male               2 0.00114 0.00111 0.00105
 9 40556 Male               3 0.00114 0.00111 0.00105
10 40798 Male               0 0.00111 0.00113 0.00111
# ... with 212 more rows


问:
Biospans from String and Dictionary of Start and End Tokens for NLP Preprocessing
Suppose I have a simple sentence and a dictionary of which has 2 lists as start and end where start has the starting token and end has the ending token for each BIO Span and I want to create the BIO tags for the sentence where B denotes Beginning, I Inside and O Outside which is a pretty well used concept for data preprocessing in NLP how can I do it?

For instance suppose the input sentence is "I like to play soccer while he likes to run" and the dictionary of tokens is {'start': [0, 6], 'end': [3, 9]} then the expected output is B I I I O O B I I I

You can assume the spans don't overlap

答:
This function does exactly this-

```<code>def spanbio(sent, toks):
    """
    Format:
    sent - Sentence - Simple String
    toks - Spans as Dictionary - Ex. {'start': [0, 13, 22], 'end': [4, 19, 27]}
    """
    samplespanstart = toks['start']
    samplespanend = toks['end'].copy()
    print("preadd", samplespanstart,samplespanend)
    for i in range(len(samplespanend)):
        samplespanend[i] = samplespanend[i] + 1
    ls = ['O']*len(sent.split())
    print(sent.split())
    print("lslen", len(ls))
    for i, j in zip(samplespanstart,samplespanend):
        print(i,j)
        for k in range(i,j):
            ls[k] = 'B'
    for i in range(1,len(ls)):
        if (ls[i-1] == 'B' and ls[i] == 'B'):
            ls[i] = 'I'
        elif (ls[i-1] == 'I' and ls[i] == 'B'):
            ls[i] = 'I'
    return ' '.join(ls)
</code>```

Driver Code to Run it -

```<code>sent = "I like to play soccer while he likes to run"
toks = {'start': [0, 6], 'end': [3, 9]}
print(spanbio(sent, toks))
</code>```

Output -

```<code>B I I I O O B I I I
</code>```

Body:
This function does exactly this-

def spanbio(sent, toks):
    """
    Format:
    sent - Sentence - Simple String
    toks - Spans as Dictionary - Ex. {'start': [0, 13, 22], 'end': [4, 19, 27]}
    """
    samplespanstart = toks['start']
    samplespanend = toks['end'].copy()
    print("preadd", samplespanstart,samplespanend)
    for i in range(len(samplespanend)):
        samplespanend[i] = samplespanend[i] + 1
    ls = ['O']*len(sent.split())
    print(sent.split())
    print("lslen", len(ls))
    for i, j in zip(samplespanstart,samplespanend):
        print(i,j)
        for k in range(i,j):
            ls[k] = 'B'
    for i in range(1,len(ls)):
        if (ls[i-1] == 'B' and ls[i] == 'B'):
            ls[i] = 'I'
        elif (ls[i-1] == 'I' and ls[i] == 'B'):
            ls[i] = 'I'
    return ' '.join(ls)

Driver Code to Run it -

sent = "I like to play soccer while he likes to run"
toks = {'start': [0, 6], 'end': [3, 9]}
print(spanbio(sent, toks))

Output -

B I I I O O B I I I


问:
how can I get the function to return index of 2 numbers that add up to a target value
I am writing a function to take a list of integers and an integer called target and return the indices of the two numbers in the list such that they add up to target. But my code doesn't work the way it should. The function ends up not printing anything at all. How can I fix this? I am a beginner and I can't figure out what's wrong :(</p>
```<code>def solution(list, target):
    firstindex = 0
    secondindex = -1

    while(firstindex <= len(list)-1):

        if list[firstindex] + list[secondindex] == target:
            print(f"The sum was found at index {firstindex} and {secondindex}")
            break

        else:
            firstindex = firstindex + 1
            secondindex = secondindex - 1

#I am calling the function here
solution([1,2,3,4,5, 6], 5)
</code>```

答:
You can use this way to solve the problem.</p>
```<code>def solution(list, target):
    n = len(list)
    for firstindex in range(n - 1):
        for secondindex in range(firstindex + 1, n):
            if list[firstindex] + list[secondindex] == target:
                print(f"The sum was found at index {firstindex} and {secondindex}")

solution([1,2,3,4,5, 6], 5)
</code>```

Body:
I am writing a function to take a list of integers and an integer called target and return the indices of the two numbers in the list such that they add up to target. But my code doesn't work the way it should. The function ends up not printing anything at all. How can I fix this? I am a beginner and I can't figure out what's wrong :(

def solution(list, target):
    firstindex = 0
    secondindex = -1

    while(firstindex <= len(list)-1):

        if list[firstindex] + list[secondindex] == target:
            print(f"The sum was found at index {firstindex} and {secondindex}")
            break

        else:
            firstindex = firstindex + 1
            secondindex = secondindex - 1

#I am calling the function here
solution([1,2,3,4,5, 6], 5)

Body:
You can use this way to solve the problem.

def solution(list, target):
    n = len(list)
    for firstindex in range(n - 1):
        for secondindex in range(firstindex + 1, n):
            if list[firstindex] + list[secondindex] == target:
                print(f"The sum was found at index {firstindex} and {secondindex}")

solution([1,2,3,4,5, 6], 5)


问:
How do I display a modal only once per hour for each user?
I have a website that displays a model on index load. Currently it loads every single time you go to the index page. It gets very annoying to the users of the website. I was wondering if I can only display it once per hour per user? The website is located at wikiraces.com</p>
```<code><!-- MODAL FOR NEWS-->
<div id="div1" class="modal">

  <!-- Modal content -->
  <div class="modal-content">
    <span class="close">×</span>
    </div>
    <!-- Modal content -->
<div class="modal-content">
  <div class="modal-header">
    <span class="close">×</span>
    <h2>New Features/Updates</h2>
  </div>
  <div class="modal-body">
   <h4> <p>The Fewest Clicks Game is Back!</p> </h4>
    <p>
    It was down for maintanece for 14 hours but finally it is back
    </p>

    <h4> The Multiplayer host random page is here! </h4>
    <p>
     You can now play multiplayer without the hassle of chosing your own start!
      <br>
      <br>
      <a href="/html/about.html"> <b> Report bugs </b></a>

    </p>
  </div>
  <div class="modal-footer">
   <h5> Enjoy, and remember to share this website with your friends! </h5>
  </div>
</div>
  </div>

</div>

<script>
  // Get the modal
var modal = document.getElementById("div1");

// Get the <span> element that closes the modal
var spanTimed = document.getElementsByClassName("close")[0];

// When the user clicks on the button, open the modal
window.onload = function() {
  modal.style.display = "block";
}

// When the user clicks on <span> (x), close the modal
spanTimed.onclick = function() {
  modal.style.display = "none";
}

// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

</script>
</code>```

答:
We can store the last time the modal was opened in localStorage and everytime the user visits the site, we can check the difference between the time stored and the current time. If the time spend is greater than one hour, then show the modal.

```<code>window.addEventListener('load', () => {
  let time = localStorage.getItem('time');
  if ( time === null ) {
    localStorage.setItem('time', new Date());
    modal.style.display = "block";
    return;
  }

  let current = new Date();
  if ( current - time >= 60 * 60 * 1000 ) {
    modal.style.display = "block";
  }

})
</code>```

Body:
I have a website that displays a model on index load. Currently it loads every single time you go to the index page. It gets very annoying to the users of the website. I was wondering if I can only display it once per hour per user? The website is located at wikiraces.com

    ×

    ×

New Features/Updates

The Fewest Clicks Game is Back!

    It was down for maintanece for 14 hours but finally it is back

 The Multiplayer host random page is here!

     You can now play multiplayer without the hassle of chosing your own start!

        Report bugs

 Enjoy, and remember to share this website with your friends!

Body:
We can store the last time the modal was opened in localStorage and everytime the user visits the site, we can check the difference between the time stored and the current time. If the time spend is greater than one hour, then show the modal.

window.addEventListener('load', () => {
  let time = localStorage.getItem('time');
  if ( time === null ) {
    localStorage.setItem('time', new Date());
    modal.style.display = "block";
    return;
  }

  let current = new Date();
  if ( current - time >= 60 * 60 * 1000 ) {
    modal.style.display = "block";
  }

})


问:
Is it possible (if yes, how) can I set link in CToolTipCtrl
I need a tooltip to display info about each item in CListCtrl.

As a part of info, there is a link.

As I found CToolTip display text message, title, icon.

What about link? is it possible?

答:
Yes, it is possible. Create your tooltip (class derived from CTooltip) adding TTS_USEVISUALSTYLE to the styles you use. You will have to modify uFlags member of the TOOLINFO structure before you call SetToolInfo to receive TTN_LINKCLICK notification.

To show a link inside of the tooltip include a link between tags, like this:
"href="https://www.google.com">Go Google".
When you hover a mouse over this text the cursor will change to indicate that this is a link.
IT would present another challenge to implement a popup tooltip with a link since it is being dismissed before the user can click on the link. I tested it on the tracking tooltip.

HOWEVER the tooltip is parsing this string as a link, but it does not handle it, you will have to handle click on the link (to the best of my knowledge).

Body:
Yes, it is possible. Create your tooltip (class derived from CTooltip) adding TTS_USEVISUALSTYLE to the styles you use. You will have to modify uFlags member of the TOOLINFO structure before you call SetToolInfo to receive TTN_LINKCLICK notification.

To show a link inside of the tooltip include a link between tags, like this:
"<a href="https://www.google.com">Go Google".
When you hover a mouse over this text the cursor will change to indicate that this is a link.
IT would present another challenge to implement a popup tooltip with a link since it is being dismissed before the user can click on the link. I tested it on the tracking tooltip.

HOWEVER the tooltip is parsing this string as a link, but it does not handle it, you will have to handle click on the link (to the best of my knowledge).


问:
C# | Create a json string out of static class fields with values
I need a method that will be able to loop through every static property in a static class, and combine these to a string with json syntax, where key name would equal to Property name, and key value would be the value of the property.

So the result would be a string with value:

{ "StaticPropertyName_string": "string_value_of_this_property", "StaticPropertyName_int": 34 }
```
<p>I have a working method that successfully does the opposite - takes a json and maps data to static fields. But can't figure out how to do it in reverse</p>
<pre class="lang-cs prettyprint-override"><code>    public static void MapProfileToJson(JToken source) //// source = plain json string
    {
        var destinationProperties = typeof(Fields)
            .GetProperties(BindingFlags.Public | BindingFlags.Static);

        foreach (JProperty prop in source)
        {
            var destinationProp = destinationProperties
                .SingleOrDefault(p => p.Name.Equals(prop.Name, StringComparison.OrdinalIgnoreCase));
            var value = ((JValue)prop.Value).Value;

            if (typeof(Fields).GetProperty(prop.Name) != null)
                destinationProp.SetValue(null, Convert.ChangeType(value, destinationProp.PropertyType));
            else
                Console.WriteLine("(!) property \"" + prop.Name + "\" is not found in class... skip");
        }
    }
</code>```

Example static class:

    public static class Fields
    {
        public static bool BoolField { get; set; }
        public static string StringField { get; set; }
        public static int IntField { get; set; }
        public static double DoubleField { get; set; }
    }
```
<p>p.s.
<em>Key value pairs saved in string, could be wrapped at the end like</em></p>
<pre class="lang-cs prettyprint-override"><code>    ResultString = "{ " + resultString + " }";
</code>```

C# .NET 4.7.2 (console app)

答:
As others have said, a static class is not a good design here.

However, it is possible to map it back to JSON with some simple reflection:

```<code>public static JObject MapStaticClassToJson(Type staticClassToMap)
{
    var result = new JObject();
    var properties = staticClassToMap.GetProperties(BindingFlags.Public | BindingFlags.Static);
    foreach (PropertyInfo prop in properties)
    {
        result.Add(new JProperty(prop.Name, prop.GetValue(null, null)));
    }

    return result;
}
</code>```

Body:
I need a method that will be able to loop through every static property in a static class, and combine these to a string with json syntax, where key name would equal to Property name, and key value would be the value of the property.

So the result would be a string with value:

{ "StaticPropertyName_string": "string_value_of_this_property", "StaticPropertyName_int": 34 }

I have a working method that successfully does the opposite - takes a json and maps data to static fields. But can't figure out how to do it in reverse

    public static void MapProfileToJson(JToken source) //// source = plain json string
    {
        var destinationProperties = typeof(Fields)
            .GetProperties(BindingFlags.Public | BindingFlags.Static);

        foreach (JProperty prop in source)
        {
            var destinationProp = destinationProperties
                .SingleOrDefault(p => p.Name.Equals(prop.Name, StringComparison.OrdinalIgnoreCase));
            var value = ((JValue)prop.Value).Value;

            if (typeof(Fields).GetProperty(prop.Name) != null)
                destinationProp.SetValue(null, Convert.ChangeType(value, destinationProp.PropertyType));
            else
                Console.WriteLine("(!) property \"" + prop.Name + "\" is not found in class... skip");
        }
    }

Example static class:

    public static class Fields
    {
        public static bool BoolField { get; set; }
        public static string StringField { get; set; }
        public static int IntField { get; set; }
        public static double DoubleField { get; set; }
    }

p.s.
Key value pairs saved in string, could be wrapped at the end like

    ResultString = "{ " + resultString + " }";

C# .NET 4.7.2 (console app)

Body:
As others have said, a static class is not a good design here.

However, it is possible to map it back to JSON with some simple reflection:

public static JObject MapStaticClassToJson(Type staticClassToMap)
{
    var result = new JObject();
    var properties = staticClassToMap.GetProperties(BindingFlags.Public | BindingFlags.Static);
    foreach (PropertyInfo prop in properties)
    {
        result.Add(new JProperty(prop.Name, prop.GetValue(null, null)));
    }

    return result;
}


问:
Prestashop webservice API didn't work
I has been installed pastershop version prestashop_1.5.4.1. My site is host on localhost like "localhost/myprestashop". When I read documentation that calling prestashop webservice, it's pretty easy. But, when I call like that "localhost/myprestashop/api", it's didn't work. I didn't see any xml result. I see "Not Found" Message at below.

I already enabled webservice and generate key. But, it's didn't work. Please point out me what kinds of problem in here. Webservice generate image is here.

答:
This is an issue related to the rewrite module of the apache. Check if you have this module installed. Once you check this, you have to modify your configuration file of Apache (httpd in Windows, apache2.conf in Ubuntu) and replace the AllowOverride properties like this:

```<code><directory />
Options All
AllowOverride All /*Put All instead of None*/
</directory>

<directory /directory/of/localhost>
Options All
AllowOverride All /*Put All instead of None*/
</directory>
</code>```

Restart the Apache service and it should work.

Title: Prestashop webservice API didn't work

Body:
This is an issue related to the rewrite module of the apache. Check if you have this module installed. Once you check this, you have to modify your configuration file of Apache (httpd in Windows, apache2.conf in Ubuntu) and replace the AllowOverride properties like this:

<directory />
Options All
AllowOverride All /*Put All instead of None*/
</directory>

<directory /directory/of/localhost>
Options All
AllowOverride All /*Put All instead of None*/
</directory>

Restart the Apache service and it should work.


问:
Django relationships between child and parent model
I am busy with a project where I have two models and I'm not sure how to do as I am fairly new to programming.
what I would like to do is have a template that

renders all the instances of first model

and then on the same template I want to have all the sales associated with each of those instances as well as the instances with different states(for example if an instance of first model is linked to 2 sales that has a state of "Confirmed" it should say 2 next to that instance name.)

```<code>   class QAAgent(models.Model):
        user=models.OneToOneField(User,on_delete=models.SET_NULL,null=True)
        Qa_name = models.CharField(max_length=15)

        def __str__(self):
          return self.user.username

   States = (('Pending',"Pending"),("Confirmed","Confirmed"),("Requested","Requested),("Cancelled","Cancelled"),("Not interested","Not interested"))
   class Sale(models.Model):
          QA = models.ForeignKey(QAAgent,on_delete=models.SET_NULL,blank=True,
          null=True,related_name="sale")
          State = models.CharField(choices=States,default="Pending",max_length=15)
          Date_created = models.DateTimeField(auto_now_add=True)
          Date_edited = models.DateTimeField(auto_now=True)

          def__str__(self):
              return self.client_name + " " + self.client_surname

</code>```

I am not sure how to reply to answers but thanks guys that worked perfectly!

答:
To list all your entries of the first model including it's related items you can do the following. Just be sure to pass the correct queryset to the view context.

```<code>{% for entry in qa_agent %}
    {{ entry.qa_name}}
    {{ entry.user.name }}
    {% for sale in entry.qa_sale.all %}
        {{sale.category.state }}
    {% endfor %}
{% endfor %}
</code>```

For your second request just create a method in your model class which filters for the desired status. I've called it get_confirmed here.

```<code>class QAAgent(models.Model):
    user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True)
    qa_name = models.CharField(max_length=15)  # You had Qa_name before

    def get_confirmed(self):
        return self.qa_sale.filter(state="Pending") # just write a method like this one for each of the other statuses.

    def __str__(self):
        return self.user.username
</code>```

And then modify your template code so it uses this method to display the confirmed ones.

```<code>{% for entry in qa_agent %}
    {{ entry.qa_name}}
    {{ entry.user.name }}
    {{ entry.get_confirmed.count }} # <-- like this
{% endfor %}
</code>```

Just a quick side note about python code styling.
For variables and function names use snake_case. for classes use CamelCase.
So for your model properties it's best to only use lower case letters and separate words using an underscore. For classes start with an uppercase letter and separate words by using an uppercase letter for the first letter of the new word. This is how it should look like:

```<code>states = (
    ("Pending", "Pending"),
    ("Confirmed", "Confirmed"),
    ("Requested", "Requested"),
    ("Cancelled", "Cancelled"),
    ("Not interested", "Not interested"),
)

class Sale(models.Model):
    qa = models.ForeignKey(QAAgent, on_delete=models.SET_NULL, blank=True, null=True, related_name="qa_sale")
    state = models.CharField(choices=States, default="Pending", max_length=15)
    date_created = models.DateTimeField(auto_now_add=True)
    date_edited = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.client_name} {self.client_surname}" # If you concatenate strings use an fstring like I did here. It's more readable
</code>```

Body:
I am busy with a project where I have two models and I'm not sure how to do as I am fairly new to programming.
what I would like to do is have a template that

renders all the instances of first model

and then on the same template I want to have all the sales associated with each of those instances as well as the instances with different states(for example if an instance of first model is linked to 2 sales that has a state of "Confirmed" it should say 2 next to that instance name.)

   class QAAgent(models.Model):
        user=models.OneToOneField(User,on_delete=models.SET_NULL,null=True)
        Qa_name = models.CharField(max_length=15)

        def __str__(self):
          return self.user.username

   States = (('Pending',"Pending"),("Confirmed","Confirmed"),("Requested","Requested),("Cancelled","Cancelled"),("Not interested","Not interested"))
   class Sale(models.Model):
          QA = models.ForeignKey(QAAgent,on_delete=models.SET_NULL,blank=True,
          null=True,related_name="sale")
          State = models.CharField(choices=States,default="Pending",max_length=15)
          Date_created = models.DateTimeField(auto_now_add=True)
          Date_edited = models.DateTimeField(auto_now=True)

          def__str__(self):
              return self.client_name + " " + self.client_surname

I am not sure how to reply to answers but thanks guys that worked perfectly!

Body:
To list all your entries of the first model including it's related items you can do the following. Just be sure to pass the correct queryset to the view context.

{% for entry in qa_agent %}
    {{ entry.qa_name}}
    {{ entry.user.name }}
    {% for sale in entry.qa_sale.all %}
        {{sale.category.state }}
    {% endfor %}
{% endfor %}

For your second request just create a method in your model class which filters for the desired status. I've called it get_confirmed here.

class QAAgent(models.Model):
    user = models.OneToOneField(User, on_delete=models.SET_NULL, null=True)
    qa_name = models.CharField(max_length=15)  # You had Qa_name before

    def get_confirmed(self):
        return self.qa_sale.filter(state="Pending") # just write a method like this one for each of the other statuses.

    def __str__(self):
        return self.user.username

And then modify your template code so it uses this method to display the confirmed ones.

{% for entry in qa_agent %}
    {{ entry.qa_name}}
    {{ entry.user.name }}
    {{ entry.get_confirmed.count }} # <-- like this
{% endfor %}

Just a quick side note about python code styling.
For variables and function names use snake_case. for classes use CamelCase.
So for your model properties it's best to only use lower case letters and separate words using an underscore. For classes start with an uppercase letter and separate words by using an uppercase letter for the first letter of the new word. This is how it should look like:

states = (
    ("Pending", "Pending"),
    ("Confirmed", "Confirmed"),
    ("Requested", "Requested"),
    ("Cancelled", "Cancelled"),
    ("Not interested", "Not interested"),
)

class Sale(models.Model):
    qa = models.ForeignKey(QAAgent, on_delete=models.SET_NULL, blank=True, null=True, related_name="qa_sale")
    state = models.CharField(choices=States, default="Pending", max_length=15)
    date_created = models.DateTimeField(auto_now_add=True)
    date_edited = models.DateTimeField(auto_now=True)

    def __str__(self):
        return f"{self.client_name} {self.client_surname}" # If you concatenate strings use an fstring like I did here. It's more readable


问:
NextJS - Linter with lint-staged not working
I've set up lint-staged and husky with NextJS. When we run yarn lint, it calls yarn next lint under the hood and it works. When we call yarn lint-staged, we receive an error:

```<code>✖ yarn lint:
> Couldn't find a `pages` directory. Please create one under the project root

</code>```

The point is that pages directory exists under src and it should work. What is going on?

package.json:

```<code>{
  "scripts": {
    "lint": "next lint"
  },
  "lint-staged": {
    "src/**/*.{ts,tsx}": [
      "yarn lint"
    ]
  }
}
</code>```

答:
use "eslint" instead of "yarn lint" under lint-staged.

I believe next lint has some inherent configurations that aren't compatible with lint-staged.

"eslint" catches the intended error during pre-commits

package.json

{
  "scripts": {
    "lint": "next lint"
  },
  "lint-staged": {
    "src/**/*.{ts,tsx}": [
      "eslint"
    ]
  }
}
```

Body:
I've set up lint-staged and husky with NextJS. When we run yarn lint, it calls yarn next lint under the hood and it works. When we call yarn lint-staged, we receive an error:

✖ yarn lint:
> Couldn't find a `pages` directory. Please create one under the project root

The point is that pages directory exists under src and it should work. What is going on?

package.json:

{
  "scripts": {
    "lint": "next lint"
  },
  "lint-staged": {
    "src/**/*.{ts,tsx}": [
      "yarn lint"
    ]
  }
}


问:
Retrieve data using axios and append data to elements created in callback function
I am trying to use axios to retrieve data from a url and then append the data to html elements I created using javascript.

In a nutshell for each programming language in my url I would like to have a card showing the headline and author name of each article.

This is my HTML

```<code><body>
  <div class="parentDiv">

  </div>
</body>

</html>
</code>```

and my JS

```<code>const CardsTest = (one) => {
  // class headline
  const divHead = Object.assign(document.createElement('div'), {className: 'one', textContent: one.headline});
  // class author
  const divAut = Object.assign(document.createElement('div'), {className: 'writer'});
  const spanCont = Object.assign(document.createElement('span'), {className: 'name', textContent: one.authorName});
  divAut.appendChild(SpanCont);
  divHead.appendChild(divAut);
  return divHead;
}

 const cardAppender = (div) => {
    const divOne = document.querySelector(div);
    axios.get('http://localhost:5000/api/articles')
      .then((resp) => {
        Object.keys(resp.data).forEach (
          function(obj) {
            const topicsData = CardsTest(obj.articles);
            divOne.appendChild(obj.articles)
          }
        )
      })
  }

 cardAppender('parentDiv')
</code>```

I know that my function CardsTest creates all the components and my cardsappender can, at the very least print out the JSON from the target URL. I know if I run the function with axios and console log obj.articles I get an object promise containing the articles in the URL.

To summarize; I expect cardAppender to take a url, and take a callback function (Cards Test) appending the writer and headline to the elements in Cards Test and then append that to my html parentDiv. However this is not happening

UPDATE

Tried changing my cardAppender function by creating an array of programming languages (the keys in my JSON) and then appending headline and authorname for each article to my Cards Test function, but this function is still not creating the components in Cards Test:

```<code>const cardsAppender = (div) => {
  const newArr = ["javascript","bootstrap","technology","jquery","node"]
const divOne = document.querySelector('.parentDiv');
axios.get('http://localhost:5000/api/articles')
      .then((resp) => {
      newArr.forEach((item) => {
        const cardsHolds = CardsTest(resp.data.articles[item])
        divOne.appendChild(cardsHolds)
      })
  })
}
cardsAppender('.parentDiv')
</code>```

答:
You are using Object.keys to iterate, so you need to use that key as a property index.  Or use Object.values.  It's not really clear what shape your data is though, so this might need to be tweaked.

Object.keys(resp.data).forEach (
          function(obj) {
            const topicsData = CardsTest(res.data[obj].articles);
            divOne.appendChild(res.data[obj].articles)
          }

Object.values(resp.data).forEach (
          function(obj) {
            const topicsData = CardsTest(obj.articles);
            divOne.appendChild(obj.articles)
          }
```

Body:
I am trying to use axios to retrieve data from a url and then append the data to html elements I created using javascript.

In a nutshell for each programming language in my url I would like to have a card showing the headline and author name of each article.

This is my HTML

and my JS

const CardsTest = (one) => {
  // class headline
  const divHead = Object.assign(document.createElement('div'), {className: 'one', textContent: one.headline});
  // class author
  const divAut = Object.assign(document.createElement('div'), {className: 'writer'});
  const spanCont = Object.assign(document.createElement('span'), {className: 'name', textContent: one.authorName});
  divAut.appendChild(SpanCont);
  divHead.appendChild(divAut);
  return divHead;
}

 const cardAppender = (div) => {
    const divOne = document.querySelector(div);
    axios.get('http://localhost:5000/api/articles')
      .then((resp) => {
        Object.keys(resp.data).forEach (
          function(obj) {
            const topicsData = CardsTest(obj.articles);
            divOne.appendChild(obj.articles)
          }
        )
      })
  }

 cardAppender('parentDiv')

I know that my function CardsTest creates all the components and my cardsappender can, at the very least print out the JSON from the target URL. I know if I run the function with axios and console log obj.articles I get an object promise containing the articles in the URL.

To summarize; I expect cardAppender to take a url, and take a callback function (Cards Test) appending the writer and headline to the elements in Cards Test and then append that to my html parentDiv. However this is not happening

UPDATE

Tried changing my cardAppender function by creating an array of programming languages (the keys in my JSON) and then appending headline and authorname for each article to my Cards Test function, but this function is still not creating the components in Cards Test:

const cardsAppender = (div) => {
  const newArr = ["javascript","bootstrap","technology","jquery","node"]
const divOne = document.querySelector('.parentDiv');
axios.get('http://localhost:5000/api/articles')
      .then((resp) => {
      newArr.forEach((item) => {
        const cardsHolds = CardsTest(resp.data.articles[item])
        divOne.appendChild(cardsHolds)
      })
  })
}
cardsAppender('.parentDiv')


问:
I can't update worksheets objects links on powerpoint VBA - OneDrive Folder
I've already read in the forums but noone has my exactly problem, so here we go.

I have my excel and powerpoint files in a OneDrive folder (the Powerpoint is in subfolder), the powerpoint has 100 links.
So, in a forum someone suggested that to get the local OneDrive path, you should turn off the process. I did it.
I have to have the excel file open, because the processing time is really slow if the excel is closed. So If I have opened the excel file and run the macro (in other folder diferent to OneDrive) it runs ok, but if I try to do the same but in the OneDrive folder, it generated the next error into the code line pptShape.LinkFormat.Update:

Error -2147188160 (80048240) in runtime. LinkFormat (unknown member):
Invalid request. The linked file was unavailable and could not be
updated

If I have the excel file closed, the macro runs ok, but the process is so slow (almost 30 minuts), because it open and close the excel a hundred times.

does anyone knows why it happened? How can I fix it? I'll appreaciate your help. here is the code to update the links

```<code>Sub updatelinks_1()
Call Shell("cmd.exe /S /C" & "%LOCALAPPDATA%\Microsoft\OneDrive\OneDrive.exe /shutdown")
Application.DisplayAlerts = ppAlertsNone

Dim pptPresentation As Presentation
Dim pptSlide As Slide
Dim pptShape As Shape

'Set the variable to the PowerPoint Presentation
Set pptPresentation = ActivePresentation

'Loop through each slide in the presentation
For Each pptSlide In pptPresentation.Slides

    'Loop through each shape in each slide
    For Each pptShape In pptSlide.Shapes

    'Find out if the shape is a linked object or a linked picture
    If pptShape.Type = msoLinkedOLEObject Then

        Dim name, path1, path2, source, begin, search1, cells As String
        Dim limit1 As Integer

        name = pptShape.LinkFormat.SourceFullName

        limit1 = InStr(1, name, "!")

        cells = Right(name, Len(name) - limit1)

        search1 = "subfoldername"

        path1 = Application.ActivePresentation.FullName

        begin = InStr(1, path1, search1)
        begin = Left(path1, begin - 1)

        file1 = Dir(begin & "*.xlsm")

        source = begin & file1

    End If

    path2 = source & "!" & cells

        pptShape.LinkFormat.SourceFullName = path2

        'update method. code line where generate error
        pptShape.LinkFormat.Update

    End If
    Next
Next

'Update the links (If I use this method on OneDrive folder, it doesn't work and broke all the links because replace the Link name with only the excel file name, not the sheets and cells)
  ' pptPresentation.UpdateLinks

Call Shell("cmd.exe /S /C" & "start %LOCALAPPDATA%\Microsoft\OneDrive\OneDrive.exe /background")
Set pptPresentation = Nothing
Set pptSlide = Nothing
Set pptShape = Nothing

Application.DisplayAlerts = ppAlertsAll
End Sub
</code>```

答:
Good morning everyone.

As I have not seen the solution, I'd like to add my 2 cents.
I have had a similar issue, on a win10 Platform running Office 365.
In my case both files are on the same laptop.
I have seen that the powerpoint VBA procedure to update the path takes a long time by default. ( around 4 Minutes for me as there are 22 linked Objects).
One can speed it up by manually open the target excel file before launching the Powerpoint VBA.
It becomes effectively faster but I hit the issue where for each link the ppt vba procedure tries to update, we get a pop up window telling us that Excel can't open 2 files with same name.

I've tried to add in the PowerPoint VBA procedure :     Application.DisplayAlerts = False , but is logically inefficient as applies to the PPT application and not to the Excel app  !

I finally found one quick (and logic) solution :

at the beginning of the PowerPoint VBA, I ask user to locate the target excel file :

```<code>Set XlApp = CreateObject("Excel.Application")
ExcelFile = XlApp.GetOpenFilename(, , "Would you please locate your excel File")
</code>```

And after, I just Open the target file, and set it with displayLAerts to False.

```<code>XlApp.Visible = True
Set xlWorkbook = XlApp.Workbooks.Open(ExcelFile, True, False)
</code>```

Doing so, I no longer get warnings.

Full source code available .

Wish you a nice day !

Body:
I've already read in the forums but noone has my exactly problem, so here we go.

I have my excel and powerpoint files in a OneDrive folder (the Powerpoint is in subfolder), the powerpoint has 100 links.
So, in a forum someone suggested that to get the local OneDrive path, you should turn off the process. I did it.
I have to have the excel file open, because the processing time is really slow if the excel is closed. So If I have opened the excel file and run the macro (in other folder diferent to OneDrive) it runs ok, but if I try to do the same but in the OneDrive folder, it generated the next error into the code line pptShape.LinkFormat.Update:

Error -2147188160 (80048240) in runtime. LinkFormat (unknown member):
Invalid request. The linked file was unavailable and could not be
updated

If I have the excel file closed, the macro runs ok, but the process is so slow (almost 30 minuts), because it open and close the excel a hundred times.

does anyone knows why it happened? How can I fix it? I'll appreaciate your help. here is the code to update the links

Sub updatelinks_1()
Call Shell("cmd.exe /S /C" & "%LOCALAPPDATA%\Microsoft\OneDrive\OneDrive.exe /shutdown")
Application.DisplayAlerts = ppAlertsNone

Dim pptPresentation As Presentation
Dim pptSlide As Slide
Dim pptShape As Shape

'Set the variable to the PowerPoint Presentation
Set pptPresentation = ActivePresentation

'Loop through each slide in the presentation
For Each pptSlide In pptPresentation.Slides

    'Loop through each shape in each slide
    For Each pptShape In pptSlide.Shapes

    'Find out if the shape is a linked object or a linked picture
    If pptShape.Type = msoLinkedOLEObject Then

        Dim name, path1, path2, source, begin, search1, cells As String
        Dim limit1 As Integer

        name = pptShape.LinkFormat.SourceFullName

        limit1 = InStr(1, name, "!")

        cells = Right(name, Len(name) - limit1)

        search1 = "subfoldername"

        path1 = Application.ActivePresentation.FullName

        begin = InStr(1, path1, search1)
        begin = Left(path1, begin - 1)

        file1 = Dir(begin & "*.xlsm")

        source = begin & file1

    End If

    path2 = source & "!" & cells

        pptShape.LinkFormat.SourceFullName = path2

        'update method. code line where generate error
        pptShape.LinkFormat.Update

    End If
    Next
Next

'Update the links (If I use this method on OneDrive folder, it doesn't work and broke all the links because replace the Link name with only the excel file name, not the sheets and cells)
  ' pptPresentation.UpdateLinks

Call Shell("cmd.exe /S /C" & "start %LOCALAPPDATA%\Microsoft\OneDrive\OneDrive.exe /background")
Set pptPresentation = Nothing
Set pptSlide = Nothing
Set pptShape = Nothing

Application.DisplayAlerts = ppAlertsAll
End Sub

Body:
Good morning everyone.

As I have not seen the solution, I'd like to add my 2 cents.
I have had a similar issue, on a win10 Platform running Office 365.
In my case both files are on the same laptop.
I have seen that the powerpoint VBA procedure to update the path takes a long time by default. ( around 4 Minutes for me as there are 22 linked Objects).
One can speed it up by manually open the target excel file before launching the Powerpoint VBA.
It becomes effectively faster but I hit the issue where for each link the ppt vba procedure tries to update, we get a pop up window telling us that Excel can't open 2 files with same name.

I've tried to add in the PowerPoint VBA procedure :     Application.DisplayAlerts = False , but is logically inefficient as applies to the PPT application and not to the Excel app  !

I finally found one quick (and logic) solution :

at the beginning of the PowerPoint VBA, I ask user to locate the target excel file :

Set XlApp = CreateObject("Excel.Application")
ExcelFile = XlApp.GetOpenFilename(, , "Would you please locate your excel File")

And after, I just Open the target file, and set it with displayLAerts to False.

XlApp.Visible = True
Set xlWorkbook = XlApp.Workbooks.Open(ExcelFile, True, False)

Doing so, I no longer get warnings.

Full source code available .

Wish you a nice day !


问:
Something is going on with my X axis where it looks continuous and is running off the plot on the x axis, although i have limited my x axis
I cannot seem to fix this bar graph so the bars don't go over the axis. I've limited the axis to the minimum date i want, but I think that's what's causing the issue. I hope someone can help. Thank you!

My code:

```<code>    ggplot(rreasont, aes(x = Week, y = count, color = reason, fill = reason)) + geom_bar(stat = "identity", position = "fill", width = 5) +
    scale_color_manual(values = mycolors) + scale_fill_manual(values = mycolors) + labs(y = "Tests Linked to Reason") + theme_linedraw()+ facet_wrap(~Contractor) +
    scale_x_date(breaks = (as.Date(rreasont$Week)), date_labels = "%m/%d") +
    theme(legend.position = "bottom", axis.title = element_text(size = 30), axis.text = element_text(size =25),
          legend.text = element_text(size = 18), legend.title = element_blank(), strip.text = element_text(size = 25)) +
    coord_cartesian(xlim = as.Date(c(min(ymd("2022-01-24")), max(rreasont$Week)))) #limit min date!
  ggsave(paste(savef, "new_reason_for_testing_over_time.png", sep = ""), width = 23, height= 9)
</code>```

The figure:

答:
There are a few things that will give you more breathing room between your bars and the ends of the x axis — which I think is what you’re asking?

First, reduce the relative width of your bars; width = 5 means each bar takes up 5 times the width of the corresponding date on the x axis, which causes it to run off the graph.

Second, you can add space to the x axis either by expanding the limits by a few days in either direction, or with the expand argument to scale_x_date().

```<code>plot +
  scale_x_date(expand = expansion(mult = .1))
# experiment with different values of “mult.”
 # see ?expansion for more details
</code>```

Third, you may get more intuitive spacing by first filtering your data to include only the dates you want, then plotting, and omitting coord_cartesian().

Body:
I cannot seem to fix this bar graph so the bars don't go over the axis. I've limited the axis to the minimum date i want, but I think that's what's causing the issue. I hope someone can help. Thank you!

My code:

    ggplot(rreasont, aes(x = Week, y = count, color = reason, fill = reason)) + geom_bar(stat = "identity", position = "fill", width = 5) +
    scale_color_manual(values = mycolors) + scale_fill_manual(values = mycolors) + labs(y = "Tests Linked to Reason") + theme_linedraw()+ facet_wrap(~Contractor) +
    scale_x_date(breaks = (as.Date(rreasont$Week)), date_labels = "%m/%d") +
    theme(legend.position = "bottom", axis.title = element_text(size = 30), axis.text = element_text(size =25),
          legend.text = element_text(size = 18), legend.title = element_blank(), strip.text = element_text(size = 25)) +
    coord_cartesian(xlim = as.Date(c(min(ymd("2022-01-24")), max(rreasont$Week)))) #limit min date!
  ggsave(paste(savef, "new_reason_for_testing_over_time.png", sep = ""), width = 23, height= 9)

The figure:

Body:
There are a few things that will give you more breathing room between your bars and the ends of the x axis — which I think is what you’re asking?

First, reduce the relative width of your bars; width = 5 means each bar takes up 5 times the width of the corresponding date on the x axis, which causes it to run off the graph.

Second, you can add space to the x axis either by expanding the limits by a few days in either direction, or with the expand argument to scale_x_date().

plot +
  scale_x_date(expand = expansion(mult = .1))
# experiment with different values of “mult.”
 # see ?expansion for more details

Third, you may get more intuitive spacing by first filtering your data to include only the dates you want, then plotting, and omitting coord_cartesian().


问:
Null check operator used on a null value Error in reload webview
Please I'm working on a flutter WebView project and I need to reload my page if I click a button but it gave me this Error : Null check operator used on a null value. Thank you in advance

this is my code :

```<code>WebView(
                  initialUrl: "https://wikoget.com",
                  javascriptMode: JavascriptMode.unrestricted,
                  onWebViewCreated: (WebViewController webViewController) {
                    _webViewController = webViewController;
                    _controller.complete(webViewController);
                  },
                  onPageFinished: (String url) {
                    _webViewController
                        .evaluateJavascript("javascript:(function() { " +
                        "var head = document.getElementsByClassName('main-header-bar-wrap')[0];" +
                        "head.parentNode.style.cssText = ' position: sticky;position: -webkit-sticky; top : 0 ';" +
                        "var footer = document.getElementsByTagName('footer')[0];" +
                        "footer.parentNode.removeChild(footer);" +
                        "})()")
                        .then((value) => debugPrint('Page finished loading Javascript'));
                  },
                  onWebResourceError: (error) => setState(() {
                    isError = true;
                  }),
                ),
              if (isError)Center(

                child :RaisedButton(
                        padding: const EdgeInsets.symmetric(vertical: 10,horizontal: 30),
                        onPressed: ()=>  _webViewController.reload(),

                        color: Color(int.parse("0xff135888")),
                        shape:const RoundedRectangleBorder(
                          borderRadius: BorderRadius.all(Radius.circular(30)),
                        ),
                        child:const Text("Réessayez",style: TextStyle(color:Colors.white),)
                    ),
                  ],
                ),
              ),
</code>```

答:
Although your code is incomplete, here's what you need to make your webview reload easily.

Create a webview controller and initialize it when the webview is created to the controller of the webview:

```<code>WebViewController? webViewController;
.
.
.
onWebViewCreated: (controller){
webViewController = controller;
}
</code>```

reload when your button is pressed:

```<code> onPressed: () {
webViewController!.reload();
},
</code>```

Click here to read more about making your webview work excellently

Body:
Please I'm working on a flutter WebView project and I need to reload my page if I click a button but it gave me this Error : Null check operator used on a null value. Thank you in advance

this is my code :

WebView(
                  initialUrl: "https://wikoget.com",
                  javascriptMode: JavascriptMode.unrestricted,
                  onWebViewCreated: (WebViewController webViewController) {
                    _webViewController = webViewController;
                    _controller.complete(webViewController);
                  },
                  onPageFinished: (String url) {
                    _webViewController
                        .evaluateJavascript("javascript:(function() { " +
                        "var head = document.getElementsByClassName('main-header-bar-wrap')[0];" +
                        "head.parentNode.style.cssText = ' position: sticky;position: -webkit-sticky; top : 0 ';" +
                        "var footer = document.getElementsByTagName('footer')[0];" +
                        "footer.parentNode.removeChild(footer);" +
                        "})()")
                        .then((value) => debugPrint('Page finished loading Javascript'));
                  },
                  onWebResourceError: (error) => setState(() {
                    isError = true;
                  }),
                ),
              if (isError)Center(

                child :RaisedButton(
                        padding: const EdgeInsets.symmetric(vertical: 10,horizontal: 30),
                        onPressed: ()=>  _webViewController.reload(),

                        color: Color(int.parse("0xff135888")),
                        shape:const RoundedRectangleBorder(
                          borderRadius: BorderRadius.all(Radius.circular(30)),
                        ),
                        child:const Text("Réessayez",style: TextStyle(color:Colors.white),)
                    ),
                  ],
                ),
              ),

Body:
Although your code is incomplete, here's what you need to make your webview reload easily.

Create a webview controller and initialize it when the webview is created to the controller of the webview:

WebViewController? webViewController;
.
.
.
onWebViewCreated: (controller){
webViewController = controller;
}

reload when your button is pressed:

 onPressed: () {
webViewController!.reload();
},

Click here to read more about making your webview work excellently


问:
Finding the difference in value counts by keys in two Dictionaries
I have two sample python dictionaries that counts how many times each key appears in a DataFrame.

```<code>dict1 =  {
           2000 : 2,
           3000 : 3,
           4000 : 4,
           5000 : 6,
           6000 : 8
          }

</code>```
```<code>dict2 = {
           4000 : 4,
           3000 : 3,
           2000 : 4,
           6000 : 10,
           5000 : 4
          }
</code>```

I would like to output the following where there is a difference.

```<code>diff = {
        2000 : 2
        5000 : 2
        6000 : 2
       }
</code>```

I would appreciate any help as I am not familiar with iterating though dictionaries. Even if the output shows me at which key there is a difference in values, it would work for me. I did the following but it does not produce any output.

```<code>for (k,v), (k2,v2) in zip(dict1.items(), dict2.items()):
    if k == k2:
        if v == v2:
            pass
        else:
            print('value is different at k')
</code>```

答:
The way you're doing doesn't work because the dicts are not sorted, so k==k2 is always evaluated False.

You could use a dict comprehension where you traverse dict1 and subtract the value in dict2 with the matching key:

```<code>diff = {k: abs(v - dict2[k]) for k, v in dict1.items()}
</code>```

Output:

```<code>{2000: 2, 3000: 0, 4000: 0, 5000: 2, 6000: 2}
</code>```

If you have Python >=3.8, and you want only key-value pairs where value > 0, then you could also use the walrus operator:

```<code>diff = {k: di for k, v in dict1.items() if (di := abs(v - dict2[k])) > 0}
</code>```

Output:

```<code>{2000: 2, 5000: 2, 6000: 2}
</code>```

Since you tagged it as pandas, you can also do a similar job in pandas as well.

First, we need to convert the dicts to DataFrame objects, then join them. Since join joins by index by default and the indexes are the keys in the dicts, you get a nice DataFrame where you can directly find the difference row-wise. Then use the diff method on axis + abs to find the differences.

```<code>df1 = pd.DataFrame.from_dict(dict1, orient='index')
df2 = pd.DataFrame.from_dict(dict2, orient='index')
out = df1.join(df2, lsuffix='_x', rsuffix='').diff(axis=1).abs().dropna(axis=1)['0']
</code>```

Also, instead of creating two DataFrames and joining them, we could also build a single DataFrame by passing a list of the dicts, and use similar methods to get the desired outcome:

```<code>out = pd.DataFrame.from_dict([dict1, dict2]).diff().dropna().abs().loc[1]
</code>```

Output:

```<code>2000    2
3000    0
4000    0
5000    2
6000    2
Name: 0, dtype: int64
</code>```

Body:
I have two sample python dictionaries that counts how many times each key appears in a DataFrame.

dict1 =  {
           2000 : 2,
           3000 : 3,
           4000 : 4,
           5000 : 6,
           6000 : 8
          }

dict2 = {
           4000 : 4,
           3000 : 3,
           2000 : 4,
           6000 : 10,
           5000 : 4
          }

I would like to output the following where there is a difference.

diff = {
        2000 : 2
        5000 : 2
        6000 : 2
       }

I would appreciate any help as I am not familiar with iterating though dictionaries. Even if the output shows me at which key there is a difference in values, it would work for me. I did the following but it does not produce any output.

for (k,v), (k2,v2) in zip(dict1.items(), dict2.items()):
    if k == k2:
        if v == v2:
            pass
        else:
            print('value is different at k')

Body:
The way you're doing doesn't work because the dicts are not sorted, so k==k2 is always evaluated False.

You could use a dict comprehension where you traverse dict1 and subtract the value in dict2 with the matching key:

diff = {k: abs(v - dict2[k]) for k, v in dict1.items()}

Output:

{2000: 2, 3000: 0, 4000: 0, 5000: 2, 6000: 2}

If you have Python >=3.8, and you want only key-value pairs where value > 0, then you could also use the walrus operator:

diff = {k: di for k, v in dict1.items() if (di := abs(v - dict2[k])) > 0}

Output:

{2000: 2, 5000: 2, 6000: 2}

Since you tagged it as pandas, you can also do a similar job in pandas as well.

First, we need to convert the dicts to DataFrame objects, then join them. Since join joins by index by default and the indexes are the keys in the dicts, you get a nice DataFrame where you can directly find the difference row-wise. Then use the diff method on axis + abs to find the differences.

df1 = pd.DataFrame.from_dict(dict1, orient='index')
df2 = pd.DataFrame.from_dict(dict2, orient='index')
out = df1.join(df2, lsuffix='_x', rsuffix='').diff(axis=1).abs().dropna(axis=1)['0']

Also, instead of creating two DataFrames and joining them, we could also build a single DataFrame by passing a list of the dicts, and use similar methods to get the desired outcome:

out = pd.DataFrame.from_dict([dict1, dict2]).diff().dropna().abs().loc[1]

Output:

2000    2
3000    0
4000    0
5000    2
6000    2
Name: 0, dtype: int64


问:
gzdecode() insufficient memory - size is exhausted
Do you know any solucion to unpack large .gz in php (>200 MB .gz, >4GB original... maybe in packs of >1GB or >2GB inside) ?

Solucion of decode .gz part by part is needed.

Code
gzdecode(@file_get_contents($file))

gets PHP error:

PHP Fatal error:  Allowed memory size of 268435456 bytes exhausted (tried to allocate ...

of course.

I cannot increase the PHP memory limit of the webserver, and it seems to be no point in trying while data >>1GB.

Using inflate_add() isn't solution, it generates the same "PHP Fatal error:  Allowed memory size ... exhausted ...".

Any idea?
(I found no answers in 1, 2 etc.)

答: Use gzopen() instead of gzdcode(). Then you can read small chunks at a time with gzread().