问:
Cyclic references when converting with MapStruct. Overflow error. Context does not work
I have 2 entities, with 1-to-1 association (ProfileEntity and VCardEntity)

Entity vcard:

```<code>@Entity
@Table(name = "vcard")
@AllArgsConstructor
@NoArgsConstructor
@Data
@SequenceGenerator(name="vcard_id_seq_generator", sequenceName="vcard_id_seq", allocationSize = 1)
public class VCardEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "vcard_id_seq_generator")
    @Column(name="vcard_id")
    Long id;
    String account;
    @Column(name = "first_name")
    String firstName;
    @Column(name = "last_name")
    String lastName;
    @Column(name = "pbxinfo_json")
    String pbxInfoJson;
    @Column(name = "avatar_id")
    String avatarId;
    @OneToOne(mappedBy = "vcard")
    ProfileEntity profile;
}
</code>```

entity Profile:

```<code>@Entity
@AllArgsConstructor
@NoArgsConstructor
@Data
@Table(name = "profile")
public class ProfileEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "profile_id")
    private Long profileId;

    private String account;
    @Column(name = "product_id")
    private String productId;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "vcard_id", referencedColumnName = "vcard_id")
    private VCardEntity vcard;
}
</code>```

I use map struct as follow:

```<code>public class CycleAvoidingMappingContext {
    private Map<Object, Object> knownInstances = new IdentityHashMap<Object, Object>();

    @BeforeMapping
    public <T> T getMappedInstance(Object source, @TargetType Class<T> targetType) {
        return targetType.cast(knownInstances.get(source));
    }

    @BeforeMapping
    public void storeMappedInstance(Object source, @MappingTarget Object target) {
        knownInstances.put( source, target );
    }
}

@Mapper(componentModel = "spring")
public interface EntityToProfile {
    ProfileEntity profileToEntity(Profile profile, @Context CycleAvoidingMappingContext context);
    Profile entityToProfile(ProfileEntity entity, @Context CycleAvoidingMappingContext context);
}

@Mapper(componentModel = "spring")
public interface EntityToVCard {
    VCard entityToVcard(VCardEntity entity, @Context CycleAvoidingMappingContext context);
    VCardEntity vcardToEntity(VCard vcard, @Context CycleAvoidingMappingContext context);
}
</code>```

Finally i call mapping in my service:

```<code>@Service
@RequiredArgsConstructor
@Slf4j
public class DefaultChatService implements ChatService {
    private final ProfileRepository profileRepository;
    private final EntityToProfile entityToProfileMapper;
    private final EntityToVCard entityToVCardMapper;

    @Override
    public List<Profile> findAllProfile(Optional<Long> id) {
        if (id.isPresent()) {
            Optional<ProfileEntity> result = profileRepository.findById(id.get());
            if (result.isPresent()) {
                Profile profile = entityToProfileMapper.entityToProfile(result.get(), new CycleAvoidingMappingContext());
                return Stream.of(profile).collect(Collectors.toList());
            }
        }
        return new ArrayList<Profile>();
    }
}
</code>```

and i got the error
ERROR 15976 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.StackOverflowError] with root cause
java.lang.StackOverflowError: null

Any thoughts how can i fix it?
In my view i did everything as it's written here Prevent Cyclic references when converting with MapStruct but it doesn't work for me

答:
Found a solution, all i had to do was to change from @Value to @Data for my models

example given:

```<code>@Data
public class Profile {
    Long profileId;
    String account;
    String productId;
    VCard vcard;
}
</code>```

and

```<code>@Data
public class VCard {
    Long id;
    String account;
    String firstName;
    String lastName;
    String pbxInfoJson;
    String avatarId;
    Profile profile;
}
</code>```

Otherwise mapstruct could not generate proper mapping code. It was trying to store an instance in knownInstances after creating an object, for example Profile. But because @value doesn't provide a way to set properties after creating the object (immutable object) it had to create all settings first and then use all args constructor which led to a mapping profile first which in turn was trying to do the same and map vcard first before storing the VCard object in knownInstances.
This is why the cyclic reference problem could not be solved

Properly generated code:

```<code>public Profile entityToProfile(ProfileEntity entity, CycleAvoidingMappingContext context) {
        Profile target = context.getMappedInstance( entity, Profile.class );
        if ( target != null ) {
            return target;
        }

        if ( entity == null ) {
            return null;
        }

        Profile profile = new Profile();

        context.storeMappedInstance( entity, profile );

        profile.setAccount( entity.getAccount() );
        profile.setProductId( entity.getProductId() );
        profile.setDeviceListJson( entity.getDeviceListJson() );
        profile.setLastSid( entity.getLastSid() );
        profile.setBalanceValue( entity.getBalanceValue() );
        profile.setBalanceCurrency( entity.getBalanceCurrency() );
        profile.setStatusJson( entity.getStatusJson() );
        profile.setData( entity.getData() );
        profile.setMissedCallsCount( entity.getMissedCallsCount() );
        profile.setFirstCallSid( entity.getFirstCallSid() );
        profile.setLastMissedCallSid( entity.getLastMissedCallSid() );
        profile.setRemoveToCallSid( entity.getRemoveToCallSid() );
        profile.setOutgoingLines( entity.getOutgoingLines() );
        profile.setFeatures( entity.getFeatures() );
        profile.setPermissions( entity.getPermissions() );
        profile.setVcard( vCardEntityToVCard( entity.getVcard(), context ) );

        return profile;
    }
}
</code>```

As you can see, firstly, it saves the object in context.storeMappedInstance( entity, profile ); and then fills the properties.

Body:
I have 2 entities, with 1-to-1 association (ProfileEntity and VCardEntity)

Entity vcard:

@Entity
@Table(name = "vcard")
@AllArgsConstructor
@NoArgsConstructor
@Data
@SequenceGenerator(name="vcard_id_seq_generator", sequenceName="vcard_id_seq", allocationSize = 1)
public class VCardEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "vcard_id_seq_generator")
    @Column(name="vcard_id")
    Long id;
    String account;
    @Column(name = "first_name")
    String firstName;
    @Column(name = "last_name")
    String lastName;
    @Column(name = "pbxinfo_json")
    String pbxInfoJson;
    @Column(name = "avatar_id")
    String avatarId;
    @OneToOne(mappedBy = "vcard")
    ProfileEntity profile;
}

entity Profile:

@Entity
@AllArgsConstructor
@NoArgsConstructor
@Data
@Table(name = "profile")
public class ProfileEntity {
    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE)
    @Column(name = "profile_id")
    private Long profileId;

    private String account;
    @Column(name = "product_id")
    private String productId;

    @OneToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "vcard_id", referencedColumnName = "vcard_id")
    private VCardEntity vcard;
}

I use map struct as follow:

public class CycleAvoidingMappingContext {
    private Map<Object, Object> knownInstances = new IdentityHashMap<Object, Object>();

    @BeforeMapping
    public <T> T getMappedInstance(Object source, @TargetType Class<T> targetType) {
        return targetType.cast(knownInstances.get(source));
    }

    @BeforeMapping
    public void storeMappedInstance(Object source, @MappingTarget Object target) {
        knownInstances.put( source, target );
    }
}

@Mapper(componentModel = "spring")
public interface EntityToProfile {
    ProfileEntity profileToEntity(Profile profile, @Context CycleAvoidingMappingContext context);
    Profile entityToProfile(ProfileEntity entity, @Context CycleAvoidingMappingContext context);
}

@Mapper(componentModel = "spring")
public interface EntityToVCard {
    VCard entityToVcard(VCardEntity entity, @Context CycleAvoidingMappingContext context);
    VCardEntity vcardToEntity(VCard vcard, @Context CycleAvoidingMappingContext context);
}

Finally i call mapping in my service:

@Service
@RequiredArgsConstructor
@Slf4j
public class DefaultChatService implements ChatService {
    private final ProfileRepository profileRepository;
    private final EntityToProfile entityToProfileMapper;
    private final EntityToVCard entityToVCardMapper;

    @Override
    public List<Profile> findAllProfile(Optional<Long> id) {
        if (id.isPresent()) {
            Optional<ProfileEntity> result = profileRepository.findById(id.get());
            if (result.isPresent()) {
                Profile profile = entityToProfileMapper.entityToProfile(result.get(), new CycleAvoidingMappingContext());
                return Stream.of(profile).collect(Collectors.toList());
            }
        }
        return new ArrayList<Profile>();
    }
}

and i got the error
ERROR 15976 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Handler dispatch failed; nested exception is java.lang.StackOverflowError] with root cause
java.lang.StackOverflowError: null

Any thoughts how can i fix it?
In my view i did everything as it's written here Prevent Cyclic references when converting with MapStruct but it doesn't work for me

Body:
Found a solution, all i had to do was to change from @Value to @Data for my models

example given:

@Data
public class Profile {
    Long profileId;
    String account;
    String productId;
    VCard vcard;
}

and

@Data
public class VCard {
    Long id;
    String account;
    String firstName;
    String lastName;
    String pbxInfoJson;
    String avatarId;
    Profile profile;
}

Otherwise mapstruct could not generate proper mapping code. It was trying to store an instance in knownInstances after creating an object, for example Profile. But because @value doesn't provide a way to set properties after creating the object (immutable object) it had to create all settings first and then use all args constructor which led to a mapping profile first which in turn was trying to do the same and map vcard first before storing the VCard object in knownInstances.
This is why the cyclic reference problem could not be solved

Properly generated code:

public Profile entityToProfile(ProfileEntity entity, CycleAvoidingMappingContext context) {
        Profile target = context.getMappedInstance( entity, Profile.class );
        if ( target != null ) {
            return target;
        }

        if ( entity == null ) {
            return null;
        }

        Profile profile = new Profile();

        context.storeMappedInstance( entity, profile );

        profile.setAccount( entity.getAccount() );
        profile.setProductId( entity.getProductId() );
        profile.setDeviceListJson( entity.getDeviceListJson() );
        profile.setLastSid( entity.getLastSid() );
        profile.setBalanceValue( entity.getBalanceValue() );
        profile.setBalanceCurrency( entity.getBalanceCurrency() );
        profile.setStatusJson( entity.getStatusJson() );
        profile.setData( entity.getData() );
        profile.setMissedCallsCount( entity.getMissedCallsCount() );
        profile.setFirstCallSid( entity.getFirstCallSid() );
        profile.setLastMissedCallSid( entity.getLastMissedCallSid() );
        profile.setRemoveToCallSid( entity.getRemoveToCallSid() );
        profile.setOutgoingLines( entity.getOutgoingLines() );
        profile.setFeatures( entity.getFeatures() );
        profile.setPermissions( entity.getPermissions() );
        profile.setVcard( vCardEntityToVCard( entity.getVcard(), context ) );

        return profile;
    }
}

As you can see, firstly, it saves the object in context.storeMappedInstance( entity, profile ); and then fills the properties.


来源: stackexchange

问:
How can I enforce that a user is only logged in once in Jboss/J2EE?
I need to enforce that some users (that have a flag at true) can only have 1 active session.
I mean, the users logs in 1 browser and can't login in another browser/computer.

I tried using my own loginmodule but the second time I login (in another browser) the loginmodule isn't used, it seems something is being cached...

答: If you use Spring Security, there is an option for concurrent session control. You would want only 1 session. There is an explanation of integrating Spring Security with JBoss.</p>

OwnerDisplayName: AlfaTeK

ContentLicense: CC BY-SA 2.5

OwnerDisplayName: CoverosGene

LastEditorDisplayName: CoverosGene


问:
Is relational database able to leverage the way of consistent hashing to do the partition table?
Assume we have a user table to be partitioned by user id as integer 1,2,3...n . Can I use the way  of consistent hashing used to partition the table?

The benefit would be if the number of partitions is increased or decreased, old index can be the same.

Question A.

Is it a good idea to use consistent hashing algorithm to do the partition table?

Question B.

Any relational database has this built in supported?

I guess some nosql database already use it.

But database here refer to relational database.

I just encountered this question in an interview. In the first reaction I just answered mod by length, but then be challenged if partitioning the table into more pieces, then it will cause problems.

答:
After I researched some wiki reference pages like Partition (database)

I believe my idea belongs to Composite partitioning .

Composite partitioning allows for certain combinations of the above partitioning schemes, by for example first applying a range partitioning and then a hash partitioning. Consistent hashing could be considered a composite of hash and list partitioning where the hash reduces the key space to a size that can be listed.

It also introduces some concepts like Consistent hashing, and Hash table

But some link like Partition (database) is kind of old. If some one can find more latest reference that will be better. My answer is incomplete indeed. Hope some one can answer it better!

UPDATE

Looks like Jonathan Ellis already mentioned in his blog, The Cassandra distributed database supports two partitioning schemes now: the traditional consistent hashing scheme, and an order-preserving partitioner.
http://spyced.blogspot.com/2009/05/consistent-hashing-vs-order-preserving.html

From Tom White's blog. A sample implemtation in java of consistent hashing

```<code>import java.util.Collection;
import java.util.SortedMap;
import java.util.TreeMap;

public class ConsistentHash<T> {
    private final HashFunction hashFunction;
    private final int numberOfReplicas;
    private final SortedMap<Integer, T> circle = new TreeMap<Integer, T>();

    public ConsistentHash(HashFunction hashFunction, int numberOfReplicas,
            Collection<T> nodes) {
        this.hashFunction = hashFunction;
        this.numberOfReplicas = numberOfReplicas;
        for (T node : nodes) {
            add(node);
        }
    }

    public void add(T node) {
        for (int i = 0; i < numberOfReplicas; i++) {
            circle.put(hashFunction.hash(node.toString() + i), node);
        }
    }

    public void remove(T node) {
        for (int i = 0; i < numberOfReplicas; i++) {
            circle.remove(hashFunction.hash(node.toString() + i));
        }
    }

    public T get(Object key) {
        if (circle.isEmpty()) {
            return null;
        }
        int hash = hashFunction.hash(key);
        if (!circle.containsKey(hash)) {
            SortedMap<Integer, T> tailMap = circle.tailMap(hash);
            hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
        }
        return circle.get(hash);
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
After I researched some wiki reference pages like Partition (database)

I believe my idea belongs to Composite partitioning .

Composite partitioning allows for certain combinations of the above partitioning schemes, by for example first applying a range partitioning and then a hash partitioning. Consistent hashing could be considered a composite of hash and list partitioning where the hash reduces the key space to a size that can be listed.

It also introduces some concepts like Consistent hashing, and Hash table

But some link like Partition (database) is kind of old. If some one can find more latest reference that will be better. My answer is incomplete indeed. Hope some one can answer it better!

UPDATE

Looks like Jonathan Ellis already mentioned in his blog, The Cassandra distributed database supports two partitioning schemes now: the traditional consistent hashing scheme, and an order-preserving partitioner.
http://spyced.blogspot.com/2009/05/consistent-hashing-vs-order-preserving.html

From Tom White's blog. A sample implemtation in java of consistent hashing

import java.util.Collection;
import java.util.SortedMap;
import java.util.TreeMap;

public class ConsistentHash<T> {
    private final HashFunction hashFunction;
    private final int numberOfReplicas;
    private final SortedMap<Integer, T> circle = new TreeMap<Integer, T>();

    public ConsistentHash(HashFunction hashFunction, int numberOfReplicas,
            Collection<T> nodes) {
        this.hashFunction = hashFunction;
        this.numberOfReplicas = numberOfReplicas;
        for (T node : nodes) {
            add(node);
        }
    }

    public void add(T node) {
        for (int i = 0; i < numberOfReplicas; i++) {
            circle.put(hashFunction.hash(node.toString() + i), node);
        }
    }

    public void remove(T node) {
        for (int i = 0; i < numberOfReplicas; i++) {
            circle.remove(hashFunction.hash(node.toString() + i));
        }
    }

    public T get(Object key) {
        if (circle.isEmpty()) {
            return null;
        }
        int hash = hashFunction.hash(key);
        if (!circle.containsKey(hash)) {
            SortedMap<Integer, T> tailMap = circle.tailMap(hash);
            hash = tailMap.isEmpty() ? circle.firstKey() : tailMap.firstKey();
        }
        return circle.get(hash);
    }
}


问:
three blured circles in background UI design challenge
How to create this kind of app background.it uses three circle in three parts of screen.
how to create a background color like this???

答:
Try to use

BackdropFilter

```<code>class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFFF3F6FE),
      body: Stack(
        children: [
          Positioned(
              top: -150,
              left: -150,
              child: Container(
                width: 300,
                height: 300,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(500),
                    color: Color(0xFFD8E4FC)),
              )),
          Positioned(
              top: 200,
              right: -150,
              child: Container(
                width: 300,
                height: 300,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(500),
                    color: Color(0xFFE8DCFC)),
              )),
          Positioned(
              bottom: -150,
              left: -150,
              child: Container(
                width: 300,
                height: 300,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(500),
                    color: Color(0xFFD8E4FC)),
              )),
          Container(
            child: BackdropFilter(
              filter: ImageFilter.blur(sigmaX: 50.0, sigmaY: 50.0),
              child: Container(
                decoration: BoxDecoration(color: Colors.white.withOpacity(0.0)),
              ),
            ),
          )
        ],
      ),
    );
  }
}
</code>```

Result :

ContentLicense: CC BY-SA 4.0

Body:
Try to use

BackdropFilter

class MyHomePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Color(0xFFF3F6FE),
      body: Stack(
        children: [
          Positioned(
              top: -150,
              left: -150,
              child: Container(
                width: 300,
                height: 300,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(500),
                    color: Color(0xFFD8E4FC)),
              )),
          Positioned(
              top: 200,
              right: -150,
              child: Container(
                width: 300,
                height: 300,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(500),
                    color: Color(0xFFE8DCFC)),
              )),
          Positioned(
              bottom: -150,
              left: -150,
              child: Container(
                width: 300,
                height: 300,
                decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(500),
                    color: Color(0xFFD8E4FC)),
              )),
          Container(
            child: BackdropFilter(
              filter: ImageFilter.blur(sigmaX: 50.0, sigmaY: 50.0),
              child: Container(
                decoration: BoxDecoration(color: Colors.white.withOpacity(0.0)),
              ),
            ),
          )
        ],
      ),
    );
  }
}

Result :


问:
pre-commit vs tox | what's the difference | scope of use
Tox:
https://tox.wiki/en/latest/

pre-commit:
https://pre-commit.com/

I would like to understand the borders for both choices.

I know that pre-commit creates a py environment - same as tox. To me, their architecture looks a bit the same.

Some people use them in combination... what pre-commit can't do, that tox can? I saw examples where with pre-commit during CI pipeline you can run unit tests, etc.

Which one is the best to integrate within the CI build?

答:
In short, pre-commit is a linter/formatter runner, tox is a generic virtual env management and test command line tool.

While tox could run linters too, it is tedious to manage the versions of the linters. In pre-commit you can just run pre-commit autoupdate, and all linters get updated.

On the other hand tox can run e.g. a test suite or a coverage report for many different Python versions. This is not only helpful for a library, but also for an app - so you can already test the upcoming Python versions.

tox is also used to create documentation, and sometimes also to make a release - you can't (shouldn't) do this with pre-commit.

And tox is certainly not obsolete, although GitHub actions can test against different Python versions, as you can run tox both local and in CI.

I gave a lightning talk on this topic:
https://www.youtube.com/watch?v=OnM3KuE7MQM

Which one is the best to integrate within the CI build?

I like to run pre-commit via tox, both in CI and locally.

Example tox configuration

https://github.com/jugmac00/flask-reuploaded/blob/6496f8427a06be4a9f6a5699757ca7f9aba78ef6/tox.ini#L24-L26

Example pre-commit configuration

https://github.com/jugmac00/flask-reuploaded/blob/6496f8427a06be4a9f6a5699757ca7f9aba78ef6/.pre-commit-config.yaml


问:
Can I pass a built-in array to std::ostream_iterator without an array-to-pointer decay?
I have overloaded operator<< to print a built-in array const int (&arr)[N]:

template <size_t N>
std::ostream& operator<<(std::ostream& os, const int (&arr)[N])
{
    os << "{ ";
    bool first{true};
    for (int i : arr)
    {
        os << (first ? "" : ", ") << i;
        first = false;
    }
    return os << " }";
}
```
<p>I can use it to print a <code>const int (&)[5]</code> array to <code>std::cout</code>:</p>
<pre class="lang-cpp prettyprint-override"><code>    int arr[3][5] = {{3, 4, 6, 1, 1}, {6, 3, 4, 5, 1}, {6, 1, 2, 3, 3}};

    for (const auto& subarr : arr) { std::cout << subarr << "\n"; }

