问:
Why is my Bootstrap column not centering its content?`
I have the following basic layout, in which to show a flash-card - the detail-card:

```<code><div class="col-md-4"></div>
<div id="cardContainer" class="col-md-4 text-center detail-card-container">
    @Html.Partial("_DetailCard", cardModel)
</div>
<div class="col-md-4"></div>
</code>```

I know I could just use col-offset but I have plans for the other two columns.

My vision here was to divide the page into three columns, give the middle one, detail-card-container, class text-center so that the content of that div should be horizontally centered inside it.

Yet when I start up the app, I get a display as follows:

The blue is the available space in the detail-card-container for the 'detail-card, outlined in red. The detail card is fixed width 200, and the available space is about 400+ .This is displaying at the left of its available space, not in the centre as intended. The empty spaces to the left and right of the green in the image are the emptycol-md-4` divs.

What am I doing wrong?

答: Maybe you could give a specific width, display: block, plus margin-left: auto, margin-right: auto.

Body:
I have the following basic layout, in which to show a flash-card - the detail-card:

    @Html.Partial("_DetailCard", cardModel)

I know I could just use col-offset but I have plans for the other two columns.

My vision here was to divide the page into three columns, give the middle one, detail-card-container, class text-center so that the content of that div should be horizontally centered inside it.

Yet when I start up the app, I get a display as follows:

The blue is the available space in the detail-card-container for the 'detail-card, outlined in red. The detail card is fixed width 200, and the available space is about 400+ .This is displaying at the left of its available space, not in the centre as intended. The empty spaces to the left and right of the green in the image are the emptycol-md-4` divs.

What am I doing wrong?


来源: stackexchange

问:
Javascript chunky monkey algorithm code break down?
I need a help on breaking how does this code works?

```<code>    function chunkArrayInGroups(arr, size) {
      var newArr = [];
      while (arr.length) {
        newArr.push(arr.splice(0,size));
      }
      return newArr;
    }
chunkArrayInGroups(["a","b","c","d"],2);
</code>```

I dont understand how while(arr.length) gets stop and what this whole code is doing. Please break this down.

答:
```<code>arr.splice(0,size)
</code>```

Array.splice will remove elements from index 0 up till size and return them as a new array.

```<code>newArr.push(arr.splice(0,size));
</code>```

The returned array is then pushed to newArr.

```<code>while (arr.length)
</code>```

Array.splice will also mutate the original array so the arr will eventually becomes empty and the loop will end.

ContentLicense: CC BY-SA 3.0

Body:
I need a help on breaking how does this code works?

    function chunkArrayInGroups(arr, size) {
      var newArr = [];
      while (arr.length) {
        newArr.push(arr.splice(0,size));
      }
      return newArr;
    }
chunkArrayInGroups(["a","b","c","d"],2);

I dont understand how while(arr.length) gets stop and what this whole code is doing. Please break this down.

Body:
arr.splice(0,size)

Array.splice will remove elements from index 0 up till size and return them as a new array.

newArr.push(arr.splice(0,size));

The returned array is then pushed to newArr.

while (arr.length)

Array.splice will also mutate the original array so the arr will eventually becomes empty and the loop will end.


问:
Converting Python 3 String of Bytes of Unicode - `str(utf8_encoded_str)` back to unicode
Well, let me introduce the problem first.

I've got some data via POST/GET requests. The data were UTF-8 encoded string. Little did I know that, and converted it just by str() method. And now I have full database of "nonsense data" and couldn't find a way back.

Example code:

unicode_str - this is the string I should obtain

encoded_str - this is the string I got with POST/GET requests - initial data

bad_str - the data I have in the Database at the moment and I need to get unicode from.

So apparently I know how to convert:
unicode_str =(encode)=> encoded_str =(str)=> bad_str

But I couldn't come up with solution back:
bad_str =(???)=> encoded_str =(decode)=> unicode_str

```<code>In [1]: unicode_str = 'Příliš žluťoučký kůň úpěl ďábelské ódy'

In [2]: unicode_str
Out[2]: 'Příliš žluťoučký kůň úpěl ďábelské ódy'

In [3]: encoded_str = unicode_str.encode("UTF-8")

In [4]: encoded_str
Out[4]: b'P\xc5\x99\xc3\xadli\xc5\xa1 \xc5\xbelu\xc5\xa5ou\xc4\x8dk\xc3\xbd k\xc5\xaf\xc5\x88 \xc3\xbap\xc4\x9bl \xc4\x8f\xc3\xa1belsk\xc3\xa9 \xc3\xb3dy'

In [5]: bad_str = str(encoded_str)

In [6]: bad_str
Out[6]: "b'P\\xc5\\x99\\xc3\\xadli\\xc5\\xa1 \\xc5\\xbelu\\xc5\\xa5ou\\xc4\\x8dk\\xc3\\xbd k\\xc5\\xaf\\xc5\\x88 \\xc3\\xbap\\xc4\\x9bl \\xc4\\x8f\\xc3\\xa1belsk\\xc3\\xa9 \\xc3\\xb3dy'"

In [7]: new_encoded_str = some_magical_function_here(bad_str) ???
</code>```

答:
Please do not use eval, instead:</p>

```<code>import codecs
s = 'žluťoučký'
x = str(s.encode('utf-8'))

# strip quotes
x = x[2:-1]

# unescape
x = codecs.escape_decode(x)[0].decode('utf-8')

# profit
x == s
</code>```

Body:
Well, let me introduce the problem first.

I've got some data via POST/GET requests. The data were UTF-8 encoded string. Little did I know that, and converted it just by str() method. And now I have full database of "nonsense data" and couldn't find a way back.

Example code:

unicode_str - this is the string I should obtain

encoded_str - this is the string I got with POST/GET requests - initial data

bad_str - the data I have in the Database at the moment and I need to get unicode from.

So apparently I know how to convert:
unicode_str =(encode)=> encoded_str =(str)=> bad_str

But I couldn't come up with solution back:
bad_str =(???)=> encoded_str =(decode)=> unicode_str

In [1]: unicode_str = 'Příliš žluťoučký kůň úpěl ďábelské ódy'

In [2]: unicode_str
Out[2]: 'Příliš žluťoučký kůň úpěl ďábelské ódy'

In [3]: encoded_str = unicode_str.encode("UTF-8")

In [4]: encoded_str
Out[4]: b'P\xc5\x99\xc3\xadli\xc5\xa1 \xc5\xbelu\xc5\xa5ou\xc4\x8dk\xc3\xbd k\xc5\xaf\xc5\x88 \xc3\xbap\xc4\x9bl \xc4\x8f\xc3\xa1belsk\xc3\xa9 \xc3\xb3dy'

In [5]: bad_str = str(encoded_str)

In [6]: bad_str
Out[6]: "b'P\\xc5\\x99\\xc3\\xadli\\xc5\\xa1 \\xc5\\xbelu\\xc5\\xa5ou\\xc4\\x8dk\\xc3\\xbd k\\xc5\\xaf\\xc5\\x88 \\xc3\\xbap\\xc4\\x9bl \\xc4\\x8f\\xc3\\xa1belsk\\xc3\\xa9 \\xc3\\xb3dy'"

In [7]: new_encoded_str = some_magical_function_here(bad_str) ???

Body:
Please do not use eval, instead:

import codecs
s = 'žluťoučký'
x = str(s.encode('utf-8'))

# strip quotes
x = x[2:-1]

# unescape
x = codecs.escape_decode(x)[0].decode('utf-8')

# profit
x == s


问:
Vue.js - emit only if the event hasn't been already been sent
I have a search input.

Each keystroke on this input emit an event "search" ($emit Vue.js function).

I have another component listening on this event ($on Vue.js function), then call a search web service and display the result.

(the events are send on a bus, here a simple Vue instance).

This works well.

I want to emit the search event only if no key press has been made for a delay, let's say 200ms.
That way, if I quicly type a word in the search input, only one event will be sent. And if I'm slow, I still will have search results while typing.

How can I achieve that ?

答:
I'm using underscore's .debounce() method for these purposes. Demo:

new Vue({
  el: '#app',
  data: {
    query: ''
  },
  methods: {
    updateQuery: _.debounce(function (evt) {
      this.query = evt.target.value
      // Call your AJAX here. For example:
      // if (this.query.length) this.$store.dispatch('loadItems')
    }, 300),
    clearQuery () {
      this.query = ''
    }
  }
})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>[v-cloak] {
  display: none;
}</code>```

  <input
    type="text"
    @input="updateQuery"
    :value="query"
    placehorder="search..."
  >
  <button @click="clearQuery">clear</button>

You are looking for {{ query }}

```
</div>
</div>
</p>

<p>If you want to be more effective, use Lodash. It is the same thing, but Lodash is modular, so you can add to your project only modules you need, and not the complete library. For .debounce() method is there separate javascript:</p>

```
```

Body:
I'm using underscore's .debounce() method for these purposes. Demo:

new Vue({
  el: '#app',
  data: {
    query: ''
  },
  methods: {
    updateQuery: _.debounce(function (evt) {
      this.query = evt.target.value
      // Call your AJAX here. For example:
      // if (this.query.length) this.$store.dispatch('loadItems')
    }, 300),
    clearQuery () {
      this.query = ''
    }
  }
})

[v-cloak] {
  display: none;
}

<div id="app">
  <input
    type="text"
    @input="updateQuery"
    :value="query"
    placehorder="search..."
  >
  <button @click="clearQuery">clear</button>
  <p v-cloak>You are looking for {{ query }}</p>
</div>

<script src="https://unpkg.com/underscore@1.8.3/underscore-min.js"></script>
<script src="https://unpkg.com/vue@2.4.4/dist/vue.min.js"></script>

If you want to be more effective, use Lodash. It is the same thing, but Lodash is modular, so you can add to your project only modules you need, and not the complete library. For .debounce() method is there separate javascript:

<script src="https://unpkg.com/lodash@4.17.4/debounce.js"></script>


问:
TextField loses focus to other window
Within a java-swing application, I have a textfield with some kind of help-popup.

I.e., when the user double clicks with the mouse within the textfield, this popup (implemented as an undecorated JFrame) is shown.

As soon as the textfield loses the focus, this popup is hidden again.

The problem is that showing this popup, the focus moves automatically to that frame, firing a lostFocus event on the textfield. This of course, closes the popup again.

I would like the lostFocus event to be triggered only if the textfield loses its focus to another component within the same window.

Any idea how to accomplish this?

答:
The solution is easier than I thought:

Within the focusLost callback, check the isTemporary() flag.

If set, ignore the event.

UPDATE:

If the ifTemporary() flag is set, determine the component that gains the focus (by means of getOppositeComponent()).

If that component if null, or its parent window is not our popup frame, than close the popup anyway.

Title: TextField loses focus to other window


问:
How to add Relationship of Factories to faker in Laravel
I have models like this:

```<code>Entity - entities table
Address - address table
User - users table
Geoloc - geoloc table
UserEntity - entity_user table
</code>```

Now Entity can have one address and one geoloc, but it can have multiple users this is what UserEntity is for.

So I need to do a pattern where factory will create it like this:

User>Entity>Address>Geoloc>UserEntity

so when user is created it will also create entity, address and geoloc, associate entity id to address, associate geoloc id to entity and insert user_id and entity_id to user entity.

Here's my current setup:

AddressFactory:

```<code>$factory->define(App\Address::class, function (Faker $faker) {
    return [
        'building_name' => $faker->company,
        'address' => $faker->streetAddress,
        'town' => $faker->city,
        'postcode' => $faker->postcode,
        'telephone' => $faker->phoneNumber,
        'private' => $faker->boolean($chanceOfGettingTrue = 50),
        'entity_id' => function () {
            return factory(App\Entity::class)->create()->id;
        }
    ];
});
</code>```

EntityFactory:

```<code>factory->define(App\Entity::class, function (Faker $faker) {
    return [
        'name' => $faker->unique()->company,
        'type' => 'Service',
        'tags' => 'mens clothes, online shopping, ladies clothes',
        'email' => $faker->safeEmail,
        'logo' => $faker->imageUrl($width = 640, $height = 480),
        'cover' => $faker->imageUrl($width = 1000, $height = 600),
        'bio' => $faker->catchPhrase,
        'main' => $faker->realText($maxNbChars = 200, $indexSize = 2),
        'twitter_business' => 'OfficialOAFC',
        'facebook_business' => 'MolinoLounge',
        'instagram_business' => 'OfficialOAFC',
        'google_places' => 'ChIJvaCBHYG3e0gRfhs0xZ1TBB8',
        'eventbrite' =>'8252340832',
        'featured' => $faker->boolean($chanceOfGettingTrue = 50),
        'url' => $faker->url,
        'video' => '6R2DIFySho4',
        'wikipedia' => 'Hackerspace',
        'contact_name' => $faker->name,
        'contact_number' => $faker->phoneNumber,
        'geoloc_id' => function () {
            return factory(App\Geoloc::class)->create()->id;
        }
    ];
});
</code>```

UserFactory:

```<code>$factory->define(App\User::class, function (Faker $faker) {
    static $password;
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('secret'),
        'avatar' => $faker->imageUrl($width = 640, $height = 480),
        //'telephone' => $faker->phoneNumber,
        'role' => rand(1, 2),
        'remember_token' => str_random(10),
    ];
});
</code>```

DatabaseSeeder:

```<code>    factory(App\User::class, 30)->create();
    factory(App\Address::class, 30)->create();
</code>```

User relations:

```<code>public function entities()
{
    return $this->belongsToMany('App\Entity', 'entity_user', 'user_id', 'entity_id');
}
</code>```

Entity relations:

```<code>public function address()
{
    return $this->hasOne('App\Address', 'entity_id');
}
public function _geoloc()
{
    return $this->belongsTo('App\Geoloc', 'geoloc_id', 'id');
}
</code>```

答:
You should do this on the seeder.

For example:

```<code>public function run()
{
    factory(App\Currency::class, 100)->create()->each(function ($currency) {
        $currency->variations()->saveMany(factory(App\Variation::class, 50)->make());
    });
}
</code>```

Body:
I have models like this:

Entity - entities table
Address - address table
User - users table
Geoloc - geoloc table
UserEntity - entity_user table

Now Entity can have one address and one geoloc, but it can have multiple users this is what UserEntity is for.

So I need to do a pattern where factory will create it like this:

User>Entity>Address>Geoloc>UserEntity

so when user is created it will also create entity, address and geoloc, associate entity id to address, associate geoloc id to entity and insert user_id and entity_id to user entity.

Here's my current setup:

AddressFactory:

$factory->define(App\Address::class, function (Faker $faker) {
    return [
        'building_name' => $faker->company,
        'address' => $faker->streetAddress,
        'town' => $faker->city,
        'postcode' => $faker->postcode,
        'telephone' => $faker->phoneNumber,
        'private' => $faker->boolean($chanceOfGettingTrue = 50),
        'entity_id' => function () {
            return factory(App\Entity::class)->create()->id;
        }
    ];
});

EntityFactory:

factory->define(App\Entity::class, function (Faker $faker) {
    return [
        'name' => $faker->unique()->company,
        'type' => 'Service',
        'tags' => 'mens clothes, online shopping, ladies clothes',
        'email' => $faker->safeEmail,
        'logo' => $faker->imageUrl($width = 640, $height = 480),
        'cover' => $faker->imageUrl($width = 1000, $height = 600),
        'bio' => $faker->catchPhrase,
        'main' => $faker->realText($maxNbChars = 200, $indexSize = 2),
        'twitter_business' => 'OfficialOAFC',
        'facebook_business' => 'MolinoLounge',
        'instagram_business' => 'OfficialOAFC',
        'google_places' => 'ChIJvaCBHYG3e0gRfhs0xZ1TBB8',
        'eventbrite' =>'8252340832',
        'featured' => $faker->boolean($chanceOfGettingTrue = 50),
        'url' => $faker->url,
        'video' => '6R2DIFySho4',
        'wikipedia' => 'Hackerspace',
        'contact_name' => $faker->name,
        'contact_number' => $faker->phoneNumber,
        'geoloc_id' => function () {
            return factory(App\Geoloc::class)->create()->id;
        }
    ];
});

UserFactory:

$factory->define(App\User::class, function (Faker $faker) {
    static $password;
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('secret'),
        'avatar' => $faker->imageUrl($width = 640, $height = 480),
        //'telephone' => $faker->phoneNumber,
        'role' => rand(1, 2),
        'remember_token' => str_random(10),
    ];
});

DatabaseSeeder:

    factory(App\User::class, 30)->create();
    factory(App\Address::class, 30)->create();

User relations:

public function entities()
{
    return $this->belongsToMany('App\Entity', 'entity_user', 'user_id', 'entity_id');
}

Entity relations:

public function address()
{
    return $this->hasOne('App\Address', 'entity_id');
}
public function _geoloc()
{
    return $this->belongsTo('App\Geoloc', 'geoloc_id', 'id');
}

Body:
You should do this on the seeder.

For example:

public function run()
{
    factory(App\Currency::class, 100)->create()->each(function ($currency) {
        $currency->variations()->saveMany(factory(App\Variation::class, 50)->make());
    });
}


问:
How do I get the difference between 2 large sets in .net
I need to get the set of GUIDs in a remote database which do not exist in an IEnumerable (for context, this is coming from a Lucene index). There are potentially many millions of these Guids.

I currently think that inserting the IEnumerable to the database and doing the difference there will be too expensive (the inserts will hammer the database), but I am prepared to be proven wrong!

Reading both sets into memory is also infeasible due to the amount of data - our existing solution does this and fails with very large sets.

I would like a solution which can operate on a small subset of the data at a time so that we have a constant memory footprint. We have an idea as to how to roll our own implementation of this, but it is non-trivial, so would obviously rather use an existing one if it exists.

If anybody has any recommendations for an existing solution, I'd be grateful to hear them!

答: You could use SqlBulkCopy to load the guids very fast to the database(if it is SQL-Server).</p>

ContentLicense: CC BY-SA 2.5


问:
cannot declare a body because it is marked abstract
Hi i'm new in C# console application and i'm using abstract and override but i get stack in the first method in public abstract double Compute() i got an error and it says cannot declare a body because it is marked abstract please help me. thank you!

`

```<code>abstract class Cake
    {
        public string _flavor, _size;
        public int _quantity;

        public Cake(string flavor, string size, int quantity)
        {
            _flavor = flavor;
            _size = size;
            _quantity = quantity;
        }

        public abstract double Compute()
        {
            double price;
            if(_flavor == "Chocolate" && _size == "Regular")
            {
               price = 250.50;
            }
            else if (_flavor == "Chocolate" && _size == "Large")
            {
                price = 450.50;
            }
            else if (_flavor == "Strawberry" && _size == "Regular")
            {
                price = 300.50;
            }
            else
            {
                price = 500.75;
            }
            return price;
        }
    }

    class BirthdayCake:Cake
    {
        public int _numOfCandles;

        public BirthdayCake(string flavor, string size, int quantity, int numOfCandles):base(flavor,size,quantity)
        {
            _numOfCandles = numOfCandles;
        }

        public override double Compute()
        {
            return _numOfCandles * 10.00;
        }
    }`
</code>```

答: Use virtual instead of abstract when you have a default implementation but would like to allow sub-classes to override

Body:
Hi i'm new in C# console application and i'm using abstract and override but i get stack in the first method in public abstract double Compute() i got an error and it says cannot declare a body because it is marked abstract please help me. thank you!

`

abstract class Cake
    {
        public string _flavor, _size;
        public int _quantity;

        public Cake(string flavor, string size, int quantity)
        {
            _flavor = flavor;
            _size = size;
            _quantity = quantity;
        }

        public abstract double Compute()
        {
            double price;
            if(_flavor == "Chocolate" && _size == "Regular")
            {
               price = 250.50;
            }
            else if (_flavor == "Chocolate" && _size == "Large")
            {
                price = 450.50;
            }
            else if (_flavor == "Strawberry" && _size == "Regular")
            {
                price = 300.50;
            }
            else
            {
                price = 500.75;
            }
            return price;
        }
    }

    class BirthdayCake:Cake
    {
        public int _numOfCandles;

        public BirthdayCake(string flavor, string size, int quantity, int numOfCandles):base(flavor,size,quantity)
        {
            _numOfCandles = numOfCandles;
        }

        public override double Compute()
        {
            return _numOfCandles * 10.00;
        }
    }`


问:
Remove (or replace) items in a multi-level list based on one of the parameters inside
```<code>population=[[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [4], [0]],
[[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [3], [1]],
[[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [4], [2]],
[[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [1], [3]]]

selected_chromosomes=[[[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [5], [2]],
[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [3], [0]]]

child1=[0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0]
child2=[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1]

def PopulationAdjustment(population, selected_chromosomes):
    for game in range(0, len(selected_chromosomes)):
        if game in selected_chromosomes[game][2]==game in population[game][2]:
            population.remove(game)
    return population
</code>```

