python – One data object instead of array of objects – why is it slower?

I’m currently writing a game of life with small extra features but I ran into a problem – in my first try i decided to use simple list of Cell objects:

class Cell:
    def __init__(self, x, y, is_alive):
        self.is_alive = is_alive
        self.x = x
        self.y = y
        self.will_be_alive = False
        self.neighbours = 0

    def kill(self):
        self.will_be_alive = False

    def revive(self):
        self.will_be_alive = True

    def iterate(self):
        self.is_alive = self.will_be_alive

but now I’m using different approach:

class Cells:
    def __init__(self, width, height):
        self.current_states = ((False for i in range(width)) for j in range(height))
        self.next_states = ((False for i in range(width)) for j in range(height))
        self.neighbours = ((0 for i in range(width)) for j in range(height))

as you can see, instead of list of objects it’s now object with lists. I expected my program to run slightly faster, but it’s totally opposite – it’s 20 fps less. I think, that problem may be in iterate method in second way:

def next_state(cells):
    for i, row in enumerate(cells.current_states):
        for j, cell in enumerate(row):
            if cells.neighbours(i)(j) > 0:
                count_state(cells, j, i)
            elif cells.neighbours(i)(j) == 0 and cells.current_states(i)(j):
                cells.next_states(i)(j) = False
    for i, row in enumerate(cells.current_states):
        for j, cell in enumerate(row):
            neigh_iterate(cells, j, i)

def count_state(cells, x, y):
    nei = neighboors(cells.current_states, x, y)
    if (nei > 3 or nei < 2) and cells.current_states(y)(x):
        cells.next_states(y)(x) = False
    elif nei == 3 and not cells.current_states(y)(x):
        cells.next_states(y)(x) = True

def neigh_iterate(cells, x, y):
    prev = cells.current_states(y)(x)
    iterate(cells, x, y)
    if cells.current_states(y)(x) != prev:
        if cells.current_states(y)(x):
            add_neighbour(cells.neighbours, x, y, 1)
            add_neighbour(cells.neighbours, x, y, -1)

def neighboors(current_states, x, y):
    how_many = -1 if current_states(y)(x) else 0
    for i in range(-1, 2):
        for j in range(-1, 2):
            if current_states((y + i) % BOARD_HEIGHT)((x + j) % BOARD_WIDTH):
                how_many += 1
    return how_many

def iterate(cells, x, y):
    cells.current_states(y)(x) = cells.next_states(y)(x)

Do you have any ideas guys?

node.js – How to make a Leaderboard using objects inside objects? Javascript

so I am trying to make a leaderboard of the players with more points, the object kinda looks like this:

