I am receiving "shmat: permission denied" when attempting to attach to shared memory. Why?

I’m having a little trouble with shared memory, and could use a little guidance if someone could point me in the right direction.

// Allocate Shared Memory
key_t key = 56789;
int shmid;
char* shm_address;
int* value;

// Reserve the memory
if (shmid = shmget(key, sizeof(int), IPC_CREAT | 0777) < 0)
{
    perror("shmget was unsuccessful");
    exit(1);
}   
else
{
    printf("\nMemory created successfully:%d\n", shmid);
}

// Attach to memory address
if ( (shm_address = shmat(shmid, NULL, 0)) == (char *)-1 )
{

    perror("shmat was unsuccessful");
    exit(1);

}
else
{
    printf ("shared memory attached at address %p\n", shm_address);
}

I then do some process management, call shmdt(shm_address), and finally cleanup with shmctl. But I never reach that part of the code.

I get this as output:

Memory created successfully:0

shmat was unsuccessful: Permission denied

I just don’t understand why shmat is failing to attach? When I call the ipcs command after execution, my memory is allocated, so I’m fairly confident that shmget is working. Could anyone point me in the right direction? Thanks.

Solution:

Precedence error:

if (shmid = shmget(key, sizeof(int), IPC_CREAT | 0777) < 0)

This assigns shmget(key, sizeof(int), IPC_CREAT | 0777) < 0 (i.e. 0 or 1) to shmid. You want

if ((shmid = shmget(key, sizeof(int), IPC_CREAT | 0777)) < 0)
Advertisements

Git doesn't add my files, even though I add them

After adding files in a bunch of different ways, the files are still not added to the commit, no matter which way I am trying to add them. This is my console output so you understand better:

daniel@padamtuts:~/github/dotfiles$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working    directory)
  (commit or discard the untracked or modified content in submodules)

    modified:   .vim/bundle/auto-pairs (modified content)
    modified:   .vim/bundle/ctrlp.vim (modified content)
    modified:   .vim/bundle/emmet-vim (modified content)
    modified:   .vim/bundle/nerdtree (modified content)
    <a lot of files>

no changes added to commit (use "git add" and/or "git commit -a")
daniel@padamtuts:~/github/dotfiles$ git add *
daniel@padamtuts:~/github/dotfiles$ git add -A
daniel@padamtuts:~/github/dotfiles$ git commit -m "Vim bundles"
On branch master
Changes not staged for commit:
    modified:   .vim/bundle/auto-pairs (modified content)
    ...
    <same files>

no changes added to commitPdaniel@padamtuts:~/github/dotfiles$ git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working    directory)
  (commit or discard the untracked or modified content in submodules)

    modified:   .vim/bundle/auto-pairs (modified content)
    <same files>

no changes added to commit (use "git add" and/or "git commit -a")
daniel@padamtuts:~/github/dotfiles$ git add *
daniel@padamtuts:~/github/dotfiles$ git add -A
daniel@padamtuts:~/github/dotfiles$ git commit -m "Vim bundles"
On branch master
Changes not staged for commit:
    modified:   .vim/bundle/auto-pairs (modified content)
    <same files>

no changes added to commit