So the objective here is to replace the parents for the children in a population (list), my approach was to delete the parents then append the children, based on the same counter. The structure of the list is [[chromosome],[fitness],[counter]], however they are not exactly the same since I manipulated the fitness during the selection to avoid 0 probabilities.

I am trying to index the items that have the same counter and delete them from the list, then the next step would be just to append the children.

Ive been trying some different ways but I couldnt get it working properly, any thoughts on how to fix that? Also, if there is a way of replacing them directly by the children without having to perform 2 steps (remove and append) it would be aslo very welcome. Thanks!!

答:
You said "I am trying to index the items that have the same counter and delete them from the list". While that's possible, it's easier (and faster) to just build a new list that contains the chromosomes that you want to keep, unless population is huge.

We first scan the selected_chromosomes to extract their counter numbers into a set so we can look them up quickly.

```<code>population=[
    [[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [4], [0]],
    [[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [3], [1]],
    [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [4], [2]],
    [[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [1], [3]],
]

selected_chromosomes=[
    [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [5], [2]],
    [[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [3], [0]],
]

def population_adjustment(population, selected_chromosomes):
    # Create a set of the counter numbers to remove
    drop = {u[-1][0] for u in selected_chromosomes}

    # Copy the wanted chromosomes to a new list
    return [u for u in population if u[-1][0] not in drop]

new_pop = population_adjustment(population, selected_chromosomes)
for row in new_pop:
    print(row)
</code>```

output

```<code>[[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [3], [1]]
[[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [1], [3]]
</code>```

If the population list is huge, or you have some other reason to keep the original list (eg, there are multiple references to it in various places), here's how to delete the unwanted lists. We have to be careful, though. Removing items from a list that you're iterating over is dangerous, since removal disturbs the indices of the remaining list items, as shown here. It's a bit like cutting a tree branch that you're sitting on. If you cut in the wrong place, Bad Things happen. ;) The simplest way is to iterate over the list in reverse.

```<code>population=[
    [[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [4], [0]],
    [[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [3], [1]],
    [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [4], [2]],
    [[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [1], [3]],
]

selected_chromosomes=[
    [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [5], [2]],
    [[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [3], [0]],
]

def population_adjustment(population, selected_chromosomes):
    # Create a set of the counter numbers to remove
    drop = {u[-1][0] for u in selected_chromosomes}

    # Iterate backwards over population so we can safely delete sublists
    for i in range(len(population)-1, -1, -1):
        k = population[i][-1][0]
        if k in drop:
           del population[i]

    # Since we mutate `population` we should return `None`, as is conventional in Python.
    # This return statement isn't necessary, since `None` is the default return value,
    # but it's nice to be explicit
    return None

population_adjustment(population, selected_chromosomes)
for row in population:
    print(row)
</code>```

This code produces the same output as the previous version, so I won't repeat it.

Body:
population=[[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [4], [0]],
[[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [3], [1]],
[[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [4], [2]],
[[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [1], [3]]]

selected_chromosomes=[[[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [5], [2]],
[[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [3], [0]]]

child1=[0, 1, 1, 0, 1, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0]
child2=[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1]

def PopulationAdjustment(population, selected_chromosomes):
    for game in range(0, len(selected_chromosomes)):
        if game in selected_chromosomes[game][2]==game in population[game][2]:
            population.remove(game)
    return population

So the objective here is to replace the parents for the children in a population (list), my approach was to delete the parents then append the children, based on the same counter. The structure of the list is [[chromosome],[fitness],[counter]], however they are not exactly the same since I manipulated the fitness during the selection to avoid 0 probabilities.

I am trying to index the items that have the same counter and delete them from the list, then the next step would be just to append the children.

Ive been trying some different ways but I couldnt get it working properly, any thoughts on how to fix that? Also, if there is a way of replacing them directly by the children without having to perform 2 steps (remove and append) it would be aslo very welcome. Thanks!!

Body:
You said "I am trying to index the items that have the same counter and delete them from the list". While that's possible, it's easier (and faster) to just build a new list that contains the chromosomes that you want to keep, unless population is huge.

We first scan the selected_chromosomes to extract their counter numbers into a set so we can look them up quickly.

population=[
    [[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [4], [0]],
    [[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [3], [1]],
    [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [4], [2]],
    [[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [1], [3]],
]

selected_chromosomes=[
    [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [5], [2]],
    [[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [3], [0]],
]

def population_adjustment(population, selected_chromosomes):
    # Create a set of the counter numbers to remove
    drop = {u[-1][0] for u in selected_chromosomes}

    # Copy the wanted chromosomes to a new list
    return [u for u in population if u[-1][0] not in drop]

new_pop = population_adjustment(population, selected_chromosomes)
for row in new_pop:
    print(row)

output

[[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [3], [1]]
[[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [1], [3]]

If the population list is huge, or you have some other reason to keep the original list (eg, there are multiple references to it in various places), here's how to delete the unwanted lists. We have to be careful, though. Removing items from a list that you're iterating over is dangerous, since removal disturbs the indices of the remaining list items, as shown here. It's a bit like cutting a tree branch that you're sitting on. If you cut in the wrong place, Bad Things happen. ;) The simplest way is to iterate over the list in reverse.

population=[
    [[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [4], [0]],
    [[0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0, 1], [3], [1]],
    [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [4], [2]],
    [[1, 0, 0, 1, 1, 1, 0, 0, 1, 1, 0, 1, 1, 0, 0, 0], [1], [3]],
]

selected_chromosomes=[
    [[0, 1, 1, 0, 1, 1, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0], [5], [2]],
    [[0, 0, 1, 0, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 1], [3], [0]],
]

def population_adjustment(population, selected_chromosomes):
    # Create a set of the counter numbers to remove
    drop = {u[-1][0] for u in selected_chromosomes}

    # Iterate backwards over population so we can safely delete sublists
    for i in range(len(population)-1, -1, -1):
        k = population[i][-1][0]
        if k in drop:
           del population[i]

    # Since we mutate `population` we should return `None`, as is conventional in Python.
    # This return statement isn't necessary, since `None` is the default return value,
    # but it's nice to be explicit
    return None

population_adjustment(population, selected_chromosomes)
for row in population:
    print(row)

This code produces the same output as the previous version, so I won't repeat it.


问:
not getting the desired output from an array
I need to create an dynamic array and can't get it right.
I need something like this:

Product Name

top

White

Black

Bottom

Red

Green

I came up with this code, which is producing the above text, so my logic must be about right.

```<code>$set = array();
$set['name'] = "Product Name";

$options = array("top", "bottom");
$values['top'] = array("White", "Black");
$values['bottom'] = array("Red", "Green");

echo "```".$set['name']."```";
foreach ($options as $o) {
    echo "```- $o```";
    $set['options'][]['name'] = $o;

    foreach ($values[$o] as $v) {
        echo "```-- $v```";
        $set['options'][]['values']['name'] = $v;
    }
}
</code>```

The array that is created with the above code is:

```<code>Array
(
  [name] => Product Name
  [options] => Array
  (
    [0] => Array
    (
     [name] => top
    )
[1] => Array
                (
                    [values] => Array
                        (
                            [name] => White
                        )

                )

            [2] => Array
                (
                    [values] => Array
                        (
                            [name] => Black
                        )

                )

            [3] => Array
                (
                    [name] => bottom
                )

            [4] => Array
                (
                    [values] => Array
                        (
                            [name] => Red
                        )

                )

            [5] => Array
                (
                    [values] => Array
                        (
                            [name] => Green
                        )
                )
        )
)
</code>```

THe output I want is:

```<code>Array
(
    [name] => Product Name
    [options] => Array
        (
            [0] => Array
                (
                    [name] => top
                    [values] => Array
                        (
                            [0] => Array
                                (
                                    [name] => White
                                )

                            [1] => Array
                                (
                                    [name] => Black
                                )

                        )

                )

            [1] => Array
                (
                    [name] => bottom
                    [values] => Array
                        (
                            [0] => Array
                                (
                                    [name] => Red
                                )

                            [1] => Array
                                (
                                    [name] => Green
                                )

                        )

                )

        )

)
</code>```

What am I missing ?

答:
You got

```<code>$set['options'][]['name'] = $o;
                ^
             this one
</code>```

and

```<code>$set['options'][]['values']['name'] = $v;
                ^
             This one
</code>```

in outer as well as inner loop which was adding new item to array (so there were indexes like 0, 1, 2 ...) so could not produce what you wanted.

You may correct your array like below:

 Demo

```<code><?php

$set = array();
$set['name'] = "Product Name";

$options = array("top", "bottom");
$values['top'] = array("White", "Black");
$values['bottom'] = array("Red", "Green");

echo "```".$set['name']."```";
foreach ($options as $o) {
    echo "```- $o```";

    $vals = array();
    foreach ($values[$o] as $v) {
        echo "```-- $v```";
         $vals[] = array('name' => $v );
    }
     $set['options'][] = array('name' => $o, 'values' => $vals );

}

print_r($set);

?>
</code>```

Body:
I need to create an dynamic array and can't get it right.
I need something like this:

Product Name

top

White

Black

Bottom

Red

Green

I came up with this code, which is producing the above text, so my logic must be about right.

$set = array();
$set['name'] = "Product Name";

$options = array("top", "bottom");
$values['top'] = array("White", "Black");
$values['bottom'] = array("Red", "Green");

echo "
".$set['name']."
";
foreach ($options as $o) {
    echo "
- $o
";
    $set['options'][]['name'] = $o;

    foreach ($values[$o] as $v) {
        echo "
-- $v
";
        $set['options'][]['values']['name'] = $v;
    }
}

The array that is created with the above code is:

Array
(
  [name] => Product Name
  [options] => Array
  (
    [0] => Array
    (
     [name] => top
    )
[1] => Array
                (
                    [values] => Array
                        (
                            [name] => White
                        )

                )

            [2] => Array
                (
                    [values] => Array
                        (
                            [name] => Black
                        )

                )

            [3] => Array
                (
                    [name] => bottom
                )

            [4] => Array
                (
                    [values] => Array
                        (
                            [name] => Red
                        )

                )

            [5] => Array
                (
                    [values] => Array
                        (
                            [name] => Green
                        )
                )
        )
)

THe output I want is:

Array
(
    [name] => Product Name
    [options] => Array
        (
            [0] => Array
                (
                    [name] => top
                    [values] => Array
                        (
                            [0] => Array
                                (
                                    [name] => White
                                )

                            [1] => Array
                                (
                                    [name] => Black
                                )

                        )

                )

            [1] => Array
                (
                    [name] => bottom
                    [values] => Array
                        (
                            [0] => Array
                                (
                                    [name] => Red
                                )

                            [1] => Array
                                (
                                    [name] => Green
                                )

                        )

                )

        )

)

What am I missing ?

Body:
You got

$set['options'][]['name'] = $o;
                ^
             this one

and

$set['options'][]['values']['name'] = $v;
                ^
             This one

in outer as well as inner loop which was adding new item to array (so there were indexes like 0, 1, 2 ...) so could not produce what you wanted.

You may correct your array like below:

 Demo

<?php

$set = array();
$set['name'] = "Product Name";

$options = array("top", "bottom");
$values['top'] = array("White", "Black");
$values['bottom'] = array("Red", "Green");

echo "<pre>".$set['name']."</pre>";
foreach ($options as $o) {
    echo "<pre>- $o</pre>";

    $vals = array();
    foreach ($values[$o] as $v) {
        echo "<pre>-- $v</pre>";
         $vals[] = array('name' => $v );
    }
     $set['options'][] = array('name' => $o, 'values' => $vals );

}

print_r($set);

?>


问:
How to hook into event fired from grandchild control?
Consider a hierachy like the following:

```<code>Parent Grid -> Detail Grid -> Detail of Detail Grid
</code>```

Where each contains the grid following it. Now, I want to fire an event from Detail of Detail Grid. I've set up my handler and events as follows.

```<code>public static readonly RoutedEvent DetailofDetailVmClickedEvent =
   EventManager.RegisterRoutedEvent("DetailofDetailVmClicked", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(RepoBreakdownRecordControl));

public event RoutedEventHandler DetailofDetailVmClicked
{
   add { AddHandler(DetailofDetailVmClickedEvent, value); }
   remove { RemoveHandler(DetailofDetailVmClickedEvent, value); }
}

public void RaiseDetailofDetailVmClickedEvent()
{
   var args = new RoutedEventArgs(DetailofDetailVmClickedEvent);
   args.Source = MyDetailOfDetailGrid.GetFocusedRow() as DetailofDetailVm;
   RaiseEvent(args);
}

private void MyDetailOfDetailGrid_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
   RaiseDetailofDetailVmClickedEvent();
}
</code>```

I want to handle this at the Parent Grid level. Since I can't hook directly into the Detail of Detail Grid event handler (as Parent Grid, Detail Grid, and Detail of Detail Grid are all their own controls), how can I accomplish this?

I will happily admit I'm probably having a brainfart from lack of coffee, but such is life.

答:
Sigh. Time for some coffee.

I just needed to add the following to Parent Grid's constructor.

```<code>public ParentGridControl()
{
    AddHandler(DetailOfDetailGridControl.DetailofDetailVmClicked, new RoutedEventHandler(DetailofDetailVmClicked_Handler));
}

private void DetailofDetailVmClicked_Handler(object sender, RoutedEventArgs routedEventArgs)
{
   // do things here
}
</code>```

Body:
Consider a hierachy like the following:

Parent Grid -> Detail Grid -> Detail of Detail Grid

Where each contains the grid following it. Now, I want to fire an event from Detail of Detail Grid. I've set up my handler and events as follows.

public static readonly RoutedEvent DetailofDetailVmClickedEvent =
   EventManager.RegisterRoutedEvent("DetailofDetailVmClicked", RoutingStrategy.Bubble, typeof(RoutedEventHandler), typeof(RepoBreakdownRecordControl));

public event RoutedEventHandler DetailofDetailVmClicked
{
   add { AddHandler(DetailofDetailVmClickedEvent, value); }
   remove { RemoveHandler(DetailofDetailVmClickedEvent, value); }
}

public void RaiseDetailofDetailVmClickedEvent()
{
   var args = new RoutedEventArgs(DetailofDetailVmClickedEvent);
   args.Source = MyDetailOfDetailGrid.GetFocusedRow() as DetailofDetailVm;
   RaiseEvent(args);
}

private void MyDetailOfDetailGrid_OnMouseDoubleClick(object sender, MouseButtonEventArgs e)
{
   RaiseDetailofDetailVmClickedEvent();
}

I want to handle this at the Parent Grid level. Since I can't hook directly into the Detail of Detail Grid event handler (as Parent Grid, Detail Grid, and Detail of Detail Grid are all their own controls), how can I accomplish this?

I will happily admit I'm probably having a brainfart from lack of coffee, but such is life.

Body:
Sigh. Time for some coffee.

I just needed to add the following to Parent Grid's constructor.

public ParentGridControl()
{
    AddHandler(DetailOfDetailGridControl.DetailofDetailVmClicked, new RoutedEventHandler(DetailofDetailVmClicked_Handler));
}

private void DetailofDetailVmClicked_Handler(object sender, RoutedEventArgs routedEventArgs)
{
   // do things here
}


问:
Android: button click event not working for simple multiplication app
Good Day,

I am new to android and using Eclipse 3.7.2. I have been following examples on the net (the so-called "add two numbers" examples but, after discovering that AbsoluteLayout is deprecated, I am using RelativeLayout and basically going from scratch. The app basically is supposed to take two numbers (how far a guy went and how much he is paid per mile) and pop out total pay.

The app compiles fine and starts up in the emulator. I get excited! Pop in 2 numbers and hit the button. Nothing. I look and see that there's no errors happening.

Am I missing something with my button listener? Here is the Java code I've put in (updated 5:27pm 10.31.2012):

```<code>package com.example.wing_it;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
EditText mile,driver;
Button button1;
TextView tv;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mile= (EditText) findViewById(R.id.mile);
    button1 = (Button) findViewById(R.id.button1);
    tv = (TextView) findViewById(R.id.pay);
    driver= (EditText) findViewById(R.id.driver);
    button1.setOnClickListener((OnClickListener) this);
    }

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
class clicker implements Button.OnClickListener
{
public void onClick(View v) {
    // TODO Auto-generated method stub
    {
        String a,b;
        Integer vis;
        a = mile.getText().toString();
        b = driver.getText().toString();
        vis = Integer.parseInt(a)*Integer.parseInt(b);
        tv.setText(vis.toString());
        }
    }
}
}
</code>```

The XML code is as such:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="@string/miles"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="40dp"
    android:text="@string/paypermile"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView2"
    android:layout_marginLeft="52dp"
    android:layout_marginTop="62dp"
    android:layout_toRightOf="@+id/textView2"
    android:text="@string/compute" />

<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/button1"
    android:layout_marginTop="46dp"
    android:text="@string/pay"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
    android:id="@+id/mile"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/button1"
    android:ems="10"
    android:inputType="numberDecimal" >

    <requestFocus />
</EditText>

<EditText
    android:id="@+id/driver"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView2"
    android:layout_alignBottom="@+id/textView2"
    android:layout_alignLeft="@+id/mile"
    android:layout_alignParentRight="true"
    android:ems="10"
    android:inputType="numberDecimal" />

<TextView
    android:id="@+id/pay"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView3"
    android:layout_alignBottom="@+id/textView3"
    android:layout_alignParentRight="true"
    android:text="@string/totalpay"
    android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>
</code>```

Here is the manifest:

```<code><manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.wing_it"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="7"
    android:targetSdkVersion="15" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
 </application>

</manifest>
</code>```

I have the value of the result textview set to nothing (just a blank) in the strings.xml. It was set to '0' and I removed that to see if it would make a difference. Still, nothing.

Is there something I am overlooking here? Thank you for looking. :)

答: Sometimes there's a bug in Android Studio itself. Close it and restart it and RUN your app again. It should work.</p>

Body:
Good Day,

I am new to android and using Eclipse 3.7.2. I have been following examples on the net (the so-called "add two numbers" examples but, after discovering that AbsoluteLayout is deprecated, I am using RelativeLayout and basically going from scratch. The app basically is supposed to take two numbers (how far a guy went and how much he is paid per mile) and pop out total pay.

The app compiles fine and starts up in the emulator. I get excited! Pop in 2 numbers and hit the button. Nothing. I look and see that there's no errors happening.

Am I missing something with my button listener? Here is the Java code I've put in (updated 5:27pm 10.31.2012):

package com.example.wing_it;

import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends Activity {
EditText mile,driver;
Button button1;
TextView tv;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mile= (EditText) findViewById(R.id.mile);
    button1 = (Button) findViewById(R.id.button1);
    tv = (TextView) findViewById(R.id.pay);
    driver= (EditText) findViewById(R.id.driver);
    button1.setOnClickListener((OnClickListener) this);
    }

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}
class clicker implements Button.OnClickListener
{
public void onClick(View v) {
    // TODO Auto-generated method stub
    {
        String a,b;
        Integer vis;
        a = mile.getText().toString();
        b = driver.getText().toString();
        vis = Integer.parseInt(a)*Integer.parseInt(b);
        tv.setText(vis.toString());
        }
    }
}
}

The XML code is as such:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:text="@string/miles"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<TextView
    android:id="@+id/textView2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/textView1"
    android:layout_marginTop="40dp"
    android:text="@string/paypermile"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<Button
    android:id="@+id/button1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@+id/textView2"
    android:layout_marginLeft="52dp"
    android:layout_marginTop="62dp"
    android:layout_toRightOf="@+id/textView2"
    android:text="@string/compute" />

<TextView
    android:id="@+id/textView3"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_below="@+id/button1"
    android:layout_marginTop="46dp"
    android:text="@string/pay"
    android:textAppearance="?android:attr/textAppearanceMedium" />

<EditText
    android:id="@+id/mile"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:layout_toRightOf="@+id/button1"
    android:ems="10"
    android:inputType="numberDecimal" >

    <requestFocus />
</EditText>

<EditText
    android:id="@+id/driver"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView2"
    android:layout_alignBottom="@+id/textView2"
    android:layout_alignLeft="@+id/mile"
    android:layout_alignParentRight="true"
    android:ems="10"
    android:inputType="numberDecimal" />

<TextView
    android:id="@+id/pay"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/textView3"
    android:layout_alignBottom="@+id/textView3"
    android:layout_alignParentRight="true"
    android:text="@string/totalpay"
    android:textAppearance="?android:attr/textAppearanceLarge" />

</RelativeLayout>

Here is the manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.wing_it"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="7"
    android:targetSdkVersion="15" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name=".MainActivity"
        android:label="@string/title_activity_main" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
 </application>

</manifest>

I have the value of the result textview set to nothing (just a blank) in the strings.xml. It was set to '0' and I removed that to see if it would make a difference. Still, nothing.

Is there something I am overlooking here? Thank you for looking. :)


答:
As said, you can't declare a body for an abstract function of an abstract class.

You need to create another class herited from your abstract class that declare the body you want.

```<code>abstract class Cake
{
    public string _flavor, _size;
    public int _quantity;
    abstract public double Compute();
}

class BirthdayCake : Cake
{
    public int _numOfCandles;

    public BirthdayCake(string flavor, string size, int quantity, int numOfCandles):base(flavor,size,quantity)
    {
        _numOfCandles = numOfCandles;
    }

    public override double Compute()
    {
        //does your stuff
    }
}
</code>```

Title: cannot declare a body because it is marked abstract

Body:
As said, you can't declare a body for an abstract function of an abstract class.

You need to create another class herited from your abstract class that declare the body you want.

abstract class Cake
{
    public string _flavor, _size;
    public int _quantity;
    abstract public double Compute();
}

class BirthdayCake : Cake
{
    public int _numOfCandles;

    public BirthdayCake(string flavor, string size, int quantity, int numOfCandles):base(flavor,size,quantity)
    {
        _numOfCandles = numOfCandles;
    }

    public override double Compute()
    {
        //does your stuff
    }
}


问:
Clean debug output function?
I want to write an function that will print out error messages/warnings in my program together with the file & line number. There are these two macros in C:

```<code>__FILE__
__LINE__
</code>```

but there's a problem in my opinion... When I'm writing a function like this:

```<code>#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void error(const char *location, const char *msg)
{
#ifdef DEBUG
  printf("Error at %s: %s\n", location, msg);
#endif
}
int main(int , char**)
{
  error(AT, "fake error");
  return 0;
}
</code>```

There are still a lot of useless function calls & trash (the values of __FILE__ and __LINE__ at every call) in the binary file, even if I undefine DEBUG for the release build.
So how can I accomplish this more elegant? I want something like this:

```<code>#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void error(const char *location, const char *msg)
{
  printf("Error at %s: %s\n", location, msg);
}
int main(int , char**)
{
#ifdef DEBUG
  error(AT, "fake error");
#endif
  return 0;
}
</code>```

But not writing #ifdef DEBUG and #endif before and after every function call - that would be too huge for such an task. And remove every  error(AT, "fake error"); call manually isn't really elegant as well...

Any ideas? Maybe inline the function (would not help, wouldn't it)? Some macro or an change of this construct?

答:
you can use this variadic macro to mimic printf which writes file and line no with desired out put.

```<code>#define eprintf(...) do {fprintf(stderr, "%s:%d: ", __FILE__, __LINE__);\
 fprintf(stderr, __VA_ARGS__);} while(0)
</code>```

edit : modified eprintf from the suggestions of jcsalomon

Title: Clean debug output function?

Body:
I want to write an function that will print out error messages/warnings in my program together with the file & line number. There are these two macros in C:

__FILE__
__LINE__

but there's a problem in my opinion... When I'm writing a function like this:

#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void error(const char *location, const char *msg)
{
#ifdef DEBUG
  printf("Error at %s: %s\n", location, msg);
#endif
}
int main(int , char**)
{
  error(AT, "fake error");
  return 0;
}

There are still a lot of useless function calls & trash (the values of __FILE__ and __LINE__ at every call) in the binary file, even if I undefine DEBUG for the release build.
So how can I accomplish this more elegant? I want something like this:

#include <stdio.h>
#define STRINGIFY(x) #x
#define TOSTRING(x) STRINGIFY(x)
#define AT __FILE__ ":" TOSTRING(__LINE__)
void error(const char *location, const char *msg)
{
  printf("Error at %s: %s\n", location, msg);
}
int main(int , char**)
{
#ifdef DEBUG
  error(AT, "fake error");
#endif
  return 0;
}

But not writing #ifdef DEBUG and #endif before and after every function call - that would be too huge for such an task. And remove every  error(AT, "fake error"); call manually isn't really elegant as well...

Any ideas? Maybe inline the function (would not help, wouldn't it)? Some macro or an change of this construct?

Body:
you can use this variadic macro to mimic printf which writes file and line no with desired out put.

#define eprintf(...) do {fprintf(stderr, "%s:%d: ", __FILE__, __LINE__);\
 fprintf(stderr, __VA_ARGS__);} while(0)

edit : modified eprintf from the suggestions of jcsalomon


问:
Trouble formatting images in my CSS
community!
I am having trouble getting the formatting down for a few images I have.

HTML

```<code><footer>
    <section class="socialmedia">
        <a href=""><img src="facebook.png" class="sm"></a>
        <a href=""><img src="twitter.png" class="sm"></a>
        <a href=""><img src="instagram.png" class="sm"></a>
    </section>
</footer>
</code>```

CSS

```<code>.sm {
    display: block;
}

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}

.socialmedia {
    display: block;
    left: 45%;
    float: left;
    width: 2%;
}
</code>```

The images are just lined up vertically to the left of the page, all at the original size. To my understanding the

float: left;

is used to make them horizontal?

Also I would like them to be centered on the page, but margin: auto; is not changing anything either.

EDIT: I would like to have some spacing between each image as well, is there an alternative to

& nbsp;

答:
Note that you want the images to be side-by-side, but you're using the float on the .socialmedia element, which is the container and not the images. So you should change your CSS to:

```<code>.socialmedia {
    display: block;
    left: 45%;
}
.socialmedia img {
    float: left;
}
</code>```

.sm {
    display: block;
}

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}

.socialmedia {
    display: block;
    left: 45%;
}

.socialmedia img {
    float: left;
}

img {
   border:1px solid red;
    height:50px;
    width:50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
    <section class="socialmedia">
        <img src="facebook.png" class="sm">
        <img src="twitter.png" class="sm">
        <img src="instagram.png" class="sm">
    </section>
</footer></code>```

Here you have it on JSFiddle: https://jsfiddle.net/e7j68Lvf/

If you want some space between the images, you can use margin, like this:

```<code>.socialmedia img {
    float: left;
    margin-right: 20px;
}
</code>```

.sm {
    display: block;
}

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}

.socialmedia {
    display: block;
    left: 45%;
}

.socialmedia img {
    float: left;
    margin-right: 20px;
}

img {
   border:1px solid red;
    height:50px;
    width:50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
    <section class="socialmedia">
        <img src="facebook.png" class="sm">
        <img src="twitter.png" class="sm">
        <img src="instagram.png" class="sm">
    </section>
</footer></code>```

Here you have it on JSFiddle: https://jsfiddle.net/e7j68Lvf/1/

Now, for centering, you could give the .socialmedia element some width, and then use margin: auto on it, like this:

```<code>.socialmedia {
    display: block;
    left: 45%;
    margin: auto;
    width: 50%;
}
</code>```

.sm {
    display: block;
}

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}

.socialmedia {
    display: block;
    left: 45%;
    margin: auto;
    width: 50%;
}

.socialmedia img {
    float: left;
    margin-right: 20px;
}

img {
   border:1px solid red;
    height:50px;
    width:50px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><footer>
    <section class="socialmedia">
        <img src="facebook.png" class="sm">
        <img src="twitter.png" class="sm">
        <img src="instagram.png" class="sm">
    </section>
</footer></code>```

And here you have the whole thing in JSFiddle: https://jsfiddle.net/e7j68Lvf/2/

Title: Trouble formatting images in my CSS

Body:
community!
I am having trouble getting the formatting down for a few images I have.

HTML

CSS

.sm {
    display: block;
}

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}

.socialmedia {
    display: block;
    left: 45%;
    float: left;
    width: 2%;
}

The images are just lined up vertically to the left of the page, all at the original size. To my understanding the

float: left;

is used to make them horizontal?

Also I would like them to be centered on the page, but margin: auto; is not changing anything either.

EDIT: I would like to have some spacing between each image as well, is there an alternative to

& nbsp;

Body:
Note that you want the images to be side-by-side, but you're using the float on the .socialmedia element, which is the container and not the images. So you should change your CSS to:

.socialmedia {
    display: block;
    left: 45%;
}
.socialmedia img {
    float: left;
}

.sm {
    display: block;
}

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}

.socialmedia {
    display: block;
    left: 45%;
}

.socialmedia img {
    float: left;
}

img {
   border:1px solid red;
    height:50px;
    width:50px;
}

<footer>
    <section class="socialmedia">
        <a href=""><img src="facebook.png" class="sm"></a>
        <a href=""><img src="twitter.png" class="sm"></a>
        <a href=""><img src="instagram.png" class="sm"></a>
    </section>
</footer>

Here you have it on JSFiddle: https://jsfiddle.net/e7j68Lvf/

If you want some space between the images, you can use margin, like this:

.socialmedia img {
    float: left;
    margin-right: 20px;
}

.sm {
    display: block;
}

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}

.socialmedia {
    display: block;
    left: 45%;
}

.socialmedia img {
    float: left;
    margin-right: 20px;
}

img {
   border:1px solid red;
    height:50px;
    width:50px;
}

<footer>
    <section class="socialmedia">
        <a href=""><img src="facebook.png" class="sm"></a>
        <a href=""><img src="twitter.png" class="sm"></a>
        <a href=""><img src="instagram.png" class="sm"></a>
    </section>
</footer>

Here you have it on JSFiddle: https://jsfiddle.net/e7j68Lvf/1/

Now, for centering, you could give the .socialmedia element some width, and then use margin: auto on it, like this:

.socialmedia {
    display: block;
    left: 45%;
    margin: auto;
    width: 50%;
}

.sm {
    display: block;
}

/* Add a hover effect */
.sm:hover {
    opacity: 0.7;
}

.socialmedia {
    display: block;
    left: 45%;
    margin: auto;
    width: 50%;
}

.socialmedia img {
    float: left;
    margin-right: 20px;
}

img {
   border:1px solid red;
    height:50px;
    width:50px;
}

<footer>
    <section class="socialmedia">
        <a href=""><img src="facebook.png" class="sm"></a>
        <a href=""><img src="twitter.png" class="sm"></a>
        <a href=""><img src="instagram.png" class="sm"></a>
    </section>
</footer>

And here you have the whole thing in JSFiddle: https://jsfiddle.net/e7j68Lvf/2/


问:
How to make GitHub's Immutables work in IntelliJ + Gradle
I use GitHub's Immutables library for Android development, and now I want to give it a try on the backend side as well.

In Android, all I need to to in order to use the library is this:

```<code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    // immutable entities generation
    provided "org.immutables:value:2.5.5" // for annotations
    provided "org.immutables:builder:2.5.5" // for annotations
    provided "org.immutables:gson:2.5.5" // for annotations

    ... other dependencies
}
</code>```

When I attempt to copy the above dependencies into build.gradle of my Java project, I get this error:

```<code>Error:(24, 0) Gradle DSL method not found: 'provided()'
</code>```

I tried to replace provided with compileOnly and compile, but then the implementations of the interfaces annotated with @Value.Immutable are not generated.

How do I make it work?

答:
Found the answer. Sharing in case it will be helpful to anyone (or myself in the future).

First of all, I had to enable annotation processing in IntelliJ as described here (though the option is now located in Settings > Build, Execution, Deployment > Compiler > Annotation Processors).

After that the following code started actually generating the implementation:

```<code>dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    // immutable entities generation
    compile "org.immutables:value:2.5.5" // for annotations
    compile "org.immutables:builder:2.5.5" // for annotations
    compile "org.immutables:gson:2.5.5" // for annotations

    ... other dependencies
}
</code>```

However, I still couldn't automatically import the implementation into source files.

In order to do allow the discovery of the generated classes, I had to right-click on the generated folder in the main package and then Mark Directory As > Generated Sources Root.

Body:
I use GitHub's Immutables library for Android development, and now I want to give it a try on the backend side as well.

In Android, all I need to to in order to use the library is this:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    // immutable entities generation
    provided "org.immutables:value:2.5.5" // for annotations
    provided "org.immutables:builder:2.5.5" // for annotations
    provided "org.immutables:gson:2.5.5" // for annotations

    ... other dependencies
}

When I attempt to copy the above dependencies into build.gradle of my Java project, I get this error:

Error:(24, 0) Gradle DSL method not found: 'provided()'

I tried to replace provided with compileOnly and compile, but then the implementations of the interfaces annotated with @Value.Immutable are not generated.

How do I make it work?

Body:
Found the answer. Sharing in case it will be helpful to anyone (or myself in the future).

First of all, I had to enable annotation processing in IntelliJ as described here (though the option is now located in Settings > Build, Execution, Deployment > Compiler > Annotation Processors).

After that the following code started actually generating the implementation:

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])

    // immutable entities generation
    compile "org.immutables:value:2.5.5" // for annotations
    compile "org.immutables:builder:2.5.5" // for annotations
    compile "org.immutables:gson:2.5.5" // for annotations

    ... other dependencies
}

However, I still couldn't automatically import the implementation into source files.

In order to do allow the discovery of the generated classes, I had to right-click on the generated folder in the main package and then Mark Directory As > Generated Sources Root.


答:
I think you can achieve this in your seeder like:

factory(App\User::class, 30)->create()->each(function($user) {

    $entity = factory(App\Entity::class)->make();

    $address = factory(App\Address::class)->create([
        'entity_id' => $entity
    ]);

    $user->entities()->save($entity);
});
```

If you are going to create multiple entities for each user, you will need to use saveMany() instead of save().

Title: How to add Relationship of Factories to faker in Laravel

Body:
I have models like this:

Entity - entities table
Address - address table
User - users table
Geoloc - geoloc table
UserEntity - entity_user table

Now Entity can have one address and one geoloc, but it can have multiple users this is what UserEntity is for.

So I need to do a pattern where factory will create it like this:

User>Entity>Address>Geoloc>UserEntity

so when user is created it will also create entity, address and geoloc, associate entity id to address, associate geoloc id to entity and insert user_id and entity_id to user entity.

Here's my current setup:

AddressFactory:

$factory->define(App\Address::class, function (Faker $faker) {
    return [
        'building_name' => $faker->company,
        'address' => $faker->streetAddress,
        'town' => $faker->city,
        'postcode' => $faker->postcode,
        'telephone' => $faker->phoneNumber,
        'private' => $faker->boolean($chanceOfGettingTrue = 50),
        'entity_id' => function () {
            return factory(App\Entity::class)->create()->id;
        }
    ];
});

EntityFactory:

factory->define(App\Entity::class, function (Faker $faker) {
    return [
        'name' => $faker->unique()->company,
        'type' => 'Service',
        'tags' => 'mens clothes, online shopping, ladies clothes',
        'email' => $faker->safeEmail,
        'logo' => $faker->imageUrl($width = 640, $height = 480),
        'cover' => $faker->imageUrl($width = 1000, $height = 600),
        'bio' => $faker->catchPhrase,
        'main' => $faker->realText($maxNbChars = 200, $indexSize = 2),
        'twitter_business' => 'OfficialOAFC',
        'facebook_business' => 'MolinoLounge',
        'instagram_business' => 'OfficialOAFC',
        'google_places' => 'ChIJvaCBHYG3e0gRfhs0xZ1TBB8',
        'eventbrite' =>'8252340832',
        'featured' => $faker->boolean($chanceOfGettingTrue = 50),
        'url' => $faker->url,
        'video' => '6R2DIFySho4',
        'wikipedia' => 'Hackerspace',
        'contact_name' => $faker->name,
        'contact_number' => $faker->phoneNumber,
        'geoloc_id' => function () {
            return factory(App\Geoloc::class)->create()->id;
        }
    ];
});

UserFactory:

$factory->define(App\User::class, function (Faker $faker) {
    static $password;
    return [
        'name' => $faker->name,
        'email' => $faker->unique()->safeEmail,
        'password' => $password ?: $password = bcrypt('secret'),
        'avatar' => $faker->imageUrl($width = 640, $height = 480),
        //'telephone' => $faker->phoneNumber,
        'role' => rand(1, 2),
        'remember_token' => str_random(10),
    ];
});

DatabaseSeeder:

    factory(App\User::class, 30)->create();
    factory(App\Address::class, 30)->create();

User relations:

public function entities()
{
    return $this->belongsToMany('App\Entity', 'entity_user', 'user_id', 'entity_id');
}

Entity relations:

public function address()
{
    return $this->hasOne('App\Address', 'entity_id');
}
public function _geoloc()
{
    return $this->belongsTo('App\Geoloc', 'geoloc_id', 'id');
}

Body:
I think you can achieve this in your seeder like:

factory(App\User::class, 30)->create()->each(function($user) {

    $entity = factory(App\Entity::class)->make();

    $address = factory(App\Address::class)->create([
        'entity_id' => $entity
    ]);

    $user->entities()->save($entity);
});

If you are going to create multiple entities for each user, you will need to use saveMany() instead of save().


问:
Gitlab-runner on another server
I would like execute gitlab-runner on another server than my own gitlab ci server. I want to do this to use the environment of this another server, and execute my code.
I tried to copy and execute the binary 'gitlab-runner' on this server, after some question, I have a certificate error, but the certificat is correctly installed on my gitlab server!

First, is that the correct way to execute a runner on another server ?

Second, how can i solve this certificate error ?

```<code>gitlab-runner --debug register
Runtime platform  arch=amd64 os=linux revision=adfc387 version=9.2.0
Checking runtime mode  GOOS=linux uid=1125
WARNING: Running in user-mode.
WARNING: The user-mode requires you to manually start builds processing:
WARNING: $ gitlab-runner run
WARNING: Use sudo for system-mode:
WARNING: $ sudo gitlab-runner...

Please enter the gitlab-ci coordinator URL (e.g. https://gitlab.com/):
https://mygitlab.myserver.fr/
Please enter the gitlab-ci token for this runner:
iYwQbJ-b2qg2JLu4sqn8
Please enter the gitlab-ci description for this runner:
[server1]: runnertest
Please enter the gitlab-ci tags for this runner (comma separated):

Whether to lock Runner to current project [true/false]:
[false]:
Dialing: tcp mygitlab.myserver.fr:443 ...
ERROR: Registering runner... failed                 runner=iYwQbJ-b
status=couldn't execute POST against
https://mygitlab.myserver.fr/api/v4/runners: Post
https://mygitlab.myserver.fr/api/v4/runners: x509: certificate signed by
unknown authority
Dialing: tcp mygitlab.myserver.fr:443 ...
ERROR: Checking GitLab compatibility... not-compatible  reason=GitLab Runner
>= 9.0 can be used ONLY with GitLab CE/EE >= 9.0 result=-1 runner=iYwQbJ-b
statusText=couldn't execute POST against
https://mygitlab.myserver.fr/api/v4/runners/verify: Post
https://mygitlab.myserver.fr/api/v4/runners/verify: x509: certificate signed
by unknown authority
PANIC: Failed to register this runner. Perhaps you are having network problems
</code>```

When I curl the url, I received :

```<code>curl -X POST -k --form "token=iYwQbJ-b2qg2JLu4sqn8" https://mygitlab.myserver.fr/api/v4/runners/verify
{"message":"403 Forbidden"}
</code>```

Thank you very much !

答: Just install it as a regular Gitlab CI runner and use the shell executor. Add tags while registering the runner so you can use it for specific jobs of your pipeline that require this runner.</p>

Title: Gitlab-runner on another server

Body:
I would like execute gitlab-runner on another server than my own gitlab ci server. I want to do this to use the environment of this another server, and execute my code.
I tried to copy and execute the binary 'gitlab-runner' on this server, after some question, I have a certificate error, but the certificat is correctly installed on my gitlab server!

First, is that the correct way to execute a runner on another server ?

Second, how can i solve this certificate error ?

gitlab-runner --debug register
Runtime platform  arch=amd64 os=linux revision=adfc387 version=9.2.0
Checking runtime mode  GOOS=linux uid=1125
WARNING: Running in user-mode.
WARNING: The user-mode requires you to manually start builds processing:
WARNING: $ gitlab-runner run
WARNING: Use sudo for system-mode:
WARNING: $ sudo gitlab-runner...

Please enter the gitlab-ci coordinator URL (e.g. https://gitlab.com/):
https://mygitlab.myserver.fr/
Please enter the gitlab-ci token for this runner:
iYwQbJ-b2qg2JLu4sqn8
Please enter the gitlab-ci description for this runner:
[server1]: runnertest
Please enter the gitlab-ci tags for this runner (comma separated):

Whether to lock Runner to current project [true/false]:
[false]:
Dialing: tcp mygitlab.myserver.fr:443 ...
ERROR: Registering runner... failed                 runner=iYwQbJ-b
status=couldn't execute POST against
https://mygitlab.myserver.fr/api/v4/runners: Post
https://mygitlab.myserver.fr/api/v4/runners: x509: certificate signed by
unknown authority
Dialing: tcp mygitlab.myserver.fr:443 ...
ERROR: Checking GitLab compatibility... not-compatible  reason=GitLab Runner
>= 9.0 can be used ONLY with GitLab CE/EE >= 9.0 result=-1 runner=iYwQbJ-b
statusText=couldn't execute POST against
https://mygitlab.myserver.fr/api/v4/runners/verify: Post
https://mygitlab.myserver.fr/api/v4/runners/verify: x509: certificate signed
by unknown authority
PANIC: Failed to register this runner. Perhaps you are having network problems

When I curl the url, I received :

curl -X POST -k --form "token=iYwQbJ-b2qg2JLu4sqn8" https://mygitlab.myserver.fr/api/v4/runners/verify
{"message":"403 Forbidden"}

Thank you very much !


问:
roscore in docker container not working when called via bash script
I have created file myScript.sh in which there is only a call to roscore:

```<code>#!/bin/bash
echo youpi
roscore
</code>```

When this executable script is run from within a container I have no problem with it, both echo youpi and roscore are executed correctly.

Now when myScript.sh is called from the host (to be executed on the container), I get the echo youpi line is executed correctly, but I get not the roscore line that outputs:

```<code>myScript.sh: line 3: roscore: command not found
</code>```

The command line I use on the host is:

```<code>docker exec -ti lescompanions /bin/bash -c "source /home/dev/DevRoot/src/catkin_ws/src/le_painters_companion/lc_control/start_roscore_docker.sh && exec /bin/bash -li"
</code>```

Any idea of what is going wrong?

答:
If roscore is not an executable in the $PATH, you should call it with the path. E.g. ./roscore or /path/to/roscore. It might be that the file permissions are not right, then you need to execute

```<code>chmod 755 roscore
</code>```

Body:
I have created file myScript.sh in which there is only a call to roscore:

#!/bin/bash
echo youpi
roscore

When this executable script is run from within a container I have no problem with it, both echo youpi and roscore are executed correctly.

Now when myScript.sh is called from the host (to be executed on the container), I get the echo youpi line is executed correctly, but I get not the roscore line that outputs:

myScript.sh: line 3: roscore: command not found

The command line I use on the host is:

docker exec -ti lescompanions /bin/bash -c "source /home/dev/DevRoot/src/catkin_ws/src/le_painters_companion/lc_control/start_roscore_docker.sh && exec /bin/bash -li"

Any idea of what is going wrong?

Body:
If roscore is not an executable in the $PATH, you should call it with the path. E.g. ./roscore or /path/to/roscore. It might be that the file permissions are not right, then you need to execute

chmod 755 roscore


问:
How to get table data after parsing HTML from a url in iOS Swift 3
I am developing an iOS app in which I need to parse html from a link with kanna api. I have done it. But it's shown all of the html file. I need to show just a portion of data like this

```<code>    <table width="880" border="1" cellspacing="0" cellpadding="0">
  <tr>
    <td width="81"><strong>Trip Name </strong></td>
    <td width="159"><div align="center"><strong>Starting Time from Campus </strong></div></td>
    <td width="186"><div align="center"><strong>Starting Spot & Time </strong></div></td>
    <td width="444"><strong>Remarks</strong></td>
  </tr>
  <tr>
    <td><div align="center">Normal-1</div></td>
    <td><div align="center">6:30 AM </div></td>
    <td>Rupsha, 7:20 AM </td>
    <td>Will back via Royalmore & Ferighat  </td>
  </tr>
  <tr>
    <td><div align="center">Normal-1</div></td>
    <td><div align="center">6:45 AM </div></td>
    <td>Moylapota, 7:25 AM </td>
    <td>Will back via Shibbari - Sonadangha </td>
  </tr>

</table>
</code>```

I have used this portion of code in swift 3 to show all html data.

```<code>let html = "<html>...</html>"

if let doc = HTML(html: html, encoding: .utf8) {
    // Search for nodes by XPath
    for link in doc.xpath("//a | //link") {
        print(link["href"])
    }
}
</code>```

Now I want to get only the table portion of html data. How can I do it?

答:
This will do the trick:

```<code>    //I replaced " with ' to make it easier. But it shouldn't be a problem in your case.
    let html = "<table width='880' border='1' cellspacing='0' cellpadding='0'>"
    + "<tr>"
    + "<td width='81'><strong>Trip Name </strong></td>"
    + "<td width='159'><div align='center'><strong>Starting Time from Campus </strong></div></td>"
    + "<td width='186'><div align='center'><strong>Starting Spot & Time </strong></div></td>"
    + "<td width='444'><strong>Remarks</strong></td>"
    + "</tr>"
    + "<tr>"
    + "<td><div align='center'>Normal-1</div></td>"
    + "<td><div align='center'>6:30 AM </div></td>"
    + "<td>Rupsha, 7:20 AM </td>"
    + "<td>Will back via Royalmore & Ferighat  </td>"
    + "</tr>"
    + "<tr>"
    + "<td><div align='center'>Normal-1</div></td>"
    + "<td><div align='center'>6:45 AM </div></td>"
    + "<td>Moylapota, 7:25 AM </td>"
    + "<td>Will back via Shibbari - Sonadangha </td>"
    + "</tr>"
    + "</table>"

    var infoFromHTML : [[String]] = []

    if let doc = try? HTML(html: html, encoding: .utf8) {
        var row : [String] = []
        //look for td tags, not a or link tags
        for (index, td) in doc.css("td").enumerated(){

            row.append(td.text as! String)

            if index%4 == 3{
                //if all row text are added to the row array, append it to info, and reset
                infoFromHTML.append(row)
                row = []
            }
        }
    }
    print(infoFromHTML)
</code>```

Here is your output:

```<code>    [
        ["Trip Name ", "Starting Time from Campus ", "Starting Spot & Time ", "Remarks"],
        ["Normal-1", "6:30 AM ", "Rupsha, 7:20 AM ", "Will back via Royalmore & Ferighat  "],
        ["Normal-1", "6:45 AM ", "Moylapota, 7:25 AM ", "Will back via Shibbari - Sonadangha "]
    ]
</code>```

If you don't want to use headers of the table, just pretend like array's first element is not 0, it is 1.

If we talk about why you couldn't make it work; you are looking for a and link tags here doc.xpath("//a | //link"). But you have td tags. So you should do this: doc.css("td"). I used css function but I may use XPath too.

Good luck!

EDIT: You still should ask for an API. Preferably a RESTful JSON API.

EDIT 2: I used Swift 4 version of the Kanna. You may need to do some changes to use this with Swift 3.

Body:
I am developing an iOS app in which I need to parse html from a link with kanna api. I have done it. But it's shown all of the html file. I need to show just a portion of data like this

    Trip Name

Starting Time from Campus

Starting Spot & Time

    Remarks

Normal-1

6:30 AM

    Rupsha, 7:20 AM
    Will back via Royalmore & Ferighat

Normal-1

6:45 AM

    Moylapota, 7:25 AM
    Will back via Shibbari - Sonadangha

I have used this portion of code in swift 3 to show all html data.

let html = "..."

if let doc = HTML(html: html, encoding: .utf8) {
    // Search for nodes by XPath
    for link in doc.xpath("//a | //link") {
        print(link["href"])
    }
}

Now I want to get only the table portion of html data. How can I do it?

Body:
This will do the trick:

    //I replaced " with ' to make it easier. But it shouldn't be a problem in your case.
    let html = "<table width='880' border='1' cellspacing='0' cellpadding='0'>"
    + "<tr>"
    + "<td width='81'><strong>Trip Name </strong></td>"
    + "<td width='159'><div align='center'><strong>Starting Time from Campus </strong></div></td>"
    + "<td width='186'><div align='center'><strong>Starting Spot &amp; Time </strong></div></td>"
    + "<td width='444'><strong>Remarks</strong></td>"
    + "</tr>"
    + "<tr>"
    + "<td><div align='center'>Normal-1</div></td>"
    + "<td><div align='center'>6:30 AM </div></td>"
    + "<td>Rupsha, 7:20 AM </td>"
    + "<td>Will back via Royalmore &amp; Ferighat  </td>"
    + "</tr>"
    + "<tr>"
    + "<td><div align='center'>Normal-1</div></td>"
    + "<td><div align='center'>6:45 AM </div></td>"
    + "<td>Moylapota, 7:25 AM </td>"
    + "<td>Will back via Shibbari - Sonadangha </td>"
    + "</tr>"
    + "</table>"

    var infoFromHTML : [[String]] = []

    if let doc = try? HTML(html: html, encoding: .utf8) {
        var row : [String] = []
        //look for td tags, not a or link tags
        for (index, td) in doc.css("td").enumerated(){

            row.append(td.text as! String)

            if index%4 == 3{
                //if all row text are added to the row array, append it to info, and reset
                infoFromHTML.append(row)
                row = []
            }
        }
    }
    print(infoFromHTML)

Here is your output:

    [
        ["Trip Name ", "Starting Time from Campus ", "Starting Spot & Time ", "Remarks"],
        ["Normal-1", "6:30 AM ", "Rupsha, 7:20 AM ", "Will back via Royalmore & Ferighat  "],
        ["Normal-1", "6:45 AM ", "Moylapota, 7:25 AM ", "Will back via Shibbari - Sonadangha "]
    ]

If you don't want to use headers of the table, just pretend like array's first element is not 0, it is 1.

If we talk about why you couldn't make it work; you are looking for a and link tags here doc.xpath("//a | //link"). But you have td tags. So you should do this: doc.css("td"). I used css function but I may use XPath too.

Good luck!

EDIT: You still should ask for an API. Preferably a RESTful JSON API.

EDIT 2: I used Swift 4 version of the Kanna. You may need to do some changes to use this with Swift 3.


问:
How to print variables using Console.WriteLine
The following code demonstrates the use of the sleep() method for making a thread pause for a specific period of time.

When I run this code :-

```<code>class Program
{
    class ThreadCreationProgram
    {
        public static void CallToChildThread()
        {
            Console.WriteLine("Child thread starts");

            // the thread is paused for 5000 milliseconds
            int sleepfor = 5000;

            Console.WriteLine("Child Thread Paused for {0} seconds");
            Thread.Sleep(sleepfor);
            Console.WriteLine("Child thread resumes");
        }

        static void Main(string[] args)
        {
            ThreadStart childref = new ThreadStart(CallToChildThread);
            Console.WriteLine("In Main: Creating the Child thread");
            Thread childThread = new Thread(childref);
            childThread.Start();
            Console.ReadKey();
        }
    }
}
</code>```

I  get this output-

```<code>In Main: Creating the child thread
Child thread starts
Child thread paused for <0> seconds
Child thread resumes
</code>```

But what i expect is :-

```<code>In Main: Creating the child thread
Child thread starts
Child thread paused for <5> seconds
Child thread resumes
</code>```

How can I do it any suggestions?

答:
```<code>Console.WriteLine("Child Thread Paused for <{0}> seconds", sleepfor/1000);
</code>```

or C# 6 approach:

```<code>Console.WriteLine($"Child Thread Paused for <{sleepfor/1000}> seconds");
</code>```

Body:
The following code demonstrates the use of the sleep() method for making a thread pause for a specific period of time.

When I run this code :-

class Program
{
    class ThreadCreationProgram
    {
        public static void CallToChildThread()
        {
            Console.WriteLine("Child thread starts");

            // the thread is paused for 5000 milliseconds
            int sleepfor = 5000;

            Console.WriteLine("Child Thread Paused for {0} seconds");
            Thread.Sleep(sleepfor);
            Console.WriteLine("Child thread resumes");
        }

        static void Main(string[] args)
        {
            ThreadStart childref = new ThreadStart(CallToChildThread);
            Console.WriteLine("In Main: Creating the Child thread");
            Thread childThread = new Thread(childref);
            childThread.Start();
            Console.ReadKey();
        }
    }
}

I  get this output-

In Main: Creating the child thread
Child thread starts
Child thread paused for <0> seconds
Child thread resumes

But what i expect is :-

In Main: Creating the child thread
Child thread starts
Child thread paused for <5> seconds
Child thread resumes

How can I do it any suggestions?

Body:
Console.WriteLine("Child Thread Paused for <{0}> seconds", sleepfor/1000);

or C# 6 approach:

Console.WriteLine($"Child Thread Paused for <{sleepfor/1000}> seconds");


问:
Is it possible to make subpackage appear as the actual package
I came around this question and got quite disappointed by how the tensorflow developers try to make the tensorflow directory appear as the actual package, whereas the actual package root is actually tensorflow/python. By using a __init__.py file of the form

```<code>from tensorflow.python import *
del python
</code>```

they try to achieve this goal. This results in some inconsistent behaviour (at least so it seems to me) when working with the package, e.g.

```<code>import tensorflow.python                # seems to work
tensorflow.python                       # AttributeError: no attribute 'python'
from tensorflow.python import Session   # works as expected
tensorflow.python.Session               # AttributeError: no attribute 'python'
from tensorflow import python           # works as expected

tensorflow.nn                           # works as expected
import tensorflow.nn                    # ImportError: no module 'tensorflow.nn'
tensorflow.nn.tanh                      # works as expected
from tensorflow.nn import tanh          # ImportError: no module 'tensorflow.nn'
</code>```

Now, I was wondering whether/how it could be possible to avoid most/all of these issues to get a more consistent behaviour. The first set of inconsistencies could be easily resolved by not deleting the python attribute. However, given that the goal would be to make the complete package appear as if it is a sub-package, this might not be entirely satisfactory.

To keep things simple, let's consider the following package structure

```<code>package/
    __init__.py
    api/
        __init__.py
        code.py
</code>```

where package/api/code.py looks something like

```<code>def a():
    return 'alpha'
def b():
    return 'bravo'
</code>```

and package/api/__init__.py would be

```<code>import package.api.code
</code>```

would it be possible to create package/__init__.py so that the following works

```<code>import package.api                      # ImportError: no module 'package.api'
package.api                             # AttributeError: no attribute 'api'
from package.api import code            # ImportError: no module 'package.api'
package.api.code                        # AttributeError: no attribute 'api'
from package import api                 # ImportError: cannot import 'api'

package.code                            # works as expected
import package.code                     # works as above
package.code.a                          # works as expected
from package import a                   # correctly imports function a
</code>```

I believe that the last four lines of code should give the expected result by adding to sys.modules, but I do not seem to be able to find a way to make import package.api fail.

Would anyone have an idea on how this could be done? Feel free to point me to use-cases that I am overlooking or should consider to achieve the above-mentioned goal.

答:
First of all - I must say that I literally hate "shady" techniques like this. It has a bad effect on various IDE intellisense and makes the library structure less understandable. But still...

If you want the submodule code.py to act as an actual subpackage, you need to create a dummy module:

```<code>package/
    __init__.py
    api/
        __init__.py
        code.py
    code/
        __init__.py
</code>```

Add this in code/__init__py:

```<code>from package.api.code import *
</code>```

And this in package/__init__.py:

```<code>from package.code import *
</code>```

And then this part should work as intended:

```<code>import package.code            # works as expected
package.code                   # works as expected
package.code.a                 # works as expected
from package import a          # works as expected
</code>```

If you further add this to the package/__init__.py:

```<code>import package.api
del package.api
</code>```

You basically disconnect user from accessing package.api, but nothing else, and they can still access the submodule through subpackage using 'from x import y':

```<code>import package.api            # works
package.api.a()               # AttributeError: module 'package' has no attribute 'api'

import package.api.code       # works
package.api.code.a()          # AttributeError: module 'package' has no attribute 'api'

from package.api import code  # works
code.a()                      # works

from package import api       # works
api.code.a()                  # AttributeError: module 'package.api' has no attribute 'code'
</code>```

Body:
I came around this question and got quite disappointed by how the tensorflow developers try to make the tensorflow directory appear as the actual package, whereas the actual package root is actually tensorflow/python. By using a __init__.py file of the form

from tensorflow.python import *
del python

they try to achieve this goal. This results in some inconsistent behaviour (at least so it seems to me) when working with the package, e.g.

import tensorflow.python                # seems to work
tensorflow.python                       # AttributeError: no attribute 'python'
from tensorflow.python import Session   # works as expected
tensorflow.python.Session               # AttributeError: no attribute 'python'
from tensorflow import python           # works as expected

tensorflow.nn                           # works as expected
import tensorflow.nn                    # ImportError: no module 'tensorflow.nn'
tensorflow.nn.tanh                      # works as expected
from tensorflow.nn import tanh          # ImportError: no module 'tensorflow.nn'

Now, I was wondering whether/how it could be possible to avoid most/all of these issues to get a more consistent behaviour. The first set of inconsistencies could be easily resolved by not deleting the python attribute. However, given that the goal would be to make the complete package appear as if it is a sub-package, this might not be entirely satisfactory.

To keep things simple, let's consider the following package structure

package/
    __init__.py
    api/
        __init__.py
        code.py

where package/api/code.py looks something like

def a():
    return 'alpha'
def b():
    return 'bravo'

and package/api/__init__.py would be

import package.api.code

would it be possible to create package/__init__.py so that the following works

import package.api                      # ImportError: no module 'package.api'
package.api                             # AttributeError: no attribute 'api'
from package.api import code            # ImportError: no module 'package.api'
package.api.code                        # AttributeError: no attribute 'api'
from package import api                 # ImportError: cannot import 'api'

package.code                            # works as expected
import package.code                     # works as above
package.code.a                          # works as expected
from package import a                   # correctly imports function a

I believe that the last four lines of code should give the expected result by adding to sys.modules, but I do not seem to be able to find a way to make import package.api fail.

Would anyone have an idea on how this could be done? Feel free to point me to use-cases that I am overlooking or should consider to achieve the above-mentioned goal.

Body:
First of all - I must say that I literally hate "shady" techniques like this. It has a bad effect on various IDE intellisense and makes the library structure less understandable. But still...

If you want the submodule code.py to act as an actual subpackage, you need to create a dummy module:

package/
    __init__.py
    api/
        __init__.py
        code.py
    code/
        __init__.py

Add this in code/__init__py:

from package.api.code import *

And this in package/__init__.py:

from package.code import *

And then this part should work as intended:

import package.code            # works as expected
package.code                   # works as expected
package.code.a                 # works as expected
from package import a          # works as expected

If you further add this to the package/__init__.py:

import package.api
del package.api

You basically disconnect user from accessing package.api, but nothing else, and they can still access the submodule through subpackage using 'from x import y':

import package.api            # works
package.api.a()               # AttributeError: module 'package' has no attribute 'api'

import package.api.code       # works
package.api.code.a()          # AttributeError: module 'package' has no attribute 'api'

from package.api import code  # works
code.a()                      # works

from package import api       # works
api.code.a()                  # AttributeError: module 'package.api' has no attribute 'code'


问:
MongoDB connection error on AWS ec2 instance
I have trying to connect to my mongo server on ec2 instance from my app hosted on elastic beanstalk.

It worked when authorization was NOT enabled. I could connect through both local IP and public IP.

Then I added users to the DB and enabled authorization in server. I could connect to the server using mongodb://user:password@ec2IP/27017 from any commandline interface.

Using the same mongo URI from the elasticbeanstalk app I cannot connect to the mongodb server. This is the error I am getting -

```<code>MongoError: failed to connect to server [<user-name-mongo-server>:27017] on first connect [MongoError: getaddrinfo ENOTFOUND <user-name-mongo-server> <user-name-mongo-server>:27017
</code>```

Any idea? Thanks in advance!

答:
Apparently,

I had passwords that included either a

%

or a

?

which was the problem for mongoose connection.

so my mongo URI looked like this -

```<code>mongodb://<user>:<password-including-%-or-?>@IP:port/dbname
</code>```

Body:
I have trying to connect to my mongo server on ec2 instance from my app hosted on elastic beanstalk.

It worked when authorization was NOT enabled. I could connect through both local IP and public IP.

Then I added users to the DB and enabled authorization in server. I could connect to the server using mongodb://user:password@ec2IP/27017 from any commandline interface.

Using the same mongo URI from the elasticbeanstalk app I cannot connect to the mongodb server. This is the error I am getting -

MongoError: failed to connect to server [<user-name-mongo-server>:27017] on first connect [MongoError: getaddrinfo ENOTFOUND <user-name-mongo-server> <user-name-mongo-server>:27017

Any idea? Thanks in advance!

Body:
Apparently,

I had passwords that included either a

%

or a

?

which was the problem for mongoose connection.

so my mongo URI looked like this -

mongodb://<user>:<password-including-%-or-?>@IP:port/dbname