let currency = {
    person1: {
        money: 1004,
        level: 20
    person2: {
        money: 124,
        level: 3
    person3: {
        money: 50144,
        level: 102

and what I want to do is it to create a leaderboard based on everyone’s MONEY (not level)
For example:

  1. person3 | 50144
  2. person1 | 1004
  3. person2 | 124

Any help will be appreciated since i have been stuck in this part.

c# – Create a Dictionary of a Property as a Key and List of Objects as Values from a List of Objects

I have a User Object as follows

public class UserInfo 
    public string DepartmentCd { get; set; }
    public string DepartmentNm { get; set; }

And I have a list of UserInfo objects and want to create a dictionary with DepartmentCd as key and List<UserInfo> Object as value (users who belong to that Dept)
Below code does it for me, but curious if there is a better and elegant way to achieve this.

var deptUserDict = employeeInfoList.GroupBy(x => x.DepartmentCd).ToDictionary(x => x.Key, x => x.ToList());

design – Memento pattern for Undo/Redo AND Save/Load with multiple objects

In a pretty big project, I have a hierarchy of objects, let’s say:

Zone object, which contains Block objects and Connection objects.

Mainliy, the Connection object links together several Block objects, all inside a Zone.

In this project, I am using the Memento pattern (together with the Command Pattern) for implementing Undo/Redo functionallity.

Also, I am reusing the “Memento” implementation to implement also Save/Load functionallity, so the Undo/Redo propertis are always in sync with what is being Saved/Loaded.

Something among the lines:

    //Base class for Zone, Connection and Block
    class Object
        virtual void save(IWriter *writer) = 0;
        virtual void load(IReader *reader) = 0;

    //Base classes:
    class IWriter
        virtual void writeInt(int x) = 0;
    class IReader
        virtual int readInt() = 0;

    //The Memento just saves / reads data from a memory map
    class Memento: public IWriter, public IReader

    //These classes are used to save / load from file
    class XmlWriter: public IWriter
    class XmlReader: public IReader

Now, it is easy to do the Undo / Redo command for deleting a zone:

    class DeleteZone: public QUndoCommand
        void redo()
            //NOTE: zone will save its own data, and also all its children data, in order
            //to restore completely the previous state.
            delete zone;
        void undo()
           Zone *zone=new Zone();
        Memento data;

And it is also easy to Save / Load the entire Zone:

    XmlWriter writer("path to file");

So, using this patterns, the UI does not need to know anything about the internal logic of the model. It just saves / loads the data and it is done.

Now I wanted to repeat this pattern also for the Connection object, which seemed similar.

Here is the problem:

When a connection is created, it should perform some operations on the related Block objects. Let’s call them connectionCreated()

This operations depend on the connections each Block has, so there are two different situations:

  • When only a connection is being created (like in a CreateConnectionCommand), then connectionCreated() should be called immediately.

In this case, to prevent the UI to know anything about the internal logic, I was thinking to add the connectionCreated() to the Connection constructor.

  • But when loading the entire Zone, connectionCreated() should be delayed, until all the connections have been loaded.

So it is not valid the solution of adding it to the constructor. Here it should be added to the load() function of the Zone, which is fine, BUT it should be also added to the CreateConnectionCommand, which is part of the UI and thus it seems not fine.

AND also, the Memento object should save the Connection state, together with the related objects for the case when a connection is being created, but not when the zone is created (since this will be handled by Zone::load()), again leaking the model details to the UI undo/redo functionallity.

Is there some better pattern / approach to this situation?

Note 1:

connectionCreated() does some operations to update variables inside Block to ensure consistency, and it also creates some required objects which will be visible to the user.

Furthermore, to ensure consistency, it may create other connections, which in the case of Zone::load may still to be created, thus duplicating objects.

This is why in the situation of Zone::load, this operations should be delayed until all the connections are created, but not in the case of CreateConnectionCommand, where only one NEW connection is being created.

api design – Representing a large list of complex objects in JSON

If you are concerned that the amount of data overhead of duplicating the keys is going to be a large enough problem for you that it is worth optimising for, there is another approach you may wish to consider

    "timeseries": (
        (1, "OK"),
        (2, "OK"),
        (3, "INVALID"),
        // ...

in this way, you keep objects together but in a structure that does not need to duplicate the keys.

As someone who is just inspecting the data, if it were to happen manually, having an array of values, and an array of statuses, where respective indexes are related (status(1) and values(1) relate), varying value lengths over long durations would make it hard to read for a human. Whether that is a concern to you or not i cant say.

if you want to optimise it even further, you may consider having all the possible statuses be a numeric enum instead, eg:

    "timeseries": (
        (1, 0),
        (2, 0),
        (3, 1),
        // ...

where you have a mapping of 0 = ok, 1 = invalid, 2 = some other fail state…etc.

realistically, these optimisations will be of minimal use in most cases due to compression and how large your messages would need to be for these differences to actually amount for much

c++ – Method to identify and compare objects in two JSON

I am looking for a method to identify compare objects. Right now I am getting two JSON-files with information about kernel objects from a memory dump, such as Processes, Threads, Mutex and so on. Each object has several attributes. The JSON_1 was created some minutes prior the JSON_2. So I want to compare which objects changed(their attributes) during the time difference.
Here an example of three objects in the JSON:

enter image description here

enter image description here

enter image description here

Right now I am using the “unique” attributes of an object and generate a UUID (Version 5) out of it. In Process I would take id and startime+pid+name to calculate a compId (UUID) (compare ID). Then I can search this UUID in JSON_2 and see what has changes in the process (like exitTime, memory usage).

Is there any other method beside UUID to identify objects and compare them later?

I can change the C++ code for creating the JSON to create more attributes if this helps somehow.

single responsibility – Should a Car object be responsible for checking if it is able to run on certain Road objects?

I have 2 kinds of objects in my system, Car and Road.

A Car can be of various types and have properties like tire, tire size, engine, etc.

A Road can be of multiple types and have properties like terrain type, slippery, etc.

Some type of cars cannot ride on certain roads, based on the road properties and car limitations/constraints, like a common car cannot walk on beach sand because it would get stuck with smaller tires and weaker engine, but a “monster truck” could, because it has bigger tires and a better engine.

with that in mind, who should have the responsibility of checking whether a car can ride on a specific road?

i think that a Car should throw exceptions if it cannot ride, but i don’t think a Car should know in which road is going to ride.

  • should the road check the car’s properties and tell if it’s able to
    run on the road?
    i think this options falls to a procedural approach of getters/setters.

  • how would this scenario “scale” if a had multiple properties on a Car
    that could affect the capability of riding on a road?

how can i approach this?

base code:

export interface Car {
  engine: string;
  tire: string;
  tireSize: string;

  ride(): void // ride only if Road is compatible

export interface Road {
  terrain: string;
  isSlippery: boolean;
  cars: Car();

  startRace(): void

game – Writing My First Code Using Objects – Python – Any Suggestions Now Before I continue adding methods?


To give a short contextual description: It is a poker game. I plan to add “cards” and a “pot”-object later on and then learn event-driven programming so that I can add a GUI. Essentially the player’s placement in the game-objects “player” variable determines their seat.

My main questions are in regards to the placement of methods and the data of each object. Do you guys see any sort of future issues with f.ex. betting being a player method, and not a round method? Or, that there is no round-method for turning players in-active other than end-round that turns all players inactive?

Other than that, pretty much any feedback is welcome, as long as it is backed up with a reasonable explanation of course. I am just trying to learn as many tricks as possible and “future-thinking”.


import random
import copy
import importlib

def limit(num, minimum=1, maximum=255):
  """Limits input 'num' between minimum and maximum values.
  Default minimum value is 1 and maximum value is 255."""
  return max(min(num, maximum), minimum)

#A player class - contains name, amount of cash and active-states
class player:

    def __init__(self,name,initMoney): = initMoney
        self.chipsInPlay = 0 #How much has this player betted? = name

        #Data Related To Active-States
        self.activeGame = 1 #Does it exist at all? Reasons for non-existance: No cash, no chips and no possibility of re-joining
        self.activeRound = 1 #Does it exist in this round? Reasons for 0: No cash, no chips, folding
        self.activeTurn = 0 #Is it active this turn? Reasons for 0: Another player is active

    #If the player has no money and no stake in the pot, they're out of the game
    def checkIfOut(self):
        if == 0 and self.chipsInPlay == 0:
            self.activeRound = 0
            self.activeTurn = 0
            self.activeGame = 0

    #Checks if the player has enough money to bet the blind and bets - doesn't check activeTurn - Doesn't change: chipsInPlay,activeTurn
    def blindMoneyBet(self,blind):
        if blind< or blind ==
   = - blind
            print(f"nPlayer: {} just bet the blind of {blind}$nCurrent balance: {}$nCurrent money in pot: {self.chipsInPlay}$n")
            print("blind()-Player: Imagine an all-in function here")

    #Checks if the player has enough to bet and bets money for the player, the money goes into the pot
    #Checks: If allActiveStates = 1 - Changes: activeTurn = 0*,chipsInPlay = +bet - *: unless endTurn = 0
    def regularMoneyBet(self,moneyChange,min =0,endTurn = 1):
        if self.activeGame == 1 and self.activeRound == 1 and self.activeTurn == 1:
            betLimit = limit(moneyChange,min,
            if moneyChange == betLimit: #He cannot bet more, than he has
       = - moneyChange
                self.chipsInPlay = self.chipsInPlay + moneyChange
                print(f"nPlayer: {} just bet {moneyChange}$nCurrent balance: {}$nCurrent money in pot: {self.chipsInPlay}$n")
                if endTurn == 1:
                    self.activeTurn = 0
            elif moneyChange != betLimit:
                print(f"{} tried to bet: {moneyChange}$, while he only has: {}$")
        elif self.activeGame != 0 or self.activeRound != 0 or self.activeTurn != 0:
            print(f"Player: {} is not active in the following ways:nGame: {self.activeGame}nRound: {self.activeRound}nTurn: {self.activeTurn}")

    #Turns activeRound = 0
    def fold(self):
        self.activeRound = 0
        print(f"{} just folded")

    def __str__(self):
            return f"nName: {} nCash left: {}nMoney in pot: {self.chipsInPlay}nGame active = {self.activeGame}nRound active = {self.activeRound}nTurn active = {self.activeTurn}"

#Contains previous turns
class gameRound:
    def __init__(self,players,startingPlayer = 0,bigBlind = 0, smallBlind = 0, tableSize = 5):

        #Data related to players in the round
        self.startingPlayer = startingPlayer #Given by the game object at initialization (Object)
        self.roundPlayers = players #Players who're still in play in the round (list with player objects)
        self.playersActiveRound = len(players) #Amount of players in the game (integer)

        #Data related to turns
        self.turns = ()
        self.lastTurnType = 0 #For keeping tack of possible actions (Integer)
        self.latestBet = 0 #The last bet, that was made in this round - To decide how much to raise or check (integer)
        self.turnNumber = 0 #For keeping track of which turn number, this is (integer)

        #Data related to who is active this turn
        self.activeThisTurn = 0 #Which player is active (object)
        self.activeThisTurnNumber = 0 #What number in the list of active players is the current active player (integer)
        self.playersActiveTurn = 0 #How many players have self.activeTurn = 1 - used for debugging (integer)

        #Data related to initial setup
        self.bigBlind = bigBlind #The bet that the first activeThisTurn has to bet (integer)
        self.smallBlind = smallBlind #The bet that roundPlayers(activeThisTurnNumber -1) has to bet i.e Player to the left of BBL. (integer)
        self.saveTurn() #Saves the initial player data at turn X (list with player objects)
        self.tableSize = tableSize

    #Debug methods below

    #Finds how many players are active - integer, not the actual player objects
    def findPlayersActiveTurn(self):
        g = 0
        for x in self.roundPlayers:
            if x.activeTurn == 1:
                g += g
        self.playersActiveTurn = g

    #Sets the person who is active this turn, and sets the previous active player as inactive (turn)
    def setActiveTurn(self,playerName): #Startingplayer, which is the optional argument in the game object, which is passed down into playerName is by default 0
        if type(self.activeThisTurn) == player:
            self.activeThisTurn.activeTurn = 0

        if playerName == 0: #If no name is given
            x = self.roundPlayers(random.randint(0, self.playersActiveRound - 1))
            self.activeThisTurn = x
            x.activeTurn = 1
        elif playerName != 0: #If a name is given
            for x in self.roundPlayers:
                if == playerName:
                    x.activeTurn = 1
                    self.activeThisTurn = x

    #Saves the current player data as a nested list in the self.turns list
    def saveTurn(self):
        z = () #For storing playerdata
        for x in self.roundPlayers:
            y = copy.copy(x) #Makes a copy of the player objects

        self.turns.append(0) #Adds a new index
        self.turns(self.turnNumber) = z #Turns this index into z

    #Finds the current active player's number in the turn order
    def findActiveNumber(self):
        g= -1 #List indexes start at 0
        for x in self.roundPlayers:
            g = g +1
            if x == self.activeThisTurn:
                self.activeThisTurnNumber = g
                #Make a debug such that, if there are more actives this turn, it will say so

    #Selects the closest roundActive player to the right of the current activeTurnPlayer as the next activeTurn.
    def nextActive(self):

        y = (self.activeThisTurnNumber+1)%len(self.roundPlayers) #Goes one player to the right, modulo so it restarts at 0 if y +1 is out of bounds

        for x in range(y,len(self.roundPlayers)): #x in (y;self.playersActiveRound(
            h = x%len(self.roundPlayers)

            if self.roundPlayers(h).activeRound == 1 and self.roundPlayers(h) != self.activeThisTurn: #First activeRound player to the right of this current active player
                self.roundPlayers(h).activeTurn = 1
                self.activeThisTurn = self.roundPlayers(h)
                return() #Ends it
                print(f"nNo other active players than {}")

    #Removes inactive players from the round list
    def removeInactiveRound(self):
        listOfActivePlayers = ()
        for x in self.roundPlayers:
            if x.activeRound == 1 and x.activeGame == 1:
        self.playersActiveRound = len(listOfActivePlayers)
        self.roundPlayers = listOfActivePlayers

    #Increments the turn by 1, changes the activeTurn player, removes inactive players and saves the player data to the turnlist
    def endTurn(self):
        self.turnNumber = self.turnNumber + 1

    def startingTurn(self):
        self.setActiveTurn(self.startingPlayer) #Starting player is provided by the game-object whenever a round is initialized
        self.activeThisTurn.blindMoneyBet(self.bigBlind) #Blind instead of moneybet, as there are no restrictions in terms of active status
        self.roundPlayers(self.activeThisTurnNumber-1).blindMoneyBet(self.smallBlind) #This works because -1 = highest number, so if 0 -1 = -1 = highest index in the list

class game:

    def __init__(self,initPlayers,startingPlayer = 0,bigBlind = 25, smallBlind = 10):
        self.players = initPlayers
        self.playersCash = self.sumList(0) #How Much Money The Players Have excl. In Pot
        self.playersActiveGame = self.sumList(1) #How Many Players Are Active In The Game (int)
        self.chipsInPlay = self.sumList(2) #The Current Pot Size
        self.bigBlind = bigBlind
        self.smallBlind = smallBlind
        self.startingPlayer = startingPlayer #The initial starting player for this or the next round
        self.startRound() #Creates a gameRound object, chooses the initial starting player and makes the players bet BBL and SBL

    #Sums up the amount of cash held by all players and returns a float
    def cashPlayersSum(self,players):
        sum = 0
        for x in players:
            sum = + sum
        return sum

    #Sums the amount of active players and returns an integer
    def playersActiveGameSum(self,players):
        sum = 0
        for x in players:
            sum = x.activeGame + sum
        return sum

    #Sums the chips in play AKA the Pot and returns number
    def chipsInPlayPlayersSum(self,players):
        sum = 0
        for x in players:
            sum = x.chipsInPlay + sum
        return sum

    # Sums up all sum-values and adds them to a list
    def valuesPlayersSum(self,players):
        totalSum = ()
        totalCash = self.cashPlayersSum(players)
        totalActivesGame = self.playersActiveGameSum(players)
        totalChipsInPlay = self.chipsInPlayPlayersSum(players)


        return totalSum

    #Updates the game's player-based sums
    def updateValuesPlayersSum(self):

        totalSum = self.valuesPlayersSum(self.players)

        self.sumList = totalSum
        self.playersCash = self.sumList(0)
        self.totalActivesGame = self.sumList(1)
        self.chipsInPlay = self.sumList(2)

    #Sets a person to be active in the round, and makes the first active player bet, and the player left to him on the list bet.
    def startRound(self):
        self.currentRound = gameRound(self.players,self.startingPlayer,self.bigBlind,self.smallBlind)

    def gameEndTurn(self):
    #Needs a function that continously allows for each active player to choose an action, unless all - 1 have folded, all have checked, or all have called the bet enough times to end round

    def __str__(self):
        return f"nPlayers in game : {str(self.players)} nActive players: {str(self.playersActiveGame)} nPot size: {str(self.chipsInPlay)} nCash on hand:  {str(self.playersCash)} "

def testNoob():
    player0 = player("player0",125)
    player1 = player("player1",125)
    player2 = player("player2",125)

    players = (player0,player1,player2)

    aGame = game(players)
    return aGame

java – Should operations on properties of list objects be encapsulated in a domain class that wraps the list?

I have a list of product price objects, List<ProductPrice>.

public class ProductPrice {

    Long id;
    LocalDate startDate;
    LocalDate endDate;
    BigDecimal value;

From the list I need to find prices that have a start date equal to or greater than a given start date AND an end date equal to or before the end date. I do that via:

List<ProductPrice> pricesInDateRange =
        .filter(p -> p.getStartDate().equals(startDate) || p.getStartDate().isAfter(startDate))
        .filter(p -> p.getEndDate().equals(endDate) || p.getEndDate().isBefore(endDate))

I need to also make sure that one price has a start date equal to the given start date and same of end date.

Finally, I need to perform some calculations on the list of ProductPrice objects using the value field. For example,

    .map(value -> value.add(BigDecimal.ONE))
    .reduce(BigDecimal.ONE, BigDecimal::multiply);

Should I create a class to wrap List<ProductPrice> for a given date range and encapsulate the calculations? For example,

public class ProductPrices {

    private List<ProductPrice> productPrices;
    public ProductPrices getPricesInDateRange(LocalDate startDate, LocalDate endDate) {
          return new ProductPrices(
            .filter(p -> p.getStartDate().equals(startDate) || p.getStartDate().isAfter(startDate))
            .filter(p -> p.getEndDate().equals(endDate) || p.getEndDate().isBefore(endDate))
   public BigDecimal calculation1() {
            .map(value -> value.add(BigDecimal.ONE))
            .reduce(BigDecimal.ONE, BigDecimal::multiply);

Or should I do these operations in the service layer instead of a domain object? In other words, don’t encapsulate in a ProductPrices class.

How to create an object of model A out of 2 random objects of model B in Django?

I’m trying to create an app that meets two random users in Django.
my question is how to create an object Meeting out of 2 random users from my User model,
I want something like a for loop so that every 2 users in my database have a meeting!

ps: I have only one day left to submit my work I will be so thankful if u help me

this is my code so far:

def createMeeting():
user_p = get_user_model()
users = user_p.objects.all()
all_users = users.exclude(username="Admin")
n = all_users.count()

for k in range(math.floor(n/2)):
    for user in all_users:
        freedate = FreeDate.objects.filter(user=user)
        starreds = user.userprofile.desired_user.all()
        matched_user = User 
        if freedate:
            if starreds:
                for u in starreds:
                     u_freedate = FreeDate.objects.filter(user=u.user)
                     for dates in freedate:
                        for matchdates in u_freedate:
                            if dates.FreeTime == matchdates.FreeTime and dates.FreeDay == matchdates.FreeDay:
                                 matched_user = u.user
            for u in users:
                u_freedate = FreeDate.objects.filter(user = u)
                for dates in freedate:
                    for matchdates in u_freedate:
                        if dates.FreeTime == matchdates.FreeTime and dates.FreeDay == matchdates.FreeDay:
                            matched_user = u

        if matched_user and matched_user != user and not(Meeting.objects.filter(user1=user, user2=matched_user) | Meeting.objects.filter(user1=matched_user, user2=user)):
            Meeting.objects.create(user1=user, user2=matched_user)`

it creates only one Meeting object and i’m getting this error:

TypeError: Field 'id' expected a number but got <class 'django.contrib.auth.models.User'>.

This is my :

class UserProfile(models.Model):
     ('Others', 'Others'),
user = models.OneToOneField(User, null=True, on_delete=models.CASCADE)
birthdate = models.DateTimeField(, null=True)
phone = models.CharField(max_length=200, null=True)
age = models.IntegerField(null=True, default=18)
years_of_experience = models.IntegerField(null=True, default=5)
job_title = models.CharField(max_length=200, null=True)
gender = models.CharField(max_length=200, null=True, choices=GENDER)
profile_image = models.ImageField(null=True, blank=True)
about = models.TextField(null=True)
desired_user = models.ManyToManyField("self")
skill = models.ManyToManyField("Skill")

`class Meeting(models.Model):
    ('Accepte', 'Accepte'),
    ('Deny', 'Deny'),
    (1, '1'),
    (2, '2'),
    (3, '3'),
    (4, '4'),
    (5, '5'),
    user1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user1', null=True)
    user2 = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user2', null=True)
    state1 = models.CharField(max_length=200, null=True, choices=STATE_CHOICES)
    state2 = models.CharField(max_length=200, null=True, choices=STATE_CHOICES)
    text1 = models.TextField(max_length=3000, null=True, blank=True)
    text2 = models.TextField(max_length=3000, null=True, blank=True)
    rate1 = models.PositiveSmallIntegerField(choices=RATE_MEETING, null=True, blank=True)
    rate2 = models.PositiveSmallIntegerField(choices=RATE_MEETING, null=True, blank=True)
    meeeting_place = models.ForeignKey(MeetingPlace, on_delete=models.CASCADE, null=True)`