“`

Solution:

Files/directories that begin with . are ‘hidden’ and will be ignored by git when you add with the glob character. You can read about these ‘dotfiles’ if you want to learn more; usually they are configuration files (e.g. for vim) and such that you may not want to interact with directly and by default will not appear in a file explorer, or in the output of ls, etc.

For your purposes, git add . should do the trick.

How can I store multiple function as a value of the dictionary?

In the following code I try to store multiple functions as a value of the dictionary. This code doesn’t work. The two functions are returned as a tuple. But I don’t want to iter over the dictionary. I want to use a special key, and then I want the dictionary to run the two functions.

from functools import partial

def test_1(arg_1 = None):
     print "printing from test_1 func with text:", arg_1

def test_2(arg_2 = None):
     print "printing from test_2 func with text:", arg_2

dic = {'a':(partial(test_1, arg_1 = 'test_1'),
            partial(test_2, arg_2 = 'test_2'))}

dic['a']()

Solution:

You can build a closure to do that like:

Code:

def chain_funcs(*funcs):
    """return a callable to call multiple functions"""
    def call_funcs(*args, **kwargs):
        for f in funcs:
            f(*args, **kwargs)

    return call_funcs

Test Code:

def test_1(arg_1=None):
    print("printing from test_1 func with text: %s" % arg_1)


def test_2(arg_2=None):
    print("printing from test_2 func with text: %s" % arg_2)


from functools import partial
dic = {'a': chain_funcs(partial(test_1, arg_1='test_1'),
                        partial(test_2, arg_2='test_2'))}

dic['a']()

Results:

printing from test_1 func with text: test_1
printing from test_2 func with text: test_2

How can I delete a repeated dictionary in list?

for dynamic values sometimes the value will be keep repeating, say if a variable

table = [
    {'man':'tim','age':'2','h':'5','w':'40'},
    {'man':'jim','age':'4','h':'3','w':'20'},
    {'man':'jon','age':'24','h':'5','w':'80'}, 
    {'man':'tim','age':'2','h':'5','w':'40'},
    {'man':'tto','age':'7','h':'4','w':'49'}    
]

here {'man':'tim','age':'2','h':'5','w':'40'} dictionary set repeat twice these are dynamic value.

How can I stop repeating this, so list will not contain any repeated dictionary before rendering it to templates?

edited: actual data

[{'scorecardid': 1, 'progress2': 'preview', 'series2': 'Afghanistan v Zimbabwe in UAE, 2018', 'Commentary1': '/Commentary1', 'commentaryid': 1, 'matchid2': '10', 'matchno2': '5th ODI', 'teams2': 'AFG vs ZIM', 'matchtype2': 'ODI', 'Scorecard1': '/Scorecard1', 'status2': 'Starts on Feb 19 at 10:30 GMT'}, {'six2': '0', 'scorecardid': 2, 'overs5': '4', 'fours1': '0', 'overs10': '20', 'Batting_team_img': 'images/RSA.png', 'wickets20': '5', 'wickets6': '1', 'Bowling_team_img': 'images/IND.png', 'maidens6': '0', 'Batting team': 'RSA', 'matchid2': '9', 'name6': 'Unadkat', 'teams2': 'RSA vs IND', 'wickets10': '9', 'desc10': 'Inns', 'runs5': '32', 'matchtype2': 'T20', 'Scorecard1': '/Scorecard2', 'runs1': '2', 'wickets5': '0', 'runs6': '33', 'runs2': '0', 'maidens5': '0', 'runs20': '203', 'name5': 'Bumrah*', 'progress2': 'complete', 'Commentary1': '/Commentary2', 'fours2': '0', 'series2': 'India tour of South Africa, 2017-18', 'name1': 'Junior Dala*', 'commentaryid': 2, 'matchno2': '1st T20I', 'six1': '0', 'overs6': '4', 'Bowling team': 'IND', 'balls2': '2', 'balls1': '3', 'name2': 'Shamsi', 'overs20': '20', 'runs10': '175', 'desc20': 'Inns', 'status2': 'Ind won by 28 runs'}, {'scorecardid': 3, 'overs5': '0.4', 'fours1': '0', 'overs10': '18.4', 'Batting_team_img': 'images/BAN.png', 'wickets20': '4', 'wickets6': '1', 'Bowling_team_img': 'images/SL.png', 'Batting team': 'BAN', 'matchid2': '6', 'name6': 'Shanaka', 'teams2': 'BAN vs SL', 'wickets10': '10', 'desc10': 'Inns', 'runs5': '3', 'matchtype2': 'T20', 'Scorecard1': '/Scorecard3', 'runs1': '1', 'wickets5': '2', 'runs6': '5', 'maidens5': '0', 'runs20': '210', 'progress2': 'complete', 'Commentary1': '/Commentary3', 'name5': 'Gunathilaka*', 'series2': 'Sri Lanka tour of Bangladesh, 2018', 'name1': 'Nazmul Islam', 'commentaryid': 3, 'matchno2': '2nd T20I', 'six1': '0', 'overs6': '1.5', 'Bowling team': 'SL', 'maidens6': '0', 'balls1': '1', 'overs20': '20', 'runs10': '135', 'desc20': 'Inns', 'status2': 'SL won by 75 runs'}, {'six2': '2', 'scorecardid': 4, 'overs5': '4', 'fours1': '1', 'overs10': '20', 'Batting_team_img': 'images/NZ.png', 'wickets20': '7', 'wickets6': '1', 'Bowling_team_img': 'images/ENG.png', 'maidens6': '0', 'Batting team': 'NZ', 'matchid2': '4', 'name6': 'Tom Curran', 'teams2': 'NZ vs ENG', 'wickets10': '4', 'desc10': 'Inns', 'runs5': '41', 'matchtype2': 'T20', 'Scorecard1': '/Scorecard4', 'runs1': '7', 'wickets5': '0', 'runs6': '32', 'runs2': '37', 'maidens5': '0', 'runs20': '194', 'name5': 'Chris Jordan*', 'progress2': 'complete', 'Commentary1': '/Commentary4', 'fours2': '2', 'series2': 'England, Australia, New Zealand T20I Tri-Series, 2018', 'name1': 'de Grandhomme*', 'commentaryid': 4, 'matchno2': '6th Match', 'six1': '0', 'overs6': '3', 'Bowling team': 'ENG', 'balls2': '30', 'balls1': '5', 'name2': 'Chapman', 'overs20': '20', 'runs10': '192', 'desc20': 'Inns', 'status2': 'Eng won by 2 runs'}, {'scorecardid': 5, 'overs5': '7.4', 'fours1': '3', 'runs20': '213', 'six2': '0', 'commentaryid': 5, 'Batting team': 'SAUS', 'matchid2': '18770', 'matchno2': '21st Match', 'wickets10': '3', 'overs10': '49.4', 'matchtype2': 'TEST', 'runs1': '26', 'overs6': '8', 'runs6': '39', 'runs2': '49', 'name1': 'Mennie*', 'name5': 'Daniel Fallins*', 'series2': 'Sheffield Shield, 2017-18', 'Commentary1': '/Commentary5', 'wickets6': '1', 'runs11': '281', 'six1': '0', 'runs10': '192', 'balls1': '58', 'overs11': '74.1', 'maidens5': '1', 'desc21': '1st Inns', 'status2': 'South Aus won by 7 wkts', 'runs5': '51', 'wickets11': '10', 'desc11': '1st Inns', 'desc20': '2nd Inns', 'wickets20': '10', 'wickets21': '10', 'teams2': 'NSW vs SAUS', 'balls2': '85', 'Scorecard1': '/Scorecard5', 'wickets5': '1', 'progress2': 'Result', 'runs21': '256', 'fours2': '6', 'desc10': '2nd Inns', 'name6': 'Stobo', 'maidens6': '1', 'Bowling team': 'NSW', 'name2': 'Ferguson', 'overs20': '68.4', 'overs21': '90.4'}, {'six2': '0', 'scorecardid': 6, 'overs5': '4', 'fours1': '0', 'overs10': '20', 'Batting_team_img': 'images/RSA.png', 'wickets20': '5', 'wickets6': '1', 'Bowling_team_img': 'images/IND.png', 'maidens6': '0', 'Batting team': 'RSA', 'matchid2': '19166', 'name6': 'Unadkat', 'teams2': 'RSA vs IND', 'wickets10': '9', 'desc10': 'Inns', 'runs5': '32', 'matchtype2': 'T20', 'Scorecard1': '/Scorecard6', 'runs1': '2', 'wickets5': '0', 'runs6': '33', 'runs2': '0', 'maidens5': '0', 'runs20': '203', 'name5': 'Bumrah*', 'progress2': 'Result', 'Commentary1': '/Commentary6', 'fours2': '0', 'series2': 'India tour of South Africa, 2017-18', 'name1': 'Junior Dala*', 'commentaryid': 6, 'matchno2': '1st T20I', 'six1': '0', 'overs6': '4', 'Bowling team': 'IND', 'balls2': '2', 'balls1': '3', 'name2': 'Shamsi', 'overs20': '20', 'runs10': '175', 'desc20': 'Inns', 'status2': 'Ind won by 28 runs'}]

Solution:

Since your records do not appear to have a unique identifier to differentiate records, you will need to hash on all key-value pairs. This approach will work as long as you do not have nested mutable objects inside your dictionaries.

I’ll use an OrderedDict here to maintain order.

from collections import OrderedDict
list(
     map(
         dict, 
         OrderedDict.fromkeys(
             map(frozenset, map(dict.items, table)), None
         )
     )
)

[{'age': '2', 'h': '5', 'man': 'tim', 'w': '40'},
 {'age': '4', 'h': '3', 'man': 'jim', 'w': '20'},
 {'age': '24', 'h': '5', 'man': 'jon', 'w': '80'},
 {'age': '7', 'h': '4', 'man': 'tto', 'w': '49'}]

Here’s what’s going on:

  1. Convert each dictionary to a frozenset of tuples. frozensets are hashable.
  2. Hash each frozenset as a key into an OrderedDict. Duplicates are removed automatically.
  3. Retrieve keys and convert back into a list of dictionaries.

There are many ways to reproduce the algorithm described above. I’ve used the functional programming tool – map – which python offers.

Using Massive Amounts of Implemented Interfaces

I am trying to create a game involving machines and items. I have a simple item interface and every item will implement this.

I would usually just create a class for every item, but there could potentially be thousands of items, and it doesn’t feel right to create thousands of files for all the items. This applies to other large amounts of types of objects I might have. (ground tiles, entities)

I need a type safe way to store all these implemented interfaces. I need to easily be able to create a new item in my code, with only the name of the item.

I was thinking of having a huge class with subclasses holding lots of final constants that would all be anonymous classes, but this also seems like a bad way of doing this.

Is there any good way to do what I have in mind? (Sorry that this is a little vague)

My item interface is currently,

package com.bobona.craftable.model;

import com.bobona.craftable.CraftableGame;

import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

public interface Item {

    String getId();
    Map<String, Integer> getValues();
    void onUse(AtomicReference<CraftableGame> game, Long entityUsedByIndex);
    void onSecondaryUse(AtomicReference<CraftableGame> game, Long 
    entityUsedByIndex);
}

Solution:

This is a difficult design problem, and there is no one size fits all answer as far as I know. As mentioned by Makoto in another answer, much of your approach will be dictated by the actual details of your specific game.

I would usually just create a class for every item, but there could potentially be thousands of items, and it doesn’t feel right to create thousands of files for all the items.

I completely agree with this statement.

I need a type safe way to store all these implemented interfaces.

I’m not sure that this is possible (literally as written), if we accept the previous statement that separate classes or interfaces aren’t the correct approach. However, if instead of type safe you’ll settle for verifiable at runtime by some yet-unspecified mechanism, then I think it’s quite doable.

[From Comment] It also wouldn’t be nice to use non type-safe values to define items in recipes, as that would quickly become a pain to debug and refactor.

I agree you’ll want some sort of verification, but as previously mentioned full-blown compile-time type safety might not be feasible while also avoiding thousands of separate classes. I think the key here is to reliably detect errors, respond to them in a way that doesn’t break the game, and generate sensible debug messages for the developer.


There are a lot of ways to go about accomplishing this; which one you choose is going to depend on your exact requirements, your preferences, and a number of implementation details that I have no way of knowing. Some things that I think you should look into or consider:

  • Inheritance probably won’t work at all, for the reasons you’ve already identified.
  • Composition or the flyweight pattern might improve things initially, but probably won’t scale the way you want.
  • You could go for a RDBMS approach, as outlined here.
  • You might try a JSON based approach or equivalent, as outlined here.
  • The component pattern fits my understanding of your problem very well.
  • This is an incredibly well written answer detailing how to implement the component pattern for entities (which I think include the types of items you were describing) using bit fields.
  • This is a very similar question to yours on the gamedev stackexchange with some good answers.

Personally I like the component pattern, and am a fan of using JSON or an equivalent language for specifying the items themselves. Hopefully at least some of the above information will help you as you iteratively modify your architecture to meet your gameplay requirements.

Grouping by fields of inner object

I have following two classes:

class Man {
    private int id;
    private String firstName;
    private String lastName;
    private int age;
    private int countOfChildren;
    private Address address; 
}

class Address {
    private Country country;
    private City city;
    private String street;
    private long quantityOfPeople; 
}

I have no idea how to group List<Man> by street and city fields of Address class. How can I do it?

Solution:

Collectors class provides Collectors.groupingBy(keyProvider, downstream) you can use to group by a pair of values. To pair two values you can either use AbstractMap.SimpleEntry or you can implement your own Pair<T,K> class that represents a pair of two values (it’s worth mentioning that you will have to implement hashCode() and equals(object) methods in your Pair class if you want to use it as a key in a hash map). Also two values you want to pair in a key have to implement hashCode() and equals(object) methods – it’s worth using immutable classes in this case.

The whole grouping part can be done by:

final Map<Map.Entry<City, String>, List<Man>> groupedByCityAndStreet = people.stream()
        .collect(Collectors.groupingBy(
                man -> new AbstractMap.SimpleEntry<>(man.getAddress().getCity(), man.getAddress().getStreet()),
                Collectors.toList()
        ));

In this example I have used AbstractMap.SimpleEntry to represent a pair of Country and street. It creates a map where for each key it groups a list of Man object based of country and street. Below you can find a full example:

import java.util.AbstractMap;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

public class GroupByTest {

    public static void main(String[] args) {
        final List<Man> people = Arrays.asList(
                new Man(1, "John", "Doe", 20, 0, new Address(new Country("England"), new City("London"), "Test Street 2", 10000)),
                new Man(2, "Mary", "Smith", 54, 4, new Address(new Country("Germany"), new City("Berlin"), "Maine Strasse 32", 10000)),
                new Man(3, "James", "Rose", 13, 0, new Address(new Country("England"), new City("London"), "Test Street 2", 10000)),
                new Man(4, "Vincent", "Dog", 43, 2, new Address(new Country("Germany"), new City("Berlin"), "Volkswagen Platz 31", 10000)),
                new Man(5, "Arnold", "Smoke", 72, 3, new Address(new Country("Italy"), new City("Rome"), "Pepperoni 31", 10000)),
                new Man(6, "Katy", "Puppet", 33, 3, new Address(new Country("England"), new City("London"), "Test Street 3", 10000))
        );

        final Map<Map.Entry<City, String>, List<Man>> groupedByCityAndStreet = people.stream()
                .collect(Collectors.groupingBy(
                        man -> new AbstractMap.SimpleEntry<>(man.getAddress().getCity(), man.getAddress().getStreet()),
                        Collectors.toList()
                ));

        // Print people associated with given city and street to console
        groupedByCityAndStreet.forEach((k, v) -> {
            System.out.println("People associated with " + k.getKey().name + ", " + k.getValue() + ":");
            v.forEach(man -> {
                System.out.println(man);
            });
        });
    }

    static final class Man {
        private final int id;
        private final String firstName;
        private final String lastName;
        private final int age;
        private final int countOfChildren;
        private final Address address;

        public Man(int id, String firstName, String lastName, int age, int countOfChildren, Address address) {
            this.id = id;
            this.firstName = firstName;
            this.lastName = lastName;
            this.age = age;
            this.countOfChildren = countOfChildren;
            this.address = address;
        }

        public int getId() {
            return id;
        }

        public String getFirstName() {
            return firstName;
        }

        public String getLastName() {
            return lastName;
        }

        public int getAge() {
            return age;
        }

        public int getCountOfChildren() {
            return countOfChildren;
        }

        public Address getAddress() {
            return address;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Man man = (Man) o;
            return id == man.id &&
                    age == man.age &&
                    countOfChildren == man.countOfChildren &&
                    Objects.equals(firstName, man.firstName) &&
                    Objects.equals(lastName, man.lastName) &&
                    Objects.equals(address, man.address);
        }

        @Override
        public int hashCode() {
            return Objects.hash(id, firstName, lastName, age, countOfChildren, address);
        }

        @Override
        public String toString() {
            return "Man{" +
                    "id=" + id +
                    ", firstName='" + firstName + '\'' +
                    ", lastName='" + lastName + '\'' +
                    ", age=" + age +
                    ", countOfChildren=" + countOfChildren +
                    ", address=" + address +
                    '}';
        }
    }

    static class Address {
        private final Country country;
        private final City city;
        private final String street;
        private final long quantityOfPeople;

        public Address(Country country, City city, String street, long quantityOfPeople) {
            this.country = country;
            this.city = city;
            this.street = street;
            this.quantityOfPeople = quantityOfPeople;
        }

        public Country getCountry() {
            return country;
        }

        public City getCity() {
            return city;
        }

        public String getStreet() {
            return street;
        }

        public long getQuantityOfPeople() {
            return quantityOfPeople;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Address address = (Address) o;
            return quantityOfPeople == address.quantityOfPeople &&
                    Objects.equals(country, address.country) &&
                    Objects.equals(city, address.city) &&
                    Objects.equals(street, address.street);
        }

        @Override
        public int hashCode() {

            return Objects.hash(country, city, street, quantityOfPeople);
        }

        @Override
        public String toString() {
            return "Address{" +
                    "country=" + country +
                    ", city=" + city +
                    ", street='" + street + '\'' +
                    ", quantityOfPeople=" + quantityOfPeople +
                    '}';
        }
    }

    static class City {
        private final String name;

        public City(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            City city = (City) o;
            return Objects.equals(name, city.name);
        }

        @Override
        public int hashCode() {

            return Objects.hash(name);
        }

        @Override
        public String toString() {
            return "City{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }

    static class Country {
        private final String name;

        public Country(String name) {
            this.name = name;
        }

        public String getName() {
            return name;
        }

        @Override
        public boolean equals(Object o) {
            if (this == o) return true;
            if (o == null || getClass() != o.getClass()) return false;
            Country country = (Country) o;
            return Objects.equals(name, country.name);
        }

        @Override
        public int hashCode() {

            return Objects.hash(name);
        }

        @Override
        public String toString() {
            return "Country{" +
                    "name='" + name + '\'' +
                    '}';
        }
    }
}

When you run this example you will something like this in the console:

People associated with Rome, Pepperoni 31:
Man{id=5, firstName='Arnold', lastName='Smoke', age=72, countOfChildren=3, address=Address{country=Country{name='Italy'}, city=City{name='Rome'}, street='Pepperoni 31', quantityOfPeople=10000}}
People associated with London, Test Street 3:
Man{id=6, firstName='Katy', lastName='Puppet', age=33, countOfChildren=3, address=Address{country=Country{name='England'}, city=City{name='London'}, street='Test Street 3', quantityOfPeople=10000}}
People associated with Berlin, Volkswagen Platz 31:
Man{id=4, firstName='Vincent', lastName='Dog', age=43, countOfChildren=2, address=Address{country=Country{name='Germany'}, city=City{name='Berlin'}, street='Volkswagen Platz 31', quantityOfPeople=10000}}
People associated with Berlin, Maine Strasse 32:
Man{id=2, firstName='Mary', lastName='Smith', age=54, countOfChildren=4, address=Address{country=Country{name='Germany'}, city=City{name='Berlin'}, street='Maine Strasse 32', quantityOfPeople=10000}}
People associated with London, Test Street 2:
Man{id=1, firstName='John', lastName='Doe', age=20, countOfChildren=0, address=Address{country=Country{name='England'}, city=City{name='London'}, street='Test Street 2', quantityOfPeople=10000}}
Man{id=3, firstName='James', lastName='Rose', age=13, countOfChildren=0, address=Address{country=Country{name='England'}, city=City{name='London'}, street='Test Street 2', quantityOfPeople=10000}}

Hope it helps.