// Outputs:
//
//   { 3, 4, 6, 1, 1 }
//   { 6, 3, 4, 5, 1 }
//   { 6, 1, 2, 3, 3 }
</code>```

However, when I try to print the same array via a std::copy to std::ostream_iterator<const int (&)[5]>, I just get the array address printed out:

std::copy(std::cbegin(arr), std::cend(arr),
        std::ostream_iterator<const int (&)[5]>{std::cout, "\n"});

// Outputs:
//
//   0x7ffec4f84db0
//   0x7ffec4f84dc4
//   0x7ffec4f84dd8
```

I suppose the array is decaying to a pointer at the ostream_iterator end. If so, is there a way to avoid that?

[Demo] for a working version.

There are many questions in this site regarding array-to-pointer decay, but I haven't seen one that was helping with this case.

Actually, this answer says:

[...] you can also prevent decay in your original version of f if
you explicitly specify the template agument T as a
reference-to-array type

f<int (&)[27]>(array);

But that doesn't seem to be happening when constructing the ostream_iterator.

答:
This has nothing to do with array-to-pointer decay and everything to do with how name lookup works.

In this version:

for (const auto& subarr : arr) { std::cout << subarr << "\n"; }
```
<p>your <code>operator<<</code> is a candidate because regular unqualified lookup will find it.</p>
<p>But that's not what <code>ostream_iterator</code> does, its implementation internally will do something like this:</p>
<pre class="lang-cpp prettyprint-override"><code>template <typename T>
void whatever(std::ostream& os, T const& arg) {
    os << arg;
}
</code>```

And that os << arg call is going to not find your operator<< candidate by unqualified lookup (it won't have been declared at the point of definition of the header) and it's not going to find your operator<< by argument-dependent lookup (since it's not in an associated namespace of either argument). Since your function isn't a candidate, instead the one selected is the pointer one - which is why it formats the way it does.

One (bad, don't do this) solution would be to put your operator<< overload inside of namespace std, which would cause argument-dependent lookup to be able to actually find it. But don't do this, since you're not allowed to add things to namespace std (and, generally speaking, shouldn't add your things to other people's namespaces).

So the better solution would be to instead create your own type that formats the way you want it to, since then you can just add an operator<< that properly associates with it - in a way that doesn't involve messing with std.

Body:
I have overloaded operator<< to print a built-in array const int (&arr)[N]:

template <size_t N>
std::ostream& operator<<(std::ostream& os, const int (&arr)[N])
{
    os << "{ ";
    bool first{true};
    for (int i : arr)
    {
        os << (first ? "" : ", ") << i;
        first = false;
    }
    return os << " }";
}

I can use it to print a const int (&)[5] array to std::cout:

    int arr[3][5] = {{3, 4, 6, 1, 1}, {6, 3, 4, 5, 1}, {6, 1, 2, 3, 3}};

    for (const auto& subarr : arr) { std::cout << subarr << "\n"; }

// Outputs:
//
//   { 3, 4, 6, 1, 1 }
//   { 6, 3, 4, 5, 1 }
//   { 6, 1, 2, 3, 3 }

However, when I try to print the same array via a std::copy to std::ostream_iterator<const int (&)[5]>, I just get the array address printed out:

std::copy(std::cbegin(arr), std::cend(arr),
        std::ostream_iterator<const int (&)[5]>{std::cout, "\n"});

// Outputs:
//
//   0x7ffec4f84db0
//   0x7ffec4f84dc4
//   0x7ffec4f84dd8

I suppose the array is decaying to a pointer at the ostream_iterator end. If so, is there a way to avoid that?

[Demo] for a working version.

There are many questions in this site regarding array-to-pointer decay, but I haven't seen one that was helping with this case.

Actually, this answer says:

[...] you can also prevent decay in your original version of f if
you explicitly specify the template agument T as a
reference-to-array type

f<int (&)[27]>(array);

But that doesn't seem to be happening when constructing the ostream_iterator.

Body:
This has nothing to do with array-to-pointer decay and everything to do with how name lookup works.

In this version:

for (const auto& subarr : arr) { std::cout << subarr << "\n"; }

your operator<< is a candidate because regular unqualified lookup will find it.

But that's not what ostream_iterator does, its implementation internally will do something like this:

template <typename T>
void whatever(std::ostream& os, T const& arg) {
    os << arg;
}

And that os << arg call is going to not find your operator<< candidate by unqualified lookup (it won't have been declared at the point of definition of the header) and it's not going to find your operator<< by argument-dependent lookup (since it's not in an associated namespace of either argument). Since your function isn't a candidate, instead the one selected is the pointer one - which is why it formats the way it does.

One (bad, don't do this) solution would be to put your operator<< overload inside of namespace std, which would cause argument-dependent lookup to be able to actually find it. But don't do this, since you're not allowed to add things to namespace std (and, generally speaking, shouldn't add your things to other people's namespaces).

So the better solution would be to instead create your own type that formats the way you want it to, since then you can just add an operator<< that properly associates with it - in a way that doesn't involve messing with std.


问:
How to access HIVE ACID tables using HANA SDA Virtual table?
We are currently using HANA 1 sps 12 and SPARK controller to create virtual tables and access the HIVE data in HANA. The problem is we have some SC2 table we want to archive in HANA for which we need full CRUD operation. We have converted a few of the Hive tables to ACID (transactional = true). Now we are not able to fetch records, it returns 0 records.

We tried to use Drill, which has native support for Hive acid tables, but when we are querying the Hive tables using Drill ODBC driver and DSN, it fails. After checking the queries that hit Drill we found out, HANA is wrapping the schema name in double-quotes. eg. Select * from "hive.schemaname".tablename.

We tried to change the default quoting to " from the default backtick, but ended up losing remote schema refresh as that query sends wrap the schema name with backtick `.

答: ACID table access is not possible using SDA, so we created a non-ACID table from the ACID table in Hive and accessed it back in the HANA DB. We are using ACID to perform all our necessary CRUD operations and then insert overwrite into a partitioned non-ACID table, this way only the partitions where an update/change happened will be recreated, rather than the whole table.</p>


问:
How to make TAG_ALPHA_IDENTIFIER empty not to ask user for a confirmation
My wallet applet requires to perform actions like PLAY TONE etc. But it requires a prompt "Yes or No?" from user. AFAIK, it is TAG_ALPHA_IDENTIFIER which is responsible for that. However, if I try this code below, it still asks user confirmation but now with "@" text. How to get rid of user confirmation at all?

Attempt 1. Failed with NullPtrException

```<code>proHdlr.appendTLV(ToolkitConstants.TAG_ALPHA_IDENTIFIER, null, (short)0, (short)0);
proHdlr.send();
</code>```

Attempt 2. Prompts '@@'

```<code>proHdlr.appendTLV(ToolkitConstants.TAG_ALPHA_IDENTIFIER, (byte)0, (byte)0);
proHdlr.send();
</code>```

Attempt 3. Prompts '@'

```<code>proHdlr.appendTLV(ToolkitConstants.TAG_ALPHA_IDENTIFIER, (byte)0);
proHdlr.send();
</code>```

Attempt 4. Prompts Default Text

```<code>byte[] ALPHA_MSG = {};
proHdlr.appendTLV(ToolkitConstants.TAG_ALPHA_IDENTIFIER, ALPHA_MSG, (short)0, (short)ALPHA_MSG.length);
proHdlr.send();
</code>```

According to ETSI 102.223, "8.2 Alpha identifier" section, it should be:

Description
Length

Alpha identifier tag
1

Length(X)
Y

Alpha identifier
X

And there is also "Default text" in documentation, however since "5.3.7 Text attributes" requires Alpha Identifier to be present, Default text should not bother, right?

In this document "6.4.5 PLAY TONE" section, page 45 it says:

if the alpha identifier is provided by the UICC and is a null data object (i.e. length = '00' and no value part), the terminal should not give any information to the user;

That's what I need. How should I do it Java with ProactiveHandler? All my Google searches end up with some text/menu title for Alpha Identifier.

How to get rid of user confirmation and perform the proactive action without it?

答:
a) Try to pass no data at all, i.e. leave out the proHdlr.appendTLV(ToolkitConstants.TAG_ALPHA_IDENTIFIER line.

b) The behavior might be phone-related or more specific modem-related. Check out a MediaTek based one, a Qualcomm based one and an iPhone and compare the results.

Body:
My wallet applet requires to perform actions like PLAY TONE etc. But it requires a prompt "Yes or No?" from user. AFAIK, it is TAG_ALPHA_IDENTIFIER which is responsible for that. However, if I try this code below, it still asks user confirmation but now with "@" text. How to get rid of user confirmation at all?

Attempt 1. Failed with NullPtrException

proHdlr.appendTLV(ToolkitConstants.TAG_ALPHA_IDENTIFIER, null, (short)0, (short)0);
proHdlr.send();

Attempt 2. Prompts '@@'

proHdlr.appendTLV(ToolkitConstants.TAG_ALPHA_IDENTIFIER, (byte)0, (byte)0);
proHdlr.send();

Attempt 3. Prompts '@'

proHdlr.appendTLV(ToolkitConstants.TAG_ALPHA_IDENTIFIER, (byte)0);
proHdlr.send();

Attempt 4. Prompts Default Text

byte[] ALPHA_MSG = {};
proHdlr.appendTLV(ToolkitConstants.TAG_ALPHA_IDENTIFIER, ALPHA_MSG, (short)0, (short)ALPHA_MSG.length);
proHdlr.send();

According to ETSI 102.223, "8.2 Alpha identifier" section, it should be:

Description
Length

Alpha identifier tag
1

Length(X)
Y

Alpha identifier
X

And there is also "Default text" in documentation, however since "5.3.7 Text attributes" requires Alpha Identifier to be present, Default text should not bother, right?

In this document "6.4.5 PLAY TONE" section, page 45 it says:

if the alpha identifier is provided by the UICC and is a null data object (i.e. length = '00' and no value part), the terminal should not give any information to the user;

That's what I need. How should I do it Java with ProactiveHandler? All my Google searches end up with some text/menu title for Alpha Identifier.

How to get rid of user confirmation and perform the proactive action without it?


问:
Are there themes for aspnet mvc3?
I'm searching for themes designed to be used with aspnet mvc3; i've found MvcContrib but download link is now empty. Can anyone help me in finding themes designed to run with the Razor engine?</p>

答: Try using an html5 boilerplate. There's a bunch of layouts u can use.</p>

Title: Are there themes for aspnet mvc3?


问:
Can I use std::next on user defined class
If I have a user-defined class :

```<code>class MyColl {
     int *data ;
     public :
     class Itr {
              int operator*() {}
              void operator++()
              bool operator != (const Itr &oth)
     } ;
     Itr begin() {}
     Itr end() {}
} ;
</code>```

Can I use std::next on objects of MyColl
If yes, then what needs to be done

答:
I figured out that my Itr class must define the following :

```<code>using difference_type = std::ptrdiff_t;
using iterator_category = std::forward_iterator_tag;
using value_type = int;
using pointer = value_type*;
using reference = value_type&;
</code>```

If I must support the std::prev function also then Itr must define prefix operator-- and iterator_category must be std::random_access_iterator_tag

Body:
If I have a user-defined class :

class MyColl {
     int *data ;
     public :
     class Itr {
              int operator*() {}
              void operator++()
              bool operator != (const Itr &oth)
     } ;
     Itr begin() {}
     Itr end() {}
} ;

Can I use std::next on objects of MyColl
If yes, then what needs to be done

Body:
I figured out that my Itr class must define the following :

using difference_type = std::ptrdiff_t;
using iterator_category = std::forward_iterator_tag;
using value_type = int;
using pointer = value_type*;
using reference = value_type&;

If I must support the std::prev function also then Itr must define prefix operator-- and iterator_category must be std::random_access_iterator_tag


问:
How to pass Automated Workflows from a Smartsheet Template to created Smartsheets using smartsheet-csharp-sdk?
So, when creating a new Smartsheet from a Template that has Automated Workflows there are some options that must be selected for the Smartsheet to inherit that automation.

(Example in Smartsheet)

The Smartsheet API has built in Inclusion Parameters (Rules and RuleRecipients) that can be passed into a request to serve the same function as what we see in the form above.

INCLUSION PARAMETERS AVAILABLE IN THE SMARTSHEET API

Parameters include (optional) -- comma-separated list of elements to copy from the template or sheet:

attachments

cellLinks

data

discussions

forms

rules

ruleRecipients

The smartsheet-csharp-sdk(v2.126.0) we are using to create the API calls has baked in Inclusion classes with preset parameters. Unfortunately, these Inclusion classes do not contain the Rules and RuleRecipients parameters.

INCLUSION PARAMETERS IN SDK (Relevant ones)

```<code>// Summary:
//     Represents specific elements that can be copied from a Template or Sheet into
//     a new Sheet.
public enum TemplateInclusion
{
    //
    // Summary:
    //     Includes the data.
    DATA = 0,
    //
    // Summary:
    //     Includes the attachments.
    ATTACHMENTS = 1,
    //
    // Summary:
    //     Includes the discussions.
    DISCUSSIONS = 2,
    //
    // Summary:
    //     Includes the cell links.
    CELL_LINKS = 3,
    //
    // Summary:
    //     Includes the forms.
    FORMS = 4
}
</code>```

```<code>// Summary:
//     Represents specific elements to include in a response.
public enum SheetLevelInclusion
{
    //
    // Summary:
    //     Includes sheet-level and row-level attachments.
    ATTACHMENTS = 0,
    //
    // Summary:
    //     Includes columnType attribute in the row’s cells indicating the type of the column
    //     the cell resides in.
    COLUMN_TYPE = 1,
    //
    // Summary:
    //     contact references
    CONTACT_REFERENCES = 2,
    //
    // Summary:
    //     cross sheet references
    CROSS_SHEET_REFERENCES = 3,
    //
    // Summary:
    //     Includes sheet-level and row-level discussions.
    DISCUSSIONS = 4,
    //
    // Summary:
    //     Includes column filters and row.filteredOut attribute.
    FILTERS = 5,
    //
    // Summary:
    //     Includes column filter definitions
    FILTER_DEFINITIONS = 6,
    //
    // Summary:
    //     Includes column, row, and cell formatting.
    FORMAT = 7,
    //
    // Summary:
    //     object representation of cell value
    OBJECT_VALUE = 8,
    //
    // Summary:
    //     Includes the owner’s email address and user Id for each sheet.
    OWNER_INFO = 9,
    //
    // Summary:
    //     Includes a permalink attribute for each row. A row permalink represents a direct
    //     link to the row in the Smartsheet application.
    ROW_PERMALINK = 10,
    //
    // Summary:
    //     (DEPRECATED: use WRITER_INFO) Includes createdBy and modifiedBy attributes on
    //     the row, indicating the row’s creator and last modifier.
    ROW_WRITER_INFO = 11,
    //
    // Summary:
    //     Includes the source object indicating which sheet or template the sheet was created
    //     from, if any.
    SOURCE = 12,
    //
    // Summary:
    //     Includes SheetSummary object.
    SUMMARY = 13,
    //
    // Summary:
    //     Includes createdBy and modifiedBy attributes on the row or summary fields, indicating
    //     the row or summary field's creator, and last modifier.
    WRITER_INFO = 14
}
</code>```

The CreateSheetFromTemplate method that we are using from the SDK does have an "includes" parameter but it only accepts an IEnumerable of the pre-built TemplateInclusion.

```<code>Sheet CreateSheetFromTemplate(long workspaceId, Sheet sheet, IEnumerable<TemplateInclusion> includes);
</code>```

I am not sure how to bypass this to add the Rules and RuleRecipients parameters in a way that would work with the SDK. Is it possible to create a Smartsheet that will inherit the Automated Workflows from a Template using the SDK? Or should I just bypass it altogether and create a traditional API call?

答:
I checked the source code of the package (https://github.com/smartsheet-platform/smartsheet-csharp-sdk) and the TemplateInclusion never included once rules or ruleRecipients.
I tried to force the call using rest api and rules are supported, but i doubt that rulesRecipents are...

```<code>url : https://api.smartsheet.com/2.0/sheets?include=rules,rulesrecipients,recipients
body : {"name":"newsheetFromTemplate", "fromId": 9999999999}
</code>```

To conclude i would advise:

Create a feature enhancement request

Report the issue on github

Not to use templates but sheet copy (where rules are supported)

Body:
So, when creating a new Smartsheet from a Template that has Automated Workflows there are some options that must be selected for the Smartsheet to inherit that automation.

(Example in Smartsheet)

The Smartsheet API has built in Inclusion Parameters (Rules and RuleRecipients) that can be passed into a request to serve the same function as what we see in the form above.

INCLUSION PARAMETERS AVAILABLE IN THE SMARTSHEET API

Parameters include (optional) -- comma-separated list of elements to copy from the template or sheet:

attachments

cellLinks

data

discussions

forms

rules

ruleRecipients

The smartsheet-csharp-sdk(v2.126.0) we are using to create the API calls has baked in Inclusion classes with preset parameters. Unfortunately, these Inclusion classes do not contain the Rules and RuleRecipients parameters.

INCLUSION PARAMETERS IN SDK (Relevant ones)

// Summary:
//     Represents specific elements that can be copied from a Template or Sheet into
//     a new Sheet.
public enum TemplateInclusion
{
    //
    // Summary:
    //     Includes the data.
    DATA = 0,
    //
    // Summary:
    //     Includes the attachments.
    ATTACHMENTS = 1,
    //
    // Summary:
    //     Includes the discussions.
    DISCUSSIONS = 2,
    //
    // Summary:
    //     Includes the cell links.
    CELL_LINKS = 3,
    //
    // Summary:
    //     Includes the forms.
    FORMS = 4
}

// Summary:
//     Represents specific elements to include in a response.
public enum SheetLevelInclusion
{
    //
    // Summary:
    //     Includes sheet-level and row-level attachments.
    ATTACHMENTS = 0,
    //
    // Summary:
    //     Includes columnType attribute in the row’s cells indicating the type of the column
    //     the cell resides in.
    COLUMN_TYPE = 1,
    //
    // Summary:
    //     contact references
    CONTACT_REFERENCES = 2,
    //
    // Summary:
    //     cross sheet references
    CROSS_SHEET_REFERENCES = 3,
    //
    // Summary:
    //     Includes sheet-level and row-level discussions.
    DISCUSSIONS = 4,
    //
    // Summary:
    //     Includes column filters and row.filteredOut attribute.
    FILTERS = 5,
    //
    // Summary:
    //     Includes column filter definitions
    FILTER_DEFINITIONS = 6,
    //
    // Summary:
    //     Includes column, row, and cell formatting.
    FORMAT = 7,
    //
    // Summary:
    //     object representation of cell value
    OBJECT_VALUE = 8,
    //
    // Summary:
    //     Includes the owner’s email address and user Id for each sheet.
    OWNER_INFO = 9,
    //
    // Summary:
    //     Includes a permalink attribute for each row. A row permalink represents a direct
    //     link to the row in the Smartsheet application.
    ROW_PERMALINK = 10,
    //
    // Summary:
    //     (DEPRECATED: use WRITER_INFO) Includes createdBy and modifiedBy attributes on
    //     the row, indicating the row’s creator and last modifier.
    ROW_WRITER_INFO = 11,
    //
    // Summary:
    //     Includes the source object indicating which sheet or template the sheet was created
    //     from, if any.
    SOURCE = 12,
    //
    // Summary:
    //     Includes SheetSummary object.
    SUMMARY = 13,
    //
    // Summary:
    //     Includes createdBy and modifiedBy attributes on the row or summary fields, indicating
    //     the row or summary field's creator, and last modifier.
    WRITER_INFO = 14
}

The CreateSheetFromTemplate method that we are using from the SDK does have an "includes" parameter but it only accepts an IEnumerable of the pre-built TemplateInclusion.

Sheet CreateSheetFromTemplate(long workspaceId, Sheet sheet, IEnumerable<TemplateInclusion> includes);

I am not sure how to bypass this to add the Rules and RuleRecipients parameters in a way that would work with the SDK. Is it possible to create a Smartsheet that will inherit the Automated Workflows from a Template using the SDK? Or should I just bypass it altogether and create a traditional API call?

Body:
I checked the source code of the package (https://github.com/smartsheet-platform/smartsheet-csharp-sdk) and the TemplateInclusion never included once rules or ruleRecipients.
I tried to force the call using rest api and rules are supported, but i doubt that rulesRecipents are...

url : https://api.smartsheet.com/2.0/sheets?include=rules,rulesrecipients,recipients
body : {"name":"newsheetFromTemplate", "fromId": 9999999999}

To conclude i would advise:

Create a feature enhancement request

Report the issue on github

Not to use templates but sheet copy (where rules are supported)


问:
Fastest Way to count all-TRUE rows of a LogicalMatrix R / C++ / Rcpp

I need to count the number of rows in a LogicalMatrix that are all TRUE.

Because I need to be able to do this 1 - 2500 million times on a relatively regular basis speed actually really matters:

My current best:

The most efficient / fastest single-process way I've figured how to do this is in the how many Rcpp function (hm2).

My limited profiling abilities show me that the vast majority of the time is spent in doing the if(r_tll == xcolls){.... I can't seem to think of a different algorithm that would be faster ( I have tried the break out of the loop as soon as a FALSE is found and it is much slower).

details that can be assumed:

I can assume that:

The matrix will always have fewer than 10 million rows.

All the output matrices from upstream will have the same number of cols (for a given session/process/thread).

There will never be more than 2326 cols per matrix.

minimal example:

m <- matrix(sample(c(T,F),50000*10, replace = T),ncol = 10L)
head(m)
#>       [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  [,8]  [,9] [,10]
#> [1,] FALSE FALSE  TRUE FALSE FALSE  TRUE  TRUE  TRUE  TRUE FALSE
#> [2,] FALSE FALSE FALSE  TRUE FALSE  TRUE FALSE FALSE FALSE  TRUE
#> [3,] FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE  TRUE
#> [4,]  TRUE  TRUE FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE  TRUE
#> [5,]  TRUE FALSE FALSE FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE
#> [6,] FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE
```

<pre class="lang-c++ prettyprint-override"><code>  // [[Rcpp::export]]
int hm(const LogicalMatrix& x){
  const int xrows = x.nrow();
  const int xcols = x.ncol();
  int n_all_true = 0;

  for(size_t row = 0; row < xrows; row++) {
    int r_ttl = 0;
    for(size_t col = 0; col < xcols; col++) {
      r_ttl += x(row,col);
    }
    if(r_ttl == xcols){
      n_all_true++;
    }
  }
  return n_all_true;
}
</code>```

I don't understand why, but on my machine if I bake in the number of cols it is faster (if someone could explain why this is it would be great too):

```<code>// [[Rcpp::export]]
int hm2(const LogicalMatrix& x){
  const int xrows = x.nrow();
  // const int xcols = x.ncol();
  int n_all_true = 0;

  for(size_t row = 0; row < xrows; row++) {
    int r_ttl = 0;
    for(size_t col = 0; col < 10; col++) {
      r_ttl += x(row,col);
    }
    if(r_ttl == 10){
      n_all_true += 1;
    }
  }
  return n_all_true;
}
</code>```

timing:

```<code>microbenchmark(hm(m), hm2(m), times = 1000)
#>  Unit: microseconds
#>   expr     min       lq     mean  median       uq      max neval
#>  hm(m) 597.828 599.0995 683.3482 605.397 643.8655 1659.711  1000
#> hm2(m) 236.847 237.6565 267.8787 238.748 253.5280  683.221  1000
</code>```

答:
Stumbled across this working on a similar problem. We can squeeze a little more performance by initializing r_ttl on the first column and eliminating the if(r_ttl == xcols) check:

```<code># initialize on the first column
cppFunction('int hm2(const LogicalMatrix& x)
{
  const int xrows = x.nrow();
  const int xcols = x.ncol();
  int n_all_true = 0;

  for(int row = 0; row < xrows; row++) {
    int r_ttl = x(row,0);
    for(int col = 1; col < xcols; col++) {
      r_ttl += x(row,col);
    }
    if(r_ttl == xcols){
      n_all_true++;
    }
  }
  return n_all_true;
}')

# use *= to eliminate the if statement
cppFunction('int hm3(const LogicalMatrix& x)
{
  const int xrows = x.nrow();
  const int xcols = x.ncol();
  int n_all_true = 0;

  for(int row = 0; row < xrows; row++) {
    int r_ttl = 1;
    for(int col = 0; col < xcols; col++) {
      r_ttl *= x(row,col);
    }
    n_all_true += r_ttl;
  }
  return n_all_true;
}')

# both modifications
cppFunction('int hm4(const LogicalMatrix& x) {
  const int xrows = x.nrow();
  const int xcols = x.ncol();
  int n_all_true = 0;

  for(int row = 0; row < xrows; row++) {
    int r_ttl = x(row,0);
    for(int col = 1; col < xcols; col++) {
      r_ttl *= x(row,col);
    }
    n_all_true += r_ttl;
  }
  return n_all_true;
}')

m <- matrix(sample(c(T,F),50000*10, replace = T),ncol = 10L)

microbenchmark::microbenchmark(hm_jmu = hm_jmu(m),
                               hm2 = hm2(m),
                               hm3 = hm3(m),
                               hm4 = hm4(m),
                               check = "equal",
                               times = 1e4)

# Unit: microseconds
#   expr   min    lq     mean median    uq    max neval
# hm_jmu 198.3 200.8 218.5362  208.3 212.7 5855.9 10000
#    hm2 169.3 170.9 184.8722  171.4 180.0 5775.4 10000
#    hm3 192.7 196.1 209.7465  196.8 206.3 1056.2 10000
#    hm4 161.9 163.1 176.2370  163.5 171.9 1119.2 10000
</code>```

About a 20% improvement over Joshua Ulrich's even larger improvement.

Body:
I need to count the number of rows in a LogicalMatrix that are all TRUE.

Because I need to be able to do this 1 - 2500 million times on a relatively regular basis speed actually really matters:

My current best:

The most efficient / fastest single-process way I've figured how to do this is in the how many Rcpp function (hm2).

My limited profiling abilities show me that the vast majority of the time is spent in doing the if(r_tll == xcolls){.... I can't seem to think of a different algorithm that would be faster ( I have tried the break out of the loop as soon as a FALSE is found and it is much slower).

details that can be assumed:

I can assume that:

The matrix will always have fewer than 10 million rows.

All the output matrices from upstream will have the same number of cols (for a given session/process/thread).

There will never be more than 2326 cols per matrix.

minimal example:

m <- matrix(sample(c(T,F),50000*10, replace = T),ncol = 10L)
head(m)
#>       [,1]  [,2]  [,3]  [,4]  [,5]  [,6]  [,7]  [,8]  [,9] [,10]
#> [1,] FALSE FALSE  TRUE FALSE FALSE  TRUE  TRUE  TRUE  TRUE FALSE
#> [2,] FALSE FALSE FALSE  TRUE FALSE  TRUE FALSE FALSE FALSE  TRUE
#> [3,] FALSE  TRUE FALSE FALSE  TRUE FALSE FALSE FALSE FALSE  TRUE
#> [4,]  TRUE  TRUE FALSE  TRUE  TRUE  TRUE FALSE FALSE FALSE  TRUE
#> [5,]  TRUE FALSE FALSE FALSE  TRUE  TRUE  TRUE FALSE  TRUE  TRUE
#> [6,] FALSE FALSE FALSE  TRUE  TRUE  TRUE  TRUE  TRUE  TRUE FALSE

  // [[Rcpp::export]]
int hm(const LogicalMatrix& x){
  const int xrows = x.nrow();
  const int xcols = x.ncol();
  int n_all_true = 0;

  for(size_t row = 0; row < xrows; row++) {
    int r_ttl = 0;
    for(size_t col = 0; col < xcols; col++) {
      r_ttl += x(row,col);
    }
    if(r_ttl == xcols){
      n_all_true++;
    }
  }
  return n_all_true;
}

I don't understand why, but on my machine if I bake in the number of cols it is faster (if someone could explain why this is it would be great too):

// [[Rcpp::export]]
int hm2(const LogicalMatrix& x){
  const int xrows = x.nrow();
  // const int xcols = x.ncol();
  int n_all_true = 0;

  for(size_t row = 0; row < xrows; row++) {
    int r_ttl = 0;
    for(size_t col = 0; col < 10; col++) {
      r_ttl += x(row,col);
    }
    if(r_ttl == 10){
      n_all_true += 1;
    }
  }
  return n_all_true;
}

timing:

microbenchmark(hm(m), hm2(m), times = 1000)
#>  Unit: microseconds
#>   expr     min       lq     mean  median       uq      max neval
#>  hm(m) 597.828 599.0995 683.3482 605.397 643.8655 1659.711  1000
#> hm2(m) 236.847 237.6565 267.8787 238.748 253.5280  683.221  1000

Body:
Stumbled across this working on a similar problem. We can squeeze a little more performance by initializing r_ttl on the first column and eliminating the if(r_ttl == xcols) check:

# initialize on the first column
cppFunction('int hm2(const LogicalMatrix& x)
{
  const int xrows = x.nrow();
  const int xcols = x.ncol();
  int n_all_true = 0;

  for(int row = 0; row < xrows; row++) {
    int r_ttl = x(row,0);
    for(int col = 1; col < xcols; col++) {
      r_ttl += x(row,col);
    }
    if(r_ttl == xcols){
      n_all_true++;
    }
  }
  return n_all_true;
}')

# use *= to eliminate the if statement
cppFunction('int hm3(const LogicalMatrix& x)
{
  const int xrows = x.nrow();
  const int xcols = x.ncol();
  int n_all_true = 0;

  for(int row = 0; row < xrows; row++) {
    int r_ttl = 1;
    for(int col = 0; col < xcols; col++) {
      r_ttl *= x(row,col);
    }
    n_all_true += r_ttl;
  }
  return n_all_true;
}')

# both modifications
cppFunction('int hm4(const LogicalMatrix& x) {
  const int xrows = x.nrow();
  const int xcols = x.ncol();
  int n_all_true = 0;

  for(int row = 0; row < xrows; row++) {
    int r_ttl = x(row,0);
    for(int col = 1; col < xcols; col++) {
      r_ttl *= x(row,col);
    }
    n_all_true += r_ttl;
  }
  return n_all_true;
}')

m <- matrix(sample(c(T,F),50000*10, replace = T),ncol = 10L)

microbenchmark::microbenchmark(hm_jmu = hm_jmu(m),
                               hm2 = hm2(m),
                               hm3 = hm3(m),
                               hm4 = hm4(m),
                               check = "equal",
                               times = 1e4)

# Unit: microseconds
#   expr   min    lq     mean median    uq    max neval
# hm_jmu 198.3 200.8 218.5362  208.3 212.7 5855.9 10000
#    hm2 169.3 170.9 184.8722  171.4 180.0 5775.4 10000
#    hm3 192.7 196.1 209.7465  196.8 206.3 1056.2 10000
#    hm4 161.9 163.1 176.2370  163.5 171.9 1119.2 10000

About a 20% improvement over Joshua Ulrich's even larger improvement.


问:
ansible ansible_default_ipv4 set wrong interface
I am trying to configure a host and automatically select the relevant interface.

For that I am trying to run the Ansible task:

- name: Set the list of interfaces to be configured
  network_interfaces_to_configure: "{{ ansible_interfaces | difference([ ansible_default_ipv4.alias, 'lo', 'docker0' ]) }}"
```

For some reason it stores in network_interfaces_to_configure an interface that is deactivated — it sets it to enp1s0f1 and it should be set to enp1s0f0

The host have the following interfaces:

lo

docker0  (virtual)

enp1s0f0 (hardware connected and enabled)

enp1s0f1 (hardware disabled and without any physical connection)

I also validated that the default gateway is set to enp1s0f0.

答:
The reason why you end up with the wrong interface there is because you are excluding the correct one in your difference filter.

difference([ ansible_default_ipv4.alias, 'lo', 'docker0' ])
##               ^--- it is excluded because of this addition
##                    of `ansible_default_ipv4.alias` in the list
```
<p>Now, as you stated that <code>enp1s0f1</code> should be excluded because it is an inactive interface, then you will have to dig further in the properties of those interfaces.</p>
<p>In order to do this, you have to know that the list inside <code>ansible_interfaces</code>, corresponds to <code>ansible_*</code> facts that list more information for those interfaces.</p>
<p>For example, in your case, you will have those facts:</p>
<ul>
<li><code>ansible_lo</code></li>
<li><code>ansible_docker0</code></li>
<li><code>ansible_enp1s0f0</code></li>
<li><code>ansible_enp1s0f1</code></li>
</ul>
<p>With information like:</p>
<pre class="lang-yaml prettyprint-override"><code>ansible_lo:
  active: true
  device: lo
  ipv4:
    address: 127.0.0.1
    broadcast: ''
    netmask: 255.0.0.0
    network: 127.0.0.0
  mtu: 65536
  promisc: false
  type: loopback
</code>```

So, maybe, a better idea would be to create a fact and exclude interfaces based on their active and type properties.

Something like:

- set_fact:
    active_interfaces: "{{ active_interfaces | default([]) + [item] }}"
  loop: "{{ ansible_interfaces }}"
  when:
    ## only include active interfaces
    - lookup('vars', 'ansible_' ~ item).active
    ## exclude local loopback interfaces (`lo`)
    - lookup('vars', 'ansible_' ~ item).type != 'loopback'
    ## exclude bridge interfaces (`dockerO`)
    - lookup('vars', 'ansible_' ~ item).type != 'bridge'
```
<p>Then, use that variable in <code>network_interfaces_to_configure</code>:</p>
<pre class="lang-yaml prettyprint-override"><code>- network_interfaces_to_configure: "{{ active_interfaces }}"
</code>```

Here would be an example of what this gives on my own setup, given the playbook:

- hosts: localhost
  gather_facts: yes

  tasks:
    - set_fact:
        active_interfaces: "{{ active_interfaces | default([]) + [item] }}"
      loop: "{{ ansible_interfaces }}"
      when:
        - lookup('vars', 'ansible_' ~ item).active
        - lookup('vars', 'ansible_' ~ item).type != 'loopback'
        - lookup('vars', 'ansible_' ~ item).type != 'bridge'

    - debug:
        var: active_interfaces
```
<p>This yields:</p>
<pre class="lang-none prettyprint-override"><code>TASK [Gathering Facts] *********************************************************
ok: [localhost]

TASK [set_fact] ****************************************************************
ok: [localhost] => (item=eth0)
skipping: [localhost] => (item=tunl0)
skipping: [localhost] => (item=docker0)
skipping: [localhost] => (item=lo)
ok: [localhost] => (item=services1)
skipping: [localhost] => (item=ip6tnl0)

TASK [debug] *******************************************************************
ok: [localhost] =>
  active_interfaces:
  - eth0
  - services1
</code>```

Body:
I am trying to configure a host and automatically select the relevant interface.

For that I am trying to run the Ansible task:

- name: Set the list of interfaces to be configured
  network_interfaces_to_configure: "{{ ansible_interfaces | difference([ ansible_default_ipv4.alias, 'lo', 'docker0' ]) }}"

For some reason it stores in network_interfaces_to_configure an interface that is deactivated — it sets it to enp1s0f1 and it should be set to enp1s0f0

The host have the following interfaces:

lo

docker0  (virtual)

enp1s0f0 (hardware connected and enabled)

enp1s0f1 (hardware disabled and without any physical connection)

I also validated that the default gateway is set to enp1s0f0.

Body:
The reason why you end up with the wrong interface there is because you are excluding the correct one in your difference filter.

difference([ ansible_default_ipv4.alias, 'lo', 'docker0' ])
##               ^--- it is excluded because of this addition
##                    of `ansible_default_ipv4.alias` in the list

Now, as you stated that enp1s0f1 should be excluded because it is an inactive interface, then you will have to dig further in the properties of those interfaces.

In order to do this, you have to know that the list inside ansible_interfaces, corresponds to ansible_* facts that list more information for those interfaces.

For example, in your case, you will have those facts:

ansible_lo

ansible_docker0

ansible_enp1s0f0

ansible_enp1s0f1

With information like:

ansible_lo:
  active: true
  device: lo
  ipv4:
    address: 127.0.0.1
    broadcast: ''
    netmask: 255.0.0.0
    network: 127.0.0.0
  mtu: 65536
  promisc: false
  type: loopback

So, maybe, a better idea would be to create a fact and exclude interfaces based on their active and type properties.

Something like:

- set_fact:
    active_interfaces: "{{ active_interfaces | default([]) + [item] }}"
  loop: "{{ ansible_interfaces }}"
  when:
    ## only include active interfaces
    - lookup('vars', 'ansible_' ~ item).active
    ## exclude local loopback interfaces (`lo`)
    - lookup('vars', 'ansible_' ~ item).type != 'loopback'
    ## exclude bridge interfaces (`dockerO`)
    - lookup('vars', 'ansible_' ~ item).type != 'bridge'

Then, use that variable in network_interfaces_to_configure:

- network_interfaces_to_configure: "{{ active_interfaces }}"

Here would be an example of what this gives on my own setup, given the playbook:

- hosts: localhost
  gather_facts: yes

  tasks:
    - set_fact:
        active_interfaces: "{{ active_interfaces | default([]) + [item] }}"
      loop: "{{ ansible_interfaces }}"
      when:
        - lookup('vars', 'ansible_' ~ item).active
        - lookup('vars', 'ansible_' ~ item).type != 'loopback'
        - lookup('vars', 'ansible_' ~ item).type != 'bridge'

    - debug:
        var: active_interfaces

This yields:

TASK [Gathering Facts] *********************************************************
ok: [localhost]

TASK [set_fact] ****************************************************************
ok: [localhost] => (item=eth0)
skipping: [localhost] => (item=tunl0)
skipping: [localhost] => (item=docker0)
skipping: [localhost] => (item=lo)
ok: [localhost] => (item=services1)
skipping: [localhost] => (item=ip6tnl0)

TASK [debug] *******************************************************************
ok: [localhost] =>
  active_interfaces:
  - eth0
  - services1


问:
ReactJS: how using queryselector variable out a function
I'm using this code:

export default function Naviguation() {

```<code>const overBtnMenu = () => {
    const navBars = document.querySelectorAll('.nav-bars')
    for (let i = 0; i < navBars.length; i++) {
        navBars[i].style.width = '40px'
    }
}

const outBtnMenu = () => {
    const navBars = document.querySelectorAll('.nav-bars')
    navBars[0].style.width = '20px'
    navBars[1].style.width = '30px'
    navBars[2].style.width = '20px'
}

return (
    <nav>
        <img src={img} className='nav-logo' alt="logo" />
        <div className='nav-btn-menu' onMouseEnter={overBtnMenu} onMouseLeave={outBtnMenu}>
            <span className='nav-barTop nav-bars'></span>
            <span className='nav-barMiddle nav-bars'></span>
            <span className='nav-barBottom nav-bars'></span>
        </div>
    </nav>
)
</code>```

}

the code runs correctly but I want to use the variable "navBars" once time like this

export default function Naviguation() {

```<code>const navBars = document.querySelectorAll('.nav-bars')

const overBtnMenu = () => {
    for (let i = 0; i < navBars.length; i++) {
        navBars[i].style.width = '40px'
    }
}

const outBtnMenu = () => {
    navBars[0].style.width = '20px'
    navBars[1].style.width = '30px'
    navBars[2].style.width = '20px'
}

return (
    <nav>
        <img src={img} className='nav-logo' alt="logo" />
        <div className='nav-btn-menu' onMouseEnter={overBtnMenu} onMouseLeave={outBtnMenu}>
            <span className='nav-barTop nav-bars'></span>
            <span className='nav-barMiddle nav-bars'></span>
            <span className='nav-barBottom nav-bars'></span>
        </div>
    </nav>
)
</code>```

}

But the code doesn't run because it wrote on the console "navBars undefined..."

How using a variable out the function to using it into my function?

答:
In React you have the concept of useRef whenever you need to get the value of an actual DOM element.

Rewrite your component as below:

import { useEffect, useRef } from 'react';

export default function Navigation() {
  const navBarsRef = useRef(null);
  const navBars = navBarsRef.current;

  useEffect(() => {
    navBarsRef.current = document.querySelectorAll('.nav-bars');
  }, []);

  const overBtnMenu = () => {
    for (let i = 0; i < navBars.length; i++) {
      navBars[i].style.width = '40px';
    }
  };

  const outBtnMenu = () => {
    navBars[0].style.width = '20px';
    navBars[1].style.width = '30px';
    navBars[2].style.width = '20px';
  };

  return (

  );
}

```

Body:
I'm using this code:

export default function Naviguation() {

const overBtnMenu = () => {
    const navBars = document.querySelectorAll('.nav-bars')
    for (let i = 0; i < navBars.length; i++) {
        navBars[i].style.width = '40px'
    }
}

const outBtnMenu = () => {
    const navBars = document.querySelectorAll('.nav-bars')
    navBars[0].style.width = '20px'
    navBars[1].style.width = '30px'
    navBars[2].style.width = '20px'
}

return (

)

}

the code runs correctly but I want to use the variable "navBars" once time like this

export default function Naviguation() {

const navBars = document.querySelectorAll('.nav-bars')

const overBtnMenu = () => {
    for (let i = 0; i < navBars.length; i++) {
        navBars[i].style.width = '40px'
    }
}

const outBtnMenu = () => {
    navBars[0].style.width = '20px'
    navBars[1].style.width = '30px'
    navBars[2].style.width = '20px'
}

return (

)

}

But the code doesn't run because it wrote on the console "navBars undefined..."

How using a variable out the function to using it into my function?

Body:
In React you have the concept of useRef whenever you need to get the value of an actual DOM element.

Rewrite your component as below:

import { useEffect, useRef } from 'react';

export default function Navigation() {
  const navBarsRef = useRef(null);
  const navBars = navBarsRef.current;

  useEffect(() => {
    navBarsRef.current = document.querySelectorAll('.nav-bars');
  }, []);

  const overBtnMenu = () => {
    for (let i = 0; i < navBars.length; i++) {
      navBars[i].style.width = '40px';
    }
  };

  const outBtnMenu = () => {
    navBars[0].style.width = '20px';
    navBars[1].style.width = '30px';
    navBars[2].style.width = '20px';
  };

  return (
    <nav>
      <img src={img} className="nav-logo" alt="logo" />
      <div className="nav-btn-menu" onMouseEnter={overBtnMenu} onMouseLeave={outBtnMenu}>
        <span className="nav-barTop nav-bars"></span>
        <span className="nav-barMiddle nav-bars"></span>
        <span className="nav-barBottom nav-bars"></span>
      </div>
    </nav>
  );
}


问:
iAds ADBanner disappear when back button is clicked
i have a navigation controller with a depth of 3 viewcontrollers. root, one, two
i want to add an ADBannerview and I followed the iAdsSuite sample code from apple.
i added to all of my viewcontrollers.
the adbanner loads at first then it is fine if i navigate to one and two.
but if i click back button from two and one, the banner is not loading anymore.
it is working root --> one --> two but it's not working two --> one --> root.
anyone encounter this problem?</p>

答: I endup implementing ADBannerView in appDelegate. Use custom delegate method to resize the UITableview of one and two. Don't know it is the right way to do... </p>


问:
How can I restrict pages to guest users using React-Router?
I'm using Firebase v9 and react-router v6. I haven't used v6 so this was quite confusing. How can I make it where the guest user can only access the login page. Only users who were logged in can access the homepage and other pages.

Everytime I'll reload any page, it will show this in the console but it will still direct the user to the right page :

No routes matched location "/location of the page"

How can I use a private route for the profile page?

```<code>//custom hook
export function useAuth() {
  const [currentUser, setCurrentUser] = useState();

  useEffect(() => {
    const unsub = onAuthStateChanged(auth, (user) => setCurrentUser(user));
    return unsub;
  }, []);

  return currentUser;
}
</code>```

App.js

```<code> import { auth, useAuth } from "./Firebase/utils";
    import { onAuthStateChanged } from "firebase/auth";

  function App() {
  const currentUser = useAuth();
  const user = auth.currentUser;
  const navigate = useNavigate();

  console.log(currentUser?.email);

  useEffect(() => {
    onAuthStateChanged(auth, (user) => {
      if (user) {
        // User is signed in, see docs for a list of available properties
        // https://firebase.google.com/docs/reference/js/firebase.User
        const uid = user.uid;
        console.log(uid);
        navigate("/Home");
        // ...
      } else {
        // User is signed out
        // ...
        navigate("/");
      }
    });
  }, []);

  return (
    <div>
      <div>
        <Routes>

          {currentUser ? (
            <>
             //If i do it this way and I'll go the profile page and reload it, it will always go to back to the Homepage.
              <Route path="/Home" element={<Home />} />
              <Route path="/Profile" element={<ProfilePage />} />
            </>
          ) : (
            <>
              <Route
                path="/"
                element={
                    <LogInPage />
                }
              />
            </>
          )}

        </Routes>
      </div>
    </div>
  );
}

export default App;
</code>```

This is what the console.log(user) shows:

Package.json file:

答:
Issues

The main issue is that the currentUser value is initially falsey

```<code>const [currentUser, setCurrentUser] = useState();
</code>```

and you are making a navigation decision on unconfirmed authentication status in App

```<code><Routes>
  {currentUser ? (
    <>
      // If i do it this way and I'll go the profile page and reload it,
      // it will always go to back to the Homepage.
      <Route path="/Home" element={<Home />} />
      <Route path="/Profile" element={<ProfilePage />} />
    </>
  ) : (
    <>
      <Route
        path="/"
        element={<LogInPage />}
      />
    </>
  )}
</Routes>
</code>```

When refreshing the page the currentUser state is reset, is undefined, i.e. falsey, and only the "/" path is rendered.

Solution

In react-router-dom is a common practice to abstract route protection into a specialized "protected route" component. You will also want to conditionally handle the indeterminant state until your Firebase auth check has had a chance to confirm an authentication status and update the currentUser state.

Example:

```<code>export function useAuth() {
  const [currentUser, setCurrentUser] = useState(); // <-- initially undefined

  useEffect(() => {
    const unsub = onAuthStateChanged(auth, (user) => setCurrentUser(user)); // <-- null or user object
    return unsub;
  }, []);

  return { currentUser };
}
</code>```

AuthWrapper - Uses the useAuth hook to check the authentication status of user. If currentUser is undefined it conditionally returns early null or some other loading indicator. Once the currentUser state is populated/defined the component conditionally renders either an Outlet for nested/wrapped Route components you want to protect, or the Navigate component to redirect to your auth route.

```<code>import { Navigate, Outlet, useLocation } from 'react-router-dom';

const AuthWrapper = () => {
  const location = useLocation();
  const { currentUser } = useAuth();

  if (currentUser === undefined) return null; // <-- or loading spinner, etc...

  return currentUser
    ? <Outlet />
    : <Navigate to="/" replace state={{ from: location }} />;
};
</code>```

App - Unconditionally renders all routes, wrapping the Home and Profile routes in the AuthWrapper layout route.

```<code>function App() {
  return (
    <div>
      <div>
        <Routes>
          <Route element={<AuthWrapper />}>
            <Route path="/Home" element={<Home />} />
            <Route path="/Profile" element={<ProfilePage />} />
          </Route>
          <Route path="/" element={<LogInPage />} />
        </Routes>
      </div>
    </div>
  );
}
</code>```

Body:
I'm using Firebase v9 and react-router v6. I haven't used v6 so this was quite confusing. How can I make it where the guest user can only access the login page. Only users who were logged in can access the homepage and other pages.

Everytime I'll reload any page, it will show this in the console but it will still direct the user to the right page :

No routes matched location "/location of the page"

How can I use a private route for the profile page?

//custom hook
export function useAuth() {
  const [currentUser, setCurrentUser] = useState();

  useEffect(() => {
    const unsub = onAuthStateChanged(auth, (user) => setCurrentUser(user));
    return unsub;
  }, []);

  return currentUser;
}

App.js

 import { auth, useAuth } from "./Firebase/utils";
    import { onAuthStateChanged } from "firebase/auth";

  function App() {
  const currentUser = useAuth();
  const user = auth.currentUser;
  const navigate = useNavigate();

  console.log(currentUser?.email);

  useEffect(() => {
    onAuthStateChanged(auth, (user) => {
      if (user) {
        // User is signed in, see docs for a list of available properties
        // https://firebase.google.com/docs/reference/js/firebase.User
        const uid = user.uid;
        console.log(uid);
        navigate("/Home");
        // ...
      } else {
        // User is signed out
        // ...
        navigate("/");
      }
    });
  }, []);

  return (

        <Routes>

          {currentUser ? (
            <>
             //If i do it this way and I'll go the profile page and reload it, it will always go to back to the Homepage.
              <Route path="/Home" element={<Home />} />
              <Route path="/Profile" element={<ProfilePage />} />
            </>
          ) : (
            <>
              <Route
                path="/"
                element={
                    <LogInPage />
                }
              />
            </>
          )}

        </Routes>

  );
}

export default App;

This is what the console.log(user) shows:

Package.json file:

Body:
Issues

The main issue is that the currentUser value is initially falsey

const [currentUser, setCurrentUser] = useState();

and you are making a navigation decision on unconfirmed authentication status in App

<Routes>
  {currentUser ? (
    <>
      // If i do it this way and I'll go the profile page and reload it,
      // it will always go to back to the Homepage.
      <Route path="/Home" element={<Home />} />
      <Route path="/Profile" element={<ProfilePage />} />
    </>
  ) : (
    <>
      <Route
        path="/"
        element={<LogInPage />}
      />
    </>
  )}
</Routes>

When refreshing the page the currentUser state is reset, is undefined, i.e. falsey, and only the "/" path is rendered.

Solution

In react-router-dom is a common practice to abstract route protection into a specialized "protected route" component. You will also want to conditionally handle the indeterminant state until your Firebase auth check has had a chance to confirm an authentication status and update the currentUser state.

Example:

export function useAuth() {
  const [currentUser, setCurrentUser] = useState(); // <-- initially undefined

  useEffect(() => {
    const unsub = onAuthStateChanged(auth, (user) => setCurrentUser(user)); // <-- null or user object
    return unsub;
  }, []);

  return { currentUser };
}

AuthWrapper - Uses the useAuth hook to check the authentication status of user. If currentUser is undefined it conditionally returns early null or some other loading indicator. Once the currentUser state is populated/defined the component conditionally renders either an Outlet for nested/wrapped Route components you want to protect, or the Navigate component to redirect to your auth route.

import { Navigate, Outlet, useLocation } from 'react-router-dom';

const AuthWrapper = () => {
  const location = useLocation();
  const { currentUser } = useAuth();

  if (currentUser === undefined) return null; // <-- or loading spinner, etc...

  return currentUser
    ? <Outlet />
    : <Navigate to="/" replace state={{ from: location }} />;
};

App - Unconditionally renders all routes, wrapping the Home and Profile routes in the AuthWrapper layout route.

function App() {
  return (
    <div>
      <div>
        <Routes>
          <Route element={<AuthWrapper />}>
            <Route path="/Home" element={<Home />} />
            <Route path="/Profile" element={<ProfilePage />} />
          </Route>
          <Route path="/" element={<LogInPage />} />
        </Routes>
      </div>
    </div>
  );
}


问:
sum of duplicates data list on java
I have this code

```<code>    ... some code here

    while (iterator.hasNext()) {
      Document next = iterator.next();

      projectNumber = new NpoProjectNumberVM();
      localDate = new java.sql.Date(((Date) next.get("_id")).getTime()).toLocalDate();
      projectNumber.setDay(localDate);
      projectNumber.setNumber(((Long) next.get("number")).intValue());
      projectNumberList.add(projectNumber);
    }

    return projectNumberList;
</code>```

which displays this result

```<code> "projectNumber": [
        {
            "day": "2022-02-07",
            "number": 2
        },
        {
            "day": "2022-02-07",
            "number": 1
        },
        {
            "day": "2022-02-07",
            "number": 4
        },
    ]
</code>```

My request is: I want to have the sum of the numbers for the same date like this

```<code> "projectNumber": [
        {
            "day": "2022-02-07",
            "number": 7
        },
    ]
</code>```

答:
You may use a Map where the key is the date, so you can verify if it exists or not then do the good logic

```<code>static List<Document> method() {
    Map<LocalDate, Document> projects = new HashMap<>();

    while (iterator.hasNext()) {
        Document next = iterator.next();

        localDate = new java.sql.Date(((Date) next.get("_id")).getTime()).toLocalDate();
        int nb = ((Long) next.get("number")).intValue();

        if (projects.containsKey(localDate)) {
            projects.get(projectNumber).setNumber(nb + projects.get(projectNumber).getNumber());
        } else {
            projectNumber = new NpoProjectNumberVM();
            projectNumber.setDay(localDate);
            projectNumber.setNumber();
            projects.put(localDate, projectNumber);
        }
    }

    return new ArrayList<>(projects.values());
}
</code>```

Title: sum of duplicates data list on java

Body:
I have this code

    ... some code here

    while (iterator.hasNext()) {
      Document next = iterator.next();

      projectNumber = new NpoProjectNumberVM();
      localDate = new java.sql.Date(((Date) next.get("_id")).getTime()).toLocalDate();
      projectNumber.setDay(localDate);
      projectNumber.setNumber(((Long) next.get("number")).intValue());
      projectNumberList.add(projectNumber);
    }

    return projectNumberList;

which displays this result

 "projectNumber": [
        {
            "day": "2022-02-07",
            "number": 2
        },
        {
            "day": "2022-02-07",
            "number": 1
        },
        {
            "day": "2022-02-07",
            "number": 4
        },
    ]

My request is: I want to have the sum of the numbers for the same date like this

 "projectNumber": [
        {
            "day": "2022-02-07",
            "number": 7
        },
    ]

Body:
You may use a Map where the key is the date, so you can verify if it exists or not then do the good logic

static List<Document> method() {
    Map<LocalDate, Document> projects = new HashMap<>();

    while (iterator.hasNext()) {
        Document next = iterator.next();

        localDate = new java.sql.Date(((Date) next.get("_id")).getTime()).toLocalDate();
        int nb = ((Long) next.get("number")).intValue();

        if (projects.containsKey(localDate)) {
            projects.get(projectNumber).setNumber(nb + projects.get(projectNumber).getNumber());
        } else {
            projectNumber = new NpoProjectNumberVM();
            projectNumber.setDay(localDate);
            projectNumber.setNumber();
            projects.put(localDate, projectNumber);
        }
    }

    return new ArrayList<>(projects.values());
}