问:
Stub authentication in request specs
I'm looking for the way to do this but in request specs. I need to log in and log out a double or instance_double to Devise instead of an actual ActiveModel/ActiveRecord.

By using the code in the wiki page:

```<code>module RequestSpecHelpers
    def sign_in(user = double('user'))
      if user.nil?
        allow(request.env['warden']).to receive(:authenticate!).and_throw(:warden, {:scope => :user})
        allow(controller).to receive(:current_user).and_return(nil)
      else
        allow(request.env['warden']).to receive(:authenticate!).and_return(user)
        allow(controller).to receive(:current_user).and_return(user)
      end
    end
  end
</code>```

I get this error:  undefined method 'env' for nil:NilClass

I saw this question and this wiki, but if I want to use doubles of the user those two don't work. I was using the last one, works fine with a real user but with a double it doesn't log it in.

The tests:

```<code>RSpec.describe 'new shipment', type: :request do
  describe 'authenticated as user' do
    before do
      @user = double(:user, id: 1, email: 'user@gmail.com', password: 'password',
                      id_card: '4163649-1', first_name: 'Jane', last_name: 'Doe')

      sign_in @user
    end
  end
end
</code>```

If I include:

```<code>RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :requests
end
</code>```

I get this error:

```<code>Failure/Error: @request.env['action_controller.instance'] = @controller

     NoMethodError:
       undefined method `env' for nil:NilClass
     # /root/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/gems/devise-4.3.0/lib/devise/test/controller_helpers.rb:40:in `setup_controller_for_warden'
</code>```

Problem with Frederick Cheung answer

If I do that the login_asmethod doesn't fail but it doesn't really log the user in. So when I try to access a path that has a before_action :authenticate_user! callback it fails.

Here is my code based on his answer:

```<code>require 'rails_helper'

RSpec.describe 'new shipment', type: :request do
  describe 'authenticated as user' do
    include Warden::Test::Helpers

    before(:each) do
      Warden.test_mode!
      #stub more methods as needed by the pages you are testing
      user = instance_double(User, to_key: 1, authenticatable_salt: 'example')
      login_as(user, scope: 'user')
    end

    it 'returns 200 Ok' do
      get new_shipment_path
      expect(response).to have_http_status(:ok)
    end
  end
end
</code>```

And this is the response when running rspec:

```<code> 1) new shipment authenticated as user returns 200 Ok
     Failure/Error: expect(response).to have_http_status(:ok)
       expected the response to have status code :ok (200) but it was :found (302)
     # ./spec/requests/shipments_requests_spec.rb:41:in `block (3 levels) in <top (required)>'
</code>```

As you can see instead of allowing me to access the path it redirects me, this is the usual behavior when the user is not allowed to access the path.

It I change the instance_double for a real User saved in the database this approach works correctly:

```<code># only changed this line in the before hook
user = User.create(email: 'user@gmail.com', password: 'password',id_card: '4163649-1', first_name: 'Jane', last_name: 'Doe')
</code>```

Result:

```<code>Finished in 3.23 seconds (files took 33.47 seconds to load)
1 example, 0 failures
</code>```

答:
It sounds like you're using Devise 3.x ( since Devise::TestHelpers was renamed in devise 4), Devise::TestHelpers is only designed to work with controller specs.

If you can upgrade to devise 4, it has separate helpers for request specs and controller tests. This is just a very thin wrapper around what warden provides, which hides all the messing around with env.

There are some extra complications when using a double - you need to stub out various methods devise calls that you might not realise.

The following worked for me

```<code>describe 'example' do
  include Warden::Test::Helpers

  before(:each) do
    Warden.test_mode!
    #stub more methods as needed by the pages you are testing
    user = instance_double(User, to_key: 1, authenticatable_salt: 'example')
    login_as(user, scope: 'user')
  end
end
</code>```

Title: Stub authentication in request specs

Body:
I'm looking for the way to do this but in request specs. I need to log in and log out a double or instance_double to Devise instead of an actual ActiveModel/ActiveRecord.

By using the code in the wiki page:

module RequestSpecHelpers
    def sign_in(user = double('user'))
      if user.nil?
        allow(request.env['warden']).to receive(:authenticate!).and_throw(:warden, {:scope => :user})
        allow(controller).to receive(:current_user).and_return(nil)
      else
        allow(request.env['warden']).to receive(:authenticate!).and_return(user)
        allow(controller).to receive(:current_user).and_return(user)
      end
    end
  end

I get this error:  undefined method 'env' for nil:NilClass

I saw this question and this wiki, but if I want to use doubles of the user those two don't work. I was using the last one, works fine with a real user but with a double it doesn't log it in.

The tests:

RSpec.describe 'new shipment', type: :request do
  describe 'authenticated as user' do
    before do
      @user = double(:user, id: 1, email: 'user@gmail.com', password: 'password',
                      id_card: '4163649-1', first_name: 'Jane', last_name: 'Doe')

      sign_in @user
    end
  end
end

If I include:

RSpec.configure do |config|
  config.include Devise::TestHelpers, :type => :requests
end

I get this error:

Failure/Error: @request.env['action_controller.instance'] = @controller

     NoMethodError:
       undefined method `env' for nil:NilClass
     # /root/.rbenv/versions/2.4.2/lib/ruby/gems/2.4.0/gems/devise-4.3.0/lib/devise/test/controller_helpers.rb:40:in `setup_controller_for_warden'

Problem with Frederick Cheung answer

If I do that the login_asmethod doesn't fail but it doesn't really log the user in. So when I try to access a path that has a before_action :authenticate_user! callback it fails.

Here is my code based on his answer:

require 'rails_helper'

RSpec.describe 'new shipment', type: :request do
  describe 'authenticated as user' do
    include Warden::Test::Helpers

    before(:each) do
      Warden.test_mode!
      #stub more methods as needed by the pages you are testing
      user = instance_double(User, to_key: 1, authenticatable_salt: 'example')
      login_as(user, scope: 'user')
    end

    it 'returns 200 Ok' do
      get new_shipment_path
      expect(response).to have_http_status(:ok)
    end
  end
end

And this is the response when running rspec:

 1) new shipment authenticated as user returns 200 Ok
     Failure/Error: expect(response).to have_http_status(:ok)
       expected the response to have status code :ok (200) but it was :found (302)
     # ./spec/requests/shipments_requests_spec.rb:41:in `block (3 levels) in <top (required)>'

As you can see instead of allowing me to access the path it redirects me, this is the usual behavior when the user is not allowed to access the path.

It I change the instance_double for a real User saved in the database this approach works correctly:

# only changed this line in the before hook
user = User.create(email: 'user@gmail.com', password: 'password',id_card: '4163649-1', first_name: 'Jane', last_name: 'Doe')

Result:

Finished in 3.23 seconds (files took 33.47 seconds to load)
1 example, 0 failures

Body:
It sounds like you're using Devise 3.x ( since Devise::TestHelpers was renamed in devise 4), Devise::TestHelpers is only designed to work with controller specs.

If you can upgrade to devise 4, it has separate helpers for request specs and controller tests. This is just a very thin wrapper around what warden provides, which hides all the messing around with env.

There are some extra complications when using a double - you need to stub out various methods devise calls that you might not realise.

The following worked for me

describe 'example' do
  include Warden::Test::Helpers

  before(:each) do
    Warden.test_mode!
    #stub more methods as needed by the pages you are testing
    user = instance_double(User, to_key: 1, authenticatable_salt: 'example')
    login_as(user, scope: 'user')
  end
end


来源: stackexchange

问:
Angular2 formating text input into dd-MM-yyyy
I have a form in my angular project that I send via json to my JAVA rest API, I need the date string to be in the dd-MM-yyyy format. How can I do this? I know you can use the date pipe to format it as output, but I need to format the value of the formControl string so I can send it as json. Any ideas?

Tried setting it as type="date" but it doesn't change anything

```<code><ion-input formControlName="pacientedataexame" placeholder="Data do Exame:" type="date"></ion-input>
</code>```

答:
Seems like you are more into ionic way of doing this rather than plain angular:

```<code><ion-item>
  <ion-label>Date</ion-label>
  <ion-datetime displayFormat="DD-MM-YYYY" [(ngModel)]="myDate"></ion-datetime>
</ion-item>
</code>```

further reading you can find as usual in ionic docs

ContentLicense: CC BY-SA 3.0

Body:
I have a form in my angular project that I send via json to my JAVA rest API, I need the date string to be in the dd-MM-yyyy format. How can I do this? I know you can use the date pipe to format it as output, but I need to format the value of the formControl string so I can send it as json. Any ideas?

Tried setting it as type="date" but it doesn't change anything

<ion-input formControlName="pacientedataexame" placeholder="Data do Exame:" type="date"></ion-input>

Body:
Seems like you are more into ionic way of doing this rather than plain angular:

<ion-item>
  <ion-label>Date</ion-label>
  <ion-datetime displayFormat="DD-MM-YYYY" [(ngModel)]="myDate"></ion-datetime>
</ion-item>

further reading you can find as usual in ionic docs


问:
Extract array element from couchbase query
I need to make a N1QL query to extract the animal with highest age, from example from here:

```<code>[
  {
    "animals": [
      {
        "name": "dog1",
        "registered": "7-16-2017",
        "age_in_months": "24",
      },
      {
        "name": "dog2",
        "registered": "7-18-2017",
        "age_in_months": "28",
      }
    ]
  }
]
</code>```

I would need this result:

```<code>[
  {
    "oldest":
      {
        "name": "dog2",
        "registered": "7-18-2017",
        "age_in_months": "28",
      }
  }
]
</code>```

I am using this query

```<code>select t1.animals from `bucket` t1 use keys "myKey";
</code>```

But I have no idea how to extract just part from an array

答:
Try these steps:

Extract the nested animal information using UNNEST,

Find the animal with the maximum age using MAX, and

Take another pass over the animals and find the one with the maximum age using a subquery

Steps 1 and 2 are achieved with this query

```<code>SELECT RAW MAX(animals.age_in_months)
    FROM `bucket` USE KEYS "myKey" UNNEST animals
</code>```

Step 3 uses UNNEST again, but this time we use the output of the previous query to select those animals with the maximum age. This approach will pick all animals with the maximum age.

Here's the complete query:

```<code>SELECT animal
  FROM `bucket` b USE KEYS "myKey" UNNEST animals animal
    WHERE animal.age_in_months IN
      (SELECT RAW MAX(animals.age_in_months)
        FROM `bucket` USE KEYS "myKey" UNNEST animals);
</code>```

And here's the result for your example:

```<code>[
  {
    "animal": {
      "age_in_months": "28",
      "name": "dog2",
      "registered": "7-18-2017"
    }
  }
]
</code>```

Body:
I need to make a N1QL query to extract the animal with highest age, from example from here:

[
  {
    "animals": [
      {
        "name": "dog1",
        "registered": "7-16-2017",
        "age_in_months": "24",
      },
      {
        "name": "dog2",
        "registered": "7-18-2017",
        "age_in_months": "28",
      }
    ]
  }
]

I would need this result:

[
  {
    "oldest":
      {
        "name": "dog2",
        "registered": "7-18-2017",
        "age_in_months": "28",
      }
  }
]

I am using this query

select t1.animals from `bucket` t1 use keys "myKey";

But I have no idea how to extract just part from an array

Body:
Try these steps:

Extract the nested animal information using UNNEST,

Find the animal with the maximum age using MAX, and

Take another pass over the animals and find the one with the maximum age using a subquery

Steps 1 and 2 are achieved with this query

SELECT RAW MAX(animals.age_in_months)
    FROM `bucket` USE KEYS "myKey" UNNEST animals

Step 3 uses UNNEST again, but this time we use the output of the previous query to select those animals with the maximum age. This approach will pick all animals with the maximum age.

Here's the complete query:

SELECT animal
  FROM `bucket` b USE KEYS "myKey" UNNEST animals animal
    WHERE animal.age_in_months IN
      (SELECT RAW MAX(animals.age_in_months)
        FROM `bucket` USE KEYS "myKey" UNNEST animals);

And here's the result for your example:

[
  {
    "animal": {
      "age_in_months": "28",
      "name": "dog2",
      "registered": "7-18-2017"
    }
  }
]


问:
optimise code into linq expression
I have an observable collection I want to remove an element from.  I have tried using the linq .Where syntax but i am getting stuck with the casting.

```<code>public class Atc
{
    public string Code { get; set; }
    public string Description { get; set; }
    public string ParentDescriptions { get; set; }
}
</code>```

i have defined the observable collection of medicines,

```<code>public ObservableCollection<Atc> MedicinesObservableCollection
</code>```

and i have a method to filter out the item from the collection that works:

```<code>private void RemoveMedicineListItem(string code)
{
    var filteredCollection = new ObservableCollection<Atc>();
    foreach (var item in MedicinesObservableCollection)
    {
        if (item.Code != code)
        {
            filteredCollection.Add(item);
        }
    }
    MedicinesObservableCollection = filteredCollection;
}
</code>```

I have tried:

```<code>(ObservableCollection<Atc>)MedicinesObservableCollection.Where(x => x.Code != code);
</code>```

but this gets a runtime exception
System.InvalidCastException: 'Unable to cast object of type 'WhereEnumerableIterator1[Atc]' to type 'System.Collections.ObjectModel.ObservableCollection1[Atc]'.'

i get this is something to do with the linq enumerables but i am out of my depth.

答:
Linq doesn't return a collection of the same type as the input. See this. So your cast to ObservableCollection<Atc> fails as it's some internal implementation of IEnumerable, not an ObservableCollection.

The solution is just to create a new ObservableCollection:

```<code>var items = new ObservableCollection<Atc>(MedicinesObservableCollection.Where(x => x.Code != code));
</code>```

Title: optimise code into linq expression

Body:
I have an observable collection I want to remove an element from.  I have tried using the linq .Where syntax but i am getting stuck with the casting.

public class Atc
{
    public string Code { get; set; }
    public string Description { get; set; }
    public string ParentDescriptions { get; set; }
}

i have defined the observable collection of medicines,

public ObservableCollection<Atc> MedicinesObservableCollection

and i have a method to filter out the item from the collection that works:

private void RemoveMedicineListItem(string code)
{
    var filteredCollection = new ObservableCollection<Atc>();
    foreach (var item in MedicinesObservableCollection)
    {
        if (item.Code != code)
        {
            filteredCollection.Add(item);
        }
    }
    MedicinesObservableCollection = filteredCollection;
}

I have tried:

(ObservableCollection<Atc>)MedicinesObservableCollection.Where(x => x.Code != code);

but this gets a runtime exception
System.InvalidCastException: 'Unable to cast object of type 'WhereEnumerableIterator1[Atc]' to type 'System.Collections.ObjectModel.ObservableCollection1[Atc]'.'

i get this is something to do with the linq enumerables but i am out of my depth.

Body:
Linq doesn't return a collection of the same type as the input. See this. So your cast to ObservableCollection<Atc> fails as it's some internal implementation of IEnumerable, not an ObservableCollection.

The solution is just to create a new ObservableCollection:

var items = new ObservableCollection<Atc>(MedicinesObservableCollection.Where(x => x.Code != code));


问:
How to install flickity carousel with vuejs and nuxtjs
I'm a new vuejs developer. I have study vueje for a while and now I decided to develop a project using vuejs.

So I learn about nuxtjs which is server side rendering. everything goes well. I can use bootstrap4 with my project.

Now I would like to use flickity carousel https://flickity.metafizzy.co on my project and I found that there is a vuejs package on https://github.com/drewjbartlett/vue-flickity

I follow the instruction how to install this component to my project by

```<code>npm install vue-flickity --save
</code>```

and put on some code

```<code><script>
  import Logo from '~/components/Logo.vue'
  import Searchbar from '~/components/Searchbar.vue'
  import axios from 'axios'
  import Flickity from 'vue-flickity';

  export default {
    data () {
      return {
        has_location: false,
        flickityOptions: {
          initialIndex: 3,
          prevNextButtons: false,
          pageDots: false,
          wrapAround: true
        }
      }
    },
    components: {
      Logo,
      Searchbar,
      Flickity
    }
  }
</script>
</code>```

but it show window is not defined

I have try this with another component like google map, it's show the same error.

Please tell me what wrong did I do and how to install new component to the project.

Thank you.

答:
Nuxt.js use SSR to render your website server side, therefore window object is not accessible on node.js environment.

What you need to do is use the built-in no-ssr component to prevent Nuxt.js to render it on the server side.

You can simply do this:

<no-ssr>
  <Flickity :options="...">

  </Flickity>
</no-ssr>
```
<blockquote>
<p><strong>UPDATE:</strong> If you still get an error at this point, then load Flickity in
a custom Plugin that you will load with <code>ssr</code> disabled</p>
</blockquote>
<p>Create a file named <code>plugins/VueFlickity.js</code></p>
<pre class="lang-js prettyprint-override"><code>import Vue from 'vue'
import Flickity from 'vue-flickity'

Vue.component('Flickity', Flickity)
</code>```

Then in your nuxt.config.js your add:

module.exports = {
  // ...
  plugins: [
    { src: '~/plugins/VueFlickity.js', ssr: false }
  ]
}
```
<p>Don't forget to remove the Flickity local component registration:</p>
<pre class="lang-js prettyprint-override"><code>components: {
  Logo,
  Searchbar
  // Flickity <-- remove this line
}
</code>```

This was tested and is now fully working.

Body:
I'm a new vuejs developer. I have study vueje for a while and now I decided to develop a project using vuejs.

So I learn about nuxtjs which is server side rendering. everything goes well. I can use bootstrap4 with my project.

Now I would like to use flickity carousel https://flickity.metafizzy.co on my project and I found that there is a vuejs package on https://github.com/drewjbartlett/vue-flickity

I follow the instruction how to install this component to my project by

npm install vue-flickity --save

and put on some code

but it show window is not defined

I have try this with another component like google map, it's show the same error.

Please tell me what wrong did I do and how to install new component to the project.

Thank you.

Body:
Nuxt.js use SSR to render your website server side, therefore window object is not accessible on node.js environment.

What you need to do is use the built-in no-ssr component to prevent Nuxt.js to render it on the server side.

You can simply do this:

<no-ssr>
  <Flickity :options="...">
    <!-- slides -->
  </Flickity>
</no-ssr>

UPDATE: If you still get an error at this point, then load Flickity in
a custom Plugin that you will load with ssr disabled

Create a file named plugins/VueFlickity.js

import Vue from 'vue'
import Flickity from 'vue-flickity'

Vue.component('Flickity', Flickity)

Then in your nuxt.config.js your add:

module.exports = {
  // ...
  plugins: [
    { src: '~/plugins/VueFlickity.js', ssr: false }
  ]
}

Don't forget to remove the Flickity local component registration:

components: {
  Logo,
  Searchbar
  // Flickity <-- remove this line
}

This was tested and is now fully working.

ContentLicense: CC BY-SA 4.0


问:
Select where date falls within range
Codeigniter/PHP:

This is my current db query:

```<code>$pass_check = $this->CI->db->select('code')->from('coupons')->where(array('title'=>'Booyah'))->get();
$pass_check = $pass_check->result_array();
</code>```

There are two other fields: 'exp_date', and 'start_date'. These represent when the coupon should be available and when it should not.

How can I only select codes/coupons that fall within the applicable date range in the db?

Does that make sense?

答:
The SQL statement to select values between two dates would be something along these lines:

```<code>SELECT code
FROM coupons
WHERE title = 'Booyah'
AND CURRENT_DATE BETWEEN start_date and exp_date;
</code>```

I'm sure you can make the appropriate substitutions for CodeIgniter.

AKA, if the start_date is less than
  today, don't get it, and if today is
  after the exp_date don't get it.

But I'm assuming you meant "E.G., if today is less than start_date, don't get it, and if today is greater than exp_date, don't get it."

ContentLicense: CC BY-SA 2.5

Title: Select where date falls within range

Body:
Codeigniter/PHP:

This is my current db query:

$pass_check = $this->CI->db->select('code')->from('coupons')->where(array('title'=>'Booyah'))->get();
$pass_check = $pass_check->result_array();

There are two other fields: 'exp_date', and 'start_date'. These represent when the coupon should be available and when it should not.

How can I only select codes/coupons that fall within the applicable date range in the db?

Does that make sense?

Body:
The SQL statement to select values between two dates would be something along these lines:

SELECT code
FROM coupons
WHERE title = 'Booyah'
AND CURRENT_DATE BETWEEN start_date and exp_date;

I'm sure you can make the appropriate substitutions for CodeIgniter.

AKA, if the start_date is less than
  today, don't get it, and if today is
  after the exp_date don't get it.

But I'm assuming you meant "E.G., if today is less than start_date, don't get it, and if today is greater than exp_date, don't get it."


问:
Java Array/List with stable index on remove
I'm looking for a data structure like ArrayList which elements don't get reindexed after removing a single one from it.

As an example scenario, Consider having a list as following psoudocode:

```<code>A(0) = m
A(1) = n
A(2) = o
A(3) = p
A(4) = q
</code>```

Using ArrayAdapter, issuing a A.remove(2) results in:

```<code>A(0) = m
A(1) = n
A(2) = p      // index decremented
A(3) = q      // index decremented
</code>```

which is not my desired behaviour. I'm looking for a list/array/map/set/collection/whatever which gives a result like this:

```<code>A(0) = m
A(1) = n
A(3) = p      // index persisted
A(4) = q      // index persisted
</code>```

It "can" be done using a integer counter combined with a Map but i'm wondering if a cleaner solution is already available.

Dirty approach using Map and integer counter:

```<code>HashMap<Integer, Object> map = new HashMap<>();
int indexCounter = 0;

public void insertItem(Object o){
    map.put(indexCounter, o);
    indexCounter++;
}
</code>```

Any ideas?

Edit:
To clearify, by m, n, o, ... i mean different values. These are not necessarily string and can be any kind of objects. That's a pseudocode.

More than that, Using NULL or mock values would not be an option in my case. Although, i'm looking for a general solution, not a specific one for my case. Thanks for sharing btw.

Edit 2:
Actually, im looking for a data structure, not a hack or trick. Thus, if there is not such a thing provided in Java, the correct answer to this question would be a straight conclusive "No, there isn't such a thing".

答:
"Actually, im looking for a data structure, not a hack or trick."

That is not a valid distinction unless you can define the difference between a "data structure" and a "hack" or "trick".

In your example, you say that the data structure / API / whatever, need to give you the following after deletion of the 3rd element:

```<code>A(0) maps to m
A(1) maps to n
A(3) maps to p
A(4) maps to q
</code>```

but what you don't say is what should happen if someone asks what A(2) maps to.  There are multiple possible answers, but the most plausible are:

it maps to null

it maps to some distinguished String; e.g. ""

it doesn't map; e.g. you get an exception.

All of these can be represented using a thin wrapper for a Map<Integer, String> where the key is the element index.  You could use a HashMap or a TreeMap, depending on other requirements for this data structure.

An alternative would be to use Android's SparseArray class.  This behaves like a map from int to Object, but it doesn't implement the standard Map API.  That allows them to use a much more compact representation than is possible using a HashMap or TreeMap.

Under the hood, SparseArray uses paired arrays of int and Object. It arranges that the int values are ordered so that they can be searched using simple binary search.  The downside is that lookup is O(log N) and insertion can be O(N). (Check the Android source code for the details.)

Body:
I'm looking for a data structure like ArrayList which elements don't get reindexed after removing a single one from it.

As an example scenario, Consider having a list as following psoudocode:

A(0) = m
A(1) = n
A(2) = o
A(3) = p
A(4) = q

Using ArrayAdapter, issuing a A.remove(2) results in:

A(0) = m
A(1) = n
A(2) = p      // index decremented
A(3) = q      // index decremented

which is not my desired behaviour. I'm looking for a list/array/map/set/collection/whatever which gives a result like this:

A(0) = m
A(1) = n
A(3) = p      // index persisted
A(4) = q      // index persisted

It "can" be done using a integer counter combined with a Map but i'm wondering if a cleaner solution is already available.

Dirty approach using Map and integer counter:

HashMap<Integer, Object> map = new HashMap<>();
int indexCounter = 0;

public void insertItem(Object o){
    map.put(indexCounter, o);
    indexCounter++;
}

Any ideas?

Edit:
To clearify, by m, n, o, ... i mean different values. These are not necessarily string and can be any kind of objects. That's a pseudocode.

More than that, Using NULL or mock values would not be an option in my case. Although, i'm looking for a general solution, not a specific one for my case. Thanks for sharing btw.

Edit 2:
Actually, im looking for a data structure, not a hack or trick. Thus, if there is not such a thing provided in Java, the correct answer to this question would be a straight conclusive "No, there isn't such a thing".

Body:
"Actually, im looking for a data structure, not a hack or trick."

That is not a valid distinction unless you can define the difference between a "data structure" and a "hack" or "trick".

In your example, you say that the data structure / API / whatever, need to give you the following after deletion of the 3rd element:

A(0) maps to m
A(1) maps to n
A(3) maps to p
A(4) maps to q

but what you don't say is what should happen if someone asks what A(2) maps to.  There are multiple possible answers, but the most plausible are:

it maps to null

it maps to some distinguished String; e.g. ""

it doesn't map; e.g. you get an exception.

All of these can be represented using a thin wrapper for a Map<Integer, String> where the key is the element index.  You could use a HashMap or a TreeMap, depending on other requirements for this data structure.

An alternative would be to use Android's SparseArray class.  This behaves like a map from int to Object, but it doesn't implement the standard Map API.  That allows them to use a much more compact representation than is possible using a HashMap or TreeMap.

Under the hood, SparseArray uses paired arrays of int and Object. It arranges that the int values are ordered so that they can be searched using simple binary search.  The downside is that lookup is O(log N) and insertion can be O(N). (Check the Android source code for the details.)


问:
Command not found when using bash script to ssh remote machine
I am trying to write a bash script and I am a newbie at that.

Everything is working beside the thing that some particular command are giving me the error

```<code>./start_components1.sh: line 17: cmd1: command not found
</code>```

They are some specific commands of my machine and I think they are related somehow to the thing that when I ssh, through the bash script, into the machine the environment is not loaded. I could be wrong.

Anyway, what happens is that if I ssh normally into my machine from a terminal and then execute the command it works flawlessly.

When I try to do the same through a bash script it tells me command not found.

I googled a lot and tried different things. Nothing worked.

Here my script if it can help:

```<code>#!/bin/bash

USERNAME=odroid

while getopts r:d:p:f: option
do
 case "${option}"
 in
 r) ROBOT=${OPTARG};;
 esac
done

for HOSTNAME in ${ROBOT}; do
    ssh -l ${USERNAME} "robot${HOSTNAME}" "./start_components${HOSTNAME}.sh; ls"
done
</code>```

EDIT: I thought it was working After following the hint by @PauloScardine I also realized that the permissions of my file were not set to executable so I sudo chmod +x fileToExecute
I thought this solved my problem but:
It is still not working. The command are executed without any error (it seems) but they are not really executed. Example: if I go in ssh (without bash script) on my machine and I do /opt/openrobots/bin/pom-ros I see that my component I want to launch is launched, I get some output and so on. When I launch the start_components2.sh file which should launch /opt/openrobots/bin/pom-ros I do not see any output and I am sure that the component is not launched because I have no effect :(

Thanks in advance

答:
Command not found usually means, that it cannot find it in the current directory as you used a dot for execution.

Try to put a full path to the script. Something like:

```<code>ssh -l ${USERNAME} "robot${HOSTNAME}" "/home/${USERNAME}/start_components${HOSTNAME}.sh; ls"
</code>```

However this will only work when the script start_componets will be in home directory of the user behind ${USERNAME} variable

Body:
I am trying to write a bash script and I am a newbie at that.

Everything is working beside the thing that some particular command are giving me the error

./start_components1.sh: line 17: cmd1: command not found

They are some specific commands of my machine and I think they are related somehow to the thing that when I ssh, through the bash script, into the machine the environment is not loaded. I could be wrong.

Anyway, what happens is that if I ssh normally into my machine from a terminal and then execute the command it works flawlessly.

When I try to do the same through a bash script it tells me command not found.

I googled a lot and tried different things. Nothing worked.

Here my script if it can help:

#!/bin/bash

USERNAME=odroid

while getopts r:d:p:f: option
do
 case "${option}"
 in
 r) ROBOT=${OPTARG};;
 esac
done

for HOSTNAME in ${ROBOT}; do
    ssh -l ${USERNAME} "robot${HOSTNAME}" "./start_components${HOSTNAME}.sh; ls"
done

EDIT: I thought it was working After following the hint by @PauloScardine I also realized that the permissions of my file were not set to executable so I sudo chmod +x fileToExecute
I thought this solved my problem but:
It is still not working. The command are executed without any error (it seems) but they are not really executed. Example: if I go in ssh (without bash script) on my machine and I do /opt/openrobots/bin/pom-ros I see that my component I want to launch is launched, I get some output and so on. When I launch the start_components2.sh file which should launch /opt/openrobots/bin/pom-ros I do not see any output and I am sure that the component is not launched because I have no effect :(

Thanks in advance

Body:
Command not found usually means, that it cannot find it in the current directory as you used a dot for execution.

Try to put a full path to the script. Something like:

ssh -l ${USERNAME} "robot${HOSTNAME}" "/home/${USERNAME}/start_components${HOSTNAME}.sh; ls"

However this will only work when the script start_componets will be in home directory of the user behind ${USERNAME} variable


问:
Count from hasManyThrough relationship with eager loading (need only Count)

I only need the count, don't want to retrive the results or perform query each time for each row. This is why I want eager loading.

I have 3 tables like the following:

```<code>Admins
    id

Posts
    id
    admin_id

Comments
    id
    user_id    //nullable (null if comment from admin)
    admin_id   //nullable (null if comment from user)
    news_id
</code>```

Now I want to retrieve all the posts from a single admin and all the comments count from those posts, without retrieving all the comments for posts, ONLY COUNT of comments,
With eager loading to avoid n+1 query issue;

Here I think we should make a relation to be used with eager loading like the following:

```<code>//admin model
public function commentsCountRelation()
        {
            return $this->hasManyThrough(Comment::class, News::class, 'admin_id', 'news_id')
                ->selectRaw('news_id, count(*) as count')
                ->groupBy('news_id');

        }
</code>```

--Look Here I used hasManyThrough relation because, news_id is not in Admins table.

Then I should make an attribute, to access the count easyly, like:

```<code>public function getCommentsCountAttribute()
    {
        return $this->commentsCountRelation->first()->count ?? 0;
    }
</code>```

Then access it like:

```<code>$admin = Admin::with('commentsCountRelation')->findOrFail($id);
$admin->commentsCount;
</code>```

But it always returns null, why is that?

The following works for hasMany & belongsTo, I've used it on my other models like:

```<code>//relation
public function ordersCountRelation()
    {
        return $this->hasOne(Order::class)->selectRaw('user_id, count(*) as count')
            ->groupBy('user_id');

    }

//attribute
public function getOrdersCountAttribute()
    {
        return $this->ordersCountRelation->count ?? 0;
    }

//Then accessed like:
$user = User::with('ordersCountRelation')->find($id);
$user->ordersCount; //return only count
</code>```

Any help will be highly appreciated

答:
there is no need for using hasManyThrough.

just use some relations and withCount method:

$admin->posts->withCount('comments')->get();

then you can access it with: $comments_count

Body:
I only need the count, don't want to retrive the results or perform query each time for each row. This is why I want eager loading.

I have 3 tables like the following:

Admins
    id

Posts
    id
    admin_id

Comments
    id
    user_id    //nullable (null if comment from admin)
    admin_id   //nullable (null if comment from user)
    news_id

Now I want to retrieve all the posts from a single admin and all the comments count from those posts, without retrieving all the comments for posts, ONLY COUNT of comments,
With eager loading to avoid n+1 query issue;

Here I think we should make a relation to be used with eager loading like the following:

//admin model
public function commentsCountRelation()
        {
            return $this->hasManyThrough(Comment::class, News::class, 'admin_id', 'news_id')
                ->selectRaw('news_id, count(*) as count')
                ->groupBy('news_id');

        }

--Look Here I used hasManyThrough relation because, news_id is not in Admins table.

Then I should make an attribute, to access the count easyly, like:

public function getCommentsCountAttribute()
    {
        return $this->commentsCountRelation->first()->count ?? 0;
    }

Then access it like:

$admin = Admin::with('commentsCountRelation')->findOrFail($id);
$admin->commentsCount;

But it always returns null, why is that?

The following works for hasMany & belongsTo, I've used it on my other models like:

//relation
public function ordersCountRelation()
    {
        return $this->hasOne(Order::class)->selectRaw('user_id, count(*) as count')
            ->groupBy('user_id');

    }

//attribute
public function getOrdersCountAttribute()
    {
        return $this->ordersCountRelation->count ?? 0;
    }

//Then accessed like:
$user = User::with('ordersCountRelation')->find($id);
$user->ordersCount; //return only count

Any help will be highly appreciated


问:
Find value in XML
I have a value in which I store XML.

I want to search for this value into the XML:

```<code><transaction_type>authorize</transaction_type>

<transaction_type>authorize3d</transaction_type>
</code>```

If there is a value "3d" I want to edit the XML file. If not I want to send it.

```<code>def web_request(request_body)

    //Search here in request body for 3d value
    if request_body.include? "3d"
     puts "String include '3d'"
    else
     puts "String does not include '3d'"
    end

    .........
    request_body
  end
</code>```

How I can implement this properly?

答:
Use regexp to find a node with 3d text:

```<code>if request_body =~ /<transaction_type>.*?3d<\/transaction_type>/
</code>```

Too you can use Nokogiri to parse xml and find a node with this value but in your case, it's overhead.

Title: Find value in XML

Body:
I have a value in which I store XML.

I want to search for this value into the XML:

<transaction_type>authorize</transaction_type>

<transaction_type>authorize3d</transaction_type>

If there is a value "3d" I want to edit the XML file. If not I want to send it.

def web_request(request_body)

    //Search here in request body for 3d value
    if request_body.include? "3d"
     puts "String include '3d'"
    else
     puts "String does not include '3d'"
    end

    .........
    request_body
  end

How I can implement this properly?

Body:
Use regexp to find a node with 3d text:

if request_body =~ /<transaction_type>.*?3d<\/transaction_type>/

Too you can use Nokogiri to parse xml and find a node with this value but in your case, it's overhead.


问:
Hibernate Error: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session
I have two user Objects and while I try to save the object using

```<code>session.save(userObj);
</code>```

I am getting the following error:

```<code>Caused by: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session:
[com.pojo.rtrequests.User#com.pojo.rtrequests.User@d079b40b]
</code>```

I am creating the session using

```<code>BaseHibernateDAO dao = new BaseHibernateDAO();

rtsession = dao.getSession(userData.getRegion(),
                           BaseHibernateDAO.RTREQUESTS_DATABASE_NAME);

rttrans = rtsession.beginTransaction();
rttrans.begin();

rtsession.save(userObj1);
rtsession.save(userObj2);

rtsession.flush();
rttrans.commit();

rtsession.close(); // in finally block
</code>```

I also tried doing the session.clear() before saving, still no luck.

This is for the first I am getting the session object when a user request comes, so I am getting why is saying that object is present in session.

Any suggestions?

答:
Late to the party, but may help for coming users -

I got this issue when i select a record using getsession()  and again update another record with same identifier using same session causes the issue. Added code below.

```<code>Customer existingCustomer=getSession().get(Customer.class,1);
Customer customerFromUi;// This customer details comiong from UI with identifer 1

getSession().update(customerFromUi);// Here the issue comes
</code>```

This should never be done . Solution is either evict session before update or change business logic.

Body:
I have two user Objects and while I try to save the object using

session.save(userObj);

I am getting the following error:

Caused by: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session:
[com.pojo.rtrequests.User#com.pojo.rtrequests.User@d079b40b]

I am creating the session using

BaseHibernateDAO dao = new BaseHibernateDAO();

rtsession = dao.getSession(userData.getRegion(),
                           BaseHibernateDAO.RTREQUESTS_DATABASE_NAME);

rttrans = rtsession.beginTransaction();
rttrans.begin();

rtsession.save(userObj1);
rtsession.save(userObj2);

rtsession.flush();
rttrans.commit();

rtsession.close(); // in finally block

I also tried doing the session.clear() before saving, still no luck.

This is for the first I am getting the session object when a user request comes, so I am getting why is saying that object is present in session.

Any suggestions?

Body:
Late to the party, but may help for coming users -

I got this issue when i select a record using getsession()  and again update another record with same identifier using same session causes the issue. Added code below.

Customer existingCustomer=getSession().get(Customer.class,1);
Customer customerFromUi;// This customer details comiong from UI with identifer 1

getSession().update(customerFromUi);// Here the issue comes

This should never be done . Solution is either evict session before update or change business logic.


问:
How to optimize the following perl code?
In the below code I tried to print every line along with its line number. Is there any other way to optimize the below code using Perl?</p>

```<code>#!/usr/bin/perl
use strict;
use warnings;
open my $fh,"<","exercise.csv";
while(<$fh>)
{
   print "$.=====>$_";
}
close $fh;
</code>```

答:
No.

When you're optimising, you look at things that are less efficient ways of accomplishing the goal. That's often algorithmic, and looking at where looping is occurring is a good start.

But then there's resource usage optimisation - disk IO is often the most expensive operation - but you need to do all the IO that you're doing, and you're not doing any redundant IO.

And sometimes - system calls or 'shelling out' to other binaries (via system or backticks) can incur overhead. But you don't do that either.

Basically - your code is just not complicated enough to have any significant inefficiencies.

Body:
In the below code I tried to print every line along with its line number. Is there any other way to optimize the below code using Perl?

#!/usr/bin/perl
use strict;
use warnings;
open my $fh,"<","exercise.csv";
while(<$fh>)
{
   print "$.=====>$_";
}
close $fh;


问:
I'm using TextMate at the moment, any reason for moving to Coda or MacVim?
I'm using TextMate at the moment as editor and it seems to be good for many tasks. Coda and MacVim are quite popular as well, so I was just wondering if there are any reasons/advantages to use those Editors instead of TextMate.

Other solutions are accepted as well.

答:
Not to start another editor flame war, but why not Emacs? I use textMate sometimes still, but Emacs runs across all platforms. I use it for R with ESS, Python, and LaTeX. </p>

<p>edit- i should add I'am unfamiliar with Coda. Whatever works best for you! </p>

Body:
Not to start another editor flame war, but why not Emacs? I use textMate sometimes still, but Emacs runs across all platforms. I use it for R with ESS, Python, and LaTeX.

edit- i should add I'am unfamiliar with Coda. Whatever works best for you!


问:
changing img src of another div with jquery?
I have a trouble changing the src of my image with jquery :

I have my div projectName with all the buttons which will be clicked on for changing the images.
Those images will be contained in another div called projectImg.

But when I click on my buttons, nothing is happening. Someone know if there is a way to make my jquery work??

EDIT : Found the error ! I only needed to put a type="button" into my html buttons. Thanks for the help though  !

$(document).ready(function(){
 $('.sliding').click(function(){
     var url_img = $(this).attr('id');
     $('#projImg img').attr('src',url_img)
   });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="galerie" class="galerie-section content-section">
      <div class="container">
        <div class="row">

          <div class="container-fluid projectName text-center col-sm-6" id="projName">
              <button id="img/img1.jpg" class="sliding" type="button">img1</button>
              <button id="img/img2.jpg" class="sliding" type="button">img2</button>
              <button id="img/img3.jpg" class="sliding" type="button">img3</button>
          </div>

          <div class="container-fluid projectImg col-sm-6" id="projImg">
            <img src="img/img1.jpg" class="img-fluid img-galerie">
          </div>
        </div>
      </div>
    </section></code>```

答: You have wrong selector - your selector is to div, not to img. This should be $('#projImage img').attr('src',url_img)

Body:
I have a trouble changing the src of my image with jquery :

I have my div projectName with all the buttons which will be clicked on for changing the images.
Those images will be contained in another div called projectImg.

But when I click on my buttons, nothing is happening. Someone know if there is a way to make my jquery work??

EDIT : Found the error ! I only needed to put a type="button" into my html buttons. Thanks for the help though  !

$(document).ready(function(){
 $('.sliding').click(function(){
     var url_img = $(this).attr('id');
     $('#projImg img').attr('src',url_img)
   });
});

              <button id="img/img1.jpg" class="sliding" type="button">img1</button>
              <button id="img/img2.jpg" class="sliding" type="button">img2</button>
              <button id="img/img3.jpg" class="sliding" type="button">img3</button>


问:
Create an ID (row number) column
I need to create a column with unique ID, basically add the row number as an own column.  My current data frame looks like this:

```<code>   V1  V2
1  23  45
2  45  45
3  56  67
</code>```

How to make it look like this:

```<code>V1  V2  V3
1  23  45
2  45  45
3  56  67
</code>```

?

Many thanks

答:
data.table solution

Easier syntax and much faster

```<code>library(data.table)

dt <- data.table(V1=c(23, 45, 56), V2=c(45, 45, 67))

setnames(dt, c("V2", "V3")) # changing column names
dt[, V1 := .I] # Adding ID column
</code>```

Title: Create an ID (row number) column

Body:
I need to create a column with unique ID, basically add the row number as an own column.  My current data frame looks like this:

   V1  V2
1  23  45
2  45  45
3  56  67

How to make it look like this:

V1  V2  V3
1  23  45
2  45  45
3  56  67

?

Many thanks

Body:
data.table solution

Easier syntax and much faster

library(data.table)

dt <- data.table(V1=c(23, 45, 56), V2=c(45, 45, 67))

setnames(dt, c("V2", "V3")) # changing column names
dt[, V1 := .I] # Adding ID column


问:
How to do "decode 'unicode-escape'" only on \xhh characters in a string in Perl?
I have a file with the following content with some characters are UTF-8 hex encoded in the string literal:

```<code><root>
<element type=\"1\">\"Hello W\xC3\x96rld\"</element>
</root>
</code>```

I want to read the file and decode the UTF-8 hex encoded characters in the file to the actual unicode characters they represent and then write to a new file.  Given the above content, the new file should look like the following when you open it in a text editor with UTF-8 encoding:

```<code><root>
<element type=\"1\">\"Hello WÖrld\"</element>
</root>
</code>```

Notice the double quotes are still escaped and the UTF-8 hex encoded \xC3\x96 has now become Ö (U+00D6 LATIN CAPITAL LETTER O WITH DIAERESIS).

I have got code that is partially working, as follows:

```<code>#! /usr/bin/perl -w

use strict;
use Encode::Escape;

while (<>)
{
    # STDOUT is redirected to a new file.
    print decode 'unicode-escape', $_;
}
</code>```

The problem however, all the other escape sequences such as \" are being decoded as well by decode 'unicode-escape', $_.  So in the end, I get the following:

```<code><root>
<element type="1">"Hello WÖrld"</element>
</root>
</code>```

I have tried reading the file in UTF-8 encoding and/or using Unicode::Escape::unescape such as

```<code>open(my $UNICODESFILE, "<:encoding(UTF-8)", shift(@ARGV));
Unicode::Escape::unescape($line);
</code>```

but neither of them decode the \xhh escape sequences.

Basically all I want is the behavior of decode 'unicode-escape', $_, but that it should only decode on \xhh escape sequences and ignore other escape sequences.

Is this possible?  Is using decode 'unicode-escape', $_ appropriate for this case?  Any other way?  Thanks!

答:
Find groups of \xNN characters and process them, I guess:</p>

```<code>s{((?:\\x[0-9A-Fa-f]{2})+)}{decode 'unicode-escape', $1}ge
</code>```

Body:
I have a file with the following content with some characters are UTF-8 hex encoded in the string literal:

<root>
<element type=\"1\">\"Hello W\xC3\x96rld\"</element>
</root>

I want to read the file and decode the UTF-8 hex encoded characters in the file to the actual unicode characters they represent and then write to a new file.  Given the above content, the new file should look like the following when you open it in a text editor with UTF-8 encoding:

<root>
<element type=\"1\">\"Hello WÖrld\"</element>
</root>

Notice the double quotes are still escaped and the UTF-8 hex encoded \xC3\x96 has now become Ö (U+00D6 LATIN CAPITAL LETTER O WITH DIAERESIS).

I have got code that is partially working, as follows:

#! /usr/bin/perl -w

use strict;
use Encode::Escape;

while (<>)
{
    # STDOUT is redirected to a new file.
    print decode 'unicode-escape', $_;
}

The problem however, all the other escape sequences such as \" are being decoded as well by decode 'unicode-escape', $_.  So in the end, I get the following:

<root>
<element type="1">"Hello WÖrld"</element>
</root>

I have tried reading the file in UTF-8 encoding and/or using Unicode::Escape::unescape such as

open(my $UNICODESFILE, "<:encoding(UTF-8)", shift(@ARGV));
Unicode::Escape::unescape($line);

but neither of them decode the \xhh escape sequences.

Basically all I want is the behavior of decode 'unicode-escape', $_, but that it should only decode on \xhh escape sequences and ignore other escape sequences.

Is this possible?  Is using decode 'unicode-escape', $_ appropriate for this case?  Any other way?  Thanks!

Body:
Find groups of \xNN characters and process them, I guess:

s{((?:\\x[0-9A-Fa-f]{2})+)}{decode 'unicode-escape', $1}ge


问:
total of label click on two buttons
I have two UIButton if I click onto button1 the value of label1 is 250, if I click again onto button1 the value of label1 should be 0. The same logic is applied to my button2 and label2. I want to store the addition of label1 and label2 into label3.  . My code is:

```<code>func PickUpCarCost() {
            if (!isclick){
                imgCheck.image = UIImage(named: "check.png")
                isclick=true

                //Pickup fare conver into integer

                let PickUp = String(self.PickUpPrice)
                PickUpFare.text = PickUp
                self.pickCost = Int( PickUpFare.text!)
                self.PAyAmount = ((self.PayFareWithSecurity)+(self.pickCost))
                print("PaybleAmount: \(self.PAyAmount)")
                self.AmountPay1 = ((self.PAyAmount)+(self.DeliverCost))
                PaybleAmount.text=String(self.AmountPay1!)

            }
            else
            {
                imgCheck.image = UIImage(named: "uncheck.png")
                PickUpFare.text = "0"
                self.PickUpElse=Int(PickUpFare.text!)
                print("PickUpElse: \(self.PickUpElse)")
                self.PAyAmount = (self.PayFareWithSecurity)+(self.PickUpElse)
                PaybleAmount.text=String(self.PAyAmount!)
                isclick=false
            }
    }

    func CarDeliverCost() {
        if (!isclick){
            imgUnCheck.image = UIImage(named: "check.png")
            isclick=true
            let DeliverPrice = String(self.deliveryPrice)
            DeliverFare.text = DeliverPrice
            self.DeliverCost = Int(DeliverFare.text!)

            self.PAyAmount = ((self.PayFareWithSecurity)+(self.DeliverCost))

            print("PaybleAmount: \(self.PAyAmount)")

            PaybleAmount.text=String(self.PAyAmount!)

        }
        else
        {
            imgUnCheck.image = UIImage(named: "uncheck.png")
            let deliveryelse = String(0)
            DeliverFare.text = deliveryelse
            self.deliver = Int(DeliverFare.text!)
            PaybleAmount.text=String(self.PAyAmount!)
            isclick=false

        }
    }
</code>```

答:
The first issue that you're facing is that you are using the same boolean isClick for two different scenarios. Your logic is that the user could decide to click onto both buttons or a single one. So if I click onto the first button then your flag is turn on, since the second button also uses the same boolean then you'll get that uncheck behavior automatically.

Thus you should use two different booleans such as hasPressOntoFirstButton and hasPressOntoSecondButton, where both set to false at the beginning, and each variable is used in their respective scene.

You mentioned that you want to add the label1 to label2, the easier way would be add the variable that set these labels. i.e

```<code>let label1 = UILabel()
let label2 = UILabel()
let label3 = UILabel()

let data1: Double = 83.0
let data2: Double = 82.0

var total: Double { // have a computed variable to adds automatically
    return data1 + data2
}

label1.text = "\(data1)"
label2.text = "\(data2)"
label3.text = "\(data1 + data2)" // or "\(total)"
</code>```

Remarks:

(1) your naming convention are really misleading, you should separate UI object naming from data. i.e you can have deliveryFareLabel.text instead of DeliverFare.text

(2) avoid using !, unwrapped all optional using either nil coalescing ??, or if let or guard statements

Title: total of label click on two buttons

Body:
I have two UIButton if I click onto button1 the value of label1 is 250, if I click again onto button1 the value of label1 should be 0. The same logic is applied to my button2 and label2. I want to store the addition of label1 and label2 into label3.  . My code is:

func PickUpCarCost() {
            if (!isclick){
                imgCheck.image = UIImage(named: "check.png")
                isclick=true

                //Pickup fare conver into integer

                let PickUp = String(self.PickUpPrice)
                PickUpFare.text = PickUp
                self.pickCost = Int( PickUpFare.text!)
                self.PAyAmount = ((self.PayFareWithSecurity)+(self.pickCost))
                print("PaybleAmount: \(self.PAyAmount)")
                self.AmountPay1 = ((self.PAyAmount)+(self.DeliverCost))
                PaybleAmount.text=String(self.AmountPay1!)

            }
            else
            {
                imgCheck.image = UIImage(named: "uncheck.png")
                PickUpFare.text = "0"
                self.PickUpElse=Int(PickUpFare.text!)
                print("PickUpElse: \(self.PickUpElse)")
                self.PAyAmount = (self.PayFareWithSecurity)+(self.PickUpElse)
                PaybleAmount.text=String(self.PAyAmount!)
                isclick=false
            }
    }

    func CarDeliverCost() {
        if (!isclick){
            imgUnCheck.image = UIImage(named: "check.png")
            isclick=true
            let DeliverPrice = String(self.deliveryPrice)
            DeliverFare.text = DeliverPrice
            self.DeliverCost = Int(DeliverFare.text!)

            self.PAyAmount = ((self.PayFareWithSecurity)+(self.DeliverCost))

            print("PaybleAmount: \(self.PAyAmount)")

            PaybleAmount.text=String(self.PAyAmount!)

        }
        else
        {
            imgUnCheck.image = UIImage(named: "uncheck.png")
            let deliveryelse = String(0)
            DeliverFare.text = deliveryelse
            self.deliver = Int(DeliverFare.text!)
            PaybleAmount.text=String(self.PAyAmount!)
            isclick=false

        }
    }

Body:
The first issue that you're facing is that you are using the same boolean isClick for two different scenarios. Your logic is that the user could decide to click onto both buttons or a single one. So if I click onto the first button then your flag is turn on, since the second button also uses the same boolean then you'll get that uncheck behavior automatically.

Thus you should use two different booleans such as hasPressOntoFirstButton and hasPressOntoSecondButton, where both set to false at the beginning, and each variable is used in their respective scene.

You mentioned that you want to add the label1 to label2, the easier way would be add the variable that set these labels. i.e

let label1 = UILabel()
let label2 = UILabel()
let label3 = UILabel()

let data1: Double = 83.0
let data2: Double = 82.0

var total: Double { // have a computed variable to adds automatically
    return data1 + data2
}

label1.text = "\(data1)"
label2.text = "\(data2)"
label3.text = "\(data1 + data2)" // or "\(total)"

Remarks:

(1) your naming convention are really misleading, you should separate UI object naming from data. i.e you can have deliveryFareLabel.text instead of DeliverFare.text

(2) avoid using !, unwrapped all optional using either nil coalescing ??, or if let or guard statements


问:
How I can get back in singly linked list?
I have a singly linked list. From each node in the list, I can get to the next element. Is it possible instead to get to the previous element? Note that I cannot use a doubly linked list because of memory constraints.</p>

答:
If you have a node that you are sure of, is before the given node in a singly linked list, then you can make a function:-

```<code>    struct node* prev(struct node* before, struct student_detail* current)
    {
        struct student_detail* temp = before;
        while (temp->next != NULL)
        {
            if(temp->next == current)
            {
                return temp;
            }

            temp = temp-> next;
        }
        return NULL;
    }
</code>```

and use it as in

```<code>    example_node = prev(before, example_node);
</code>```

If you have head, you can always use that as the prev node.

Body:
If you have a node that you are sure of, is before the given node in a singly linked list, then you can make a function:-

    struct node* prev(struct node* before, struct student_detail* current)
    {
        struct student_detail* temp = before;
        while (temp->next != NULL)
        {
            if(temp->next == current)
            {
                return temp;
            }

            temp = temp-> next;
        }
        return NULL;
    }

and use it as in

    example_node = prev(before, example_node);

If you have head, you can always use that as the prev node.


问:
Why is my import of the containsString method not working?
I've written the simple Java script below in order to learn more about TDD, IntelliJ and Java itself.

```<code>import java.util.ArrayList;
import java.util.List;

import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.both;

public class JUnit_Dummy {

  private StringJoiner joiner;
  private List<String> strings;

  @Before
  public void setUp() throws Exception {
    strings = new ArrayList<String>();
    joiner = new StringJoiner();
  }
....

  @Test
  public void shouldContainBothStringsWhenListIsTwoStrings() {
    strings.add("one");
    strings.add("two");
    assertThat(joiner.join(strings),
        both(containsString("A")).
            and(containsString("B")));
  }

}
_____________

import java.util.List;

public class StringJoiner {
  public String join(List<String> strings) {
    if(strings.size() > 0) {
      return (strings.get(0);
    }
    return "";
  }
}
</code>```

I'm trying to use the "containsString" method inside an assertion, but IntelliJ keeps telling me that it "cannot resolve method 'containsString(java.lang.String)".  This despite the fact that the jUnit docs (http://junit.sourceforge.net/javadoc/org/junit/matchers/JUnitMatchers.html#containsString(java.lang.String)) tell me that this method does accept a String parameter.

I've tried swapping out various import statements, including the following:

```<code>import static org.hamcrest.Matcher.containsString;
import static org.hamcrest.Matcher.*;
import static org.hamcrest.CoreMatchers.*;
</code>```

The best that I get is a greyed-out import statement telling me that the import statement is unused.  Not sure what the problem is, any help would be appreciated.

UPDATE:

Here is the exact compiler error:

```<code>java: cannot find symbol
  symbol:   method containsString(java.lang.String)
  location: class JUnit_Dummy
</code>```

答:
I faced the same issue with a Spring Boot app.
Seems like this is a dependency ordering issue.. one of the dependencies mentioned in pom.xml before the "spring-boot-starter-test" artifact was overriding the hamcrest version.

So all I did was change the order (moved this dependency up):

```<code>    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>
</code>```

I'm using Spring Boot 1.5.7.RELEASE.

Body:
I've written the simple Java script below in order to learn more about TDD, IntelliJ and Java itself.

import java.util.ArrayList;
import java.util.List;

import org.junit.Before;
import org.junit.Test;

import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.CoreMatchers.is;
import static org.junit.Assert.assertThat;
import static org.junit.matchers.JUnitMatchers.both;

public class JUnit_Dummy {

  private StringJoiner joiner;
  private List<String> strings;

  @Before
  public void setUp() throws Exception {
    strings = new ArrayList<String>();
    joiner = new StringJoiner();
  }
....

  @Test
  public void shouldContainBothStringsWhenListIsTwoStrings() {
    strings.add("one");
    strings.add("two");
    assertThat(joiner.join(strings),
        both(containsString("A")).
            and(containsString("B")));
  }

}
_____________

import java.util.List;

public class StringJoiner {
  public String join(List<String> strings) {
    if(strings.size() > 0) {
      return (strings.get(0);
    }
    return "";
  }
}

I'm trying to use the "containsString" method inside an assertion, but IntelliJ keeps telling me that it "cannot resolve method 'containsString(java.lang.String)".  This despite the fact that the jUnit docs (http://junit.sourceforge.net/javadoc/org/junit/matchers/JUnitMatchers.html#containsString(java.lang.String)) tell me that this method does accept a String parameter.

I've tried swapping out various import statements, including the following:

import static org.hamcrest.Matcher.containsString;
import static org.hamcrest.Matcher.*;
import static org.hamcrest.CoreMatchers.*;

The best that I get is a greyed-out import statement telling me that the import statement is unused.  Not sure what the problem is, any help would be appreciated.

UPDATE:

Here is the exact compiler error:

java: cannot find symbol
  symbol:   method containsString(java.lang.String)
  location: class JUnit_Dummy

Body:
I faced the same issue with a Spring Boot app.
Seems like this is a dependency ordering issue.. one of the dependencies mentioned in pom.xml before the "spring-boot-starter-test" artifact was overriding the hamcrest version.

So all I did was change the order (moved this dependency up):

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
    </dependency>

I'm using Spring Boot 1.5.7.RELEASE.


问:
SELECT multivalues from same table in one row
I have the below table. as a reference table for values in the system.

```<code>Item    Item_code
Turkey  c01
KSA     c02
USA     c03
NY      s01
JED     s03
Dubai   j01
London  j02
.       .
.       .
.       .
</code>```

In the display page for users I want to show readable data " KSA, NY ..." not the codes. having the results in one row would save a lot code line.I don't want to do 5 select statements to get each value separately

example: I want to display the Item column of c02, s01 and s03 in one row.

desired result :

```<code>first Item     second Item    third Item ...
KSA             JED           NY
</code>```

this goes for 5 columns.

答:
One method uses conditional aggregation with the ANSI-standard row_number() function:

```<code>select max(case when seqnum = 1 then item end) as item_1,
       max(case when seqnum = 2 then item end) as item_2,
       max(case when seqnum = 3 then item end) as item_3,
       max(case when seqnum = 4 then item end) as item_4,
       max(case when seqnum = 5 then item end) as item_5
from (select t.*, row_number() over (order by item_code) as seqnum
      from t
       where item_code in ('c02', 's01', 's03')
     ) t;
</code>```

Body:
I have the below table. as a reference table for values in the system.

Item    Item_code
Turkey  c01
KSA     c02
USA     c03
NY      s01
JED     s03
Dubai   j01
London  j02
.       .
.       .
.       .

In the display page for users I want to show readable data " KSA, NY ..." not the codes. having the results in one row would save a lot code line.I don't want to do 5 select statements to get each value separately

example: I want to display the Item column of c02, s01 and s03 in one row.

desired result :

first Item     second Item    third Item ...
KSA             JED           NY

this goes for 5 columns.

Body:
One method uses conditional aggregation with the ANSI-standard row_number() function:

select max(case when seqnum = 1 then item end) as item_1,
       max(case when seqnum = 2 then item end) as item_2,
       max(case when seqnum = 3 then item end) as item_3,
       max(case when seqnum = 4 then item end) as item_4,
       max(case when seqnum = 5 then item end) as item_5
from (select t.*, row_number() over (order by item_code) as seqnum
      from t
       where item_code in ('c02', 's01', 's03')
     ) t;


问:
UITableViewCell Selected Background Color on Multiple Selection
```<code>// Doesn't work
cell.selectionStyle = .Blue
//Works when the selection is not multiple, if it's multiple with each selection the previous one disappear...
let cellBGView = UIView()
cellBGView.backgroundColor = UIColor(red: 0, green: 0, blue: 200, alpha: 0.4)
cell.selectedBackgroundView = cellBGView
</code>```

Any answer how to set background color of the cells which are selected?

答: You can also set cell's selectionStyle to.none in interface builder. The same solution as @AhmedLotfy provided, only from IB.

Body:
// Doesn't work
cell.selectionStyle = .Blue
//Works when the selection is not multiple, if it's multiple with each selection the previous one disappear...
let cellBGView = UIView()
cellBGView.backgroundColor = UIColor(red: 0, green: 0, blue: 200, alpha: 0.4)
cell.selectedBackgroundView = cellBGView

Any answer how to set background color of the cells which are selected?


问:
Sql Design Question
I have a table with 25 columns where 20 columns can have null values for some (30-40%) rows.
Now what is the cost of having rows with 20 null columns? Is this OK?

Or

is it a good design to have another table to store those 20 columns and add a ref to the first table?
This way I will only write to the second table only when there is are values.

I am using SQL server 2005. Will migrate to 2008 in future.

Only 20 columns are varchar, rest smallint, smalldate

What I am storing:
  These columns store different attributes of the row it belongs to. These attributes can be null sometimes.

The table will hold ~billion of rows

Please comment.

答:
It depends on the data types (40 nullable ints is going to basically take the same space as 40 non-nullable ints, regardless of the values).  In SQL Server, the space is fairly efficient with ordinary techniques.  In 2008, you do have the SPARSE feature.

If you do split the table vertically with an optional 1:1 relationship, there is a possibility of wrapping the two tables with a view and adding triggers on the view to make it updatable and hide the underlying implementation.

So there are plenty of options, many of which can be implemented after you see the data load and behavior.

Title: Sql Design Question


问:
Excel: Increasing/Decreasing number of columns in table based on number of coloured rows from different sheet
I am in the process of creating a costing summary workbook. My main summary sheet lists a job category and then 4 rows of cost breakdown before the next category is listed. On another sheet, I have a template that the user will make a copy of for each month, which breaks down weekly work hours and then allocates hours from each employee/plant to against a job category. Please see attached pictures.

Summary Sheet -
 Template Sheet

My goal is to have the number of columns on the template increase/decrease as categories are added to or removed from the summary sheet. I already have a cell that contains a count of coloured rows (category titles), and  i figure i should be able to use this to determine the amount of rows that need to be added to or removed from a table. I can't think of any ways for this to be done without macros or VBA code of some kind, which I am open to but I would like to minimise the use of.
Can anyone provide me with some code or a push in the right direction for this kind of function? Category names will be stored in column A, or my count is stored in B84. Columns for each category start from column S in the template sheet.

答:
Kyle, you can visit the following sites with a lot of vba beginners information.

http://www.excel-easy.com/vba.html
  http://www.homeandlearn.org/

https://www.tutorialspoint.com/vba/

Try implementing your idea using pseudo-code.

http://www.vikingcodeschool.com/software-engineering-basics/what-is-pseudo-coding

https://www.youtube.com/watch?v=4G0EYfrrDT8

https://www.khanacademy.org/computing/computer-programming/programming/good-practices/p/planning-with-pseudo-code

Once you be able to write your code and you are having some code error or problem you cannot find a solution in the web, come again and ask specific questions, there are a lot of experienced programmers that will be happy to help you to solve your coding problems.


问:
Run-time permission request is not working
I'm trying my first Android app using Run time permission with Kotlin, based on my understanding of this example but the permission request dialog never appears.

Did I make any error in writing the Kotlin equivalent of the Java code in the mentioned reference example?

The app assumes to call the pre-defined number upon clicking the button.

string.xml:

```<code><resources>
    <string name="app_name">Kotlin</string>
    <string name="title_activity_display">Call</string>
</resources>
</code>```

activity_main.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.home.kotlin.MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Display" />

</LinearLayout>
</code>```

MainActivity.kt:

```<code>package com.example.home.kotlin

import android.Manifest
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast

class MainActivity : AppCompatActivity() {

    private var mCall: Button? = null
    private var callIntent: Intent? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mCall = findViewById(R.id.button)

        mCall!!.setOnClickListener { _: View ->
            callIntent = Intent(Intent.ACTION_CALL)
            callIntent!!.data = Uri.parse("tel:0123456789")

            val hasCallPhone = checkSelfPermission(Manifest.permission.CALL_PHONE)
            if (hasCallPhone != PackageManager.PERMISSION_GRANTED) {
                if (!shouldShowRequestPermissionRationale(Manifest.permission.CALL_PHONE)) {
                    showMessageOKCancel("You need to allow access to dialer",
                    DialogInterface.OnClickListener { _, _ ->
                        requestPermissions(arrayOf(Manifest.permission.CALL_PHONE),
                                1)
                    })
                    return@setOnClickListener
                }
                requestPermissions(arrayOf(Manifest.permission.CALL_PHONE),
                        1)
                return@setOnClickListener
            }
        }
    }

    private fun showMessageOKCancel(message: String, okListener: DialogInterface.OnClickListener) {
        AlertDialog.Builder(this@MainActivity)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show()
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        when (requestCode) {
            1 -> if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                Toast.makeText(this@MainActivity, "Permission Granted", Toast.LENGTH_SHORT)
                        .show()
                startActivity(callIntent)
                this.finish()
            } else {
                // Permission Denied
                Toast.makeText(this@MainActivity, "Permission Denied", Toast.LENGTH_SHORT)
                        .show()
            }
            else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        }
    }

}
</code>```

答:
You need to add the permission to the manifest.xml too.</p>

```<code> <uses-permission android:name="android.permission.CALL_PHONE" />
</code>```

Body:
I'm trying my first Android app using Run time permission with Kotlin, based on my understanding of this example but the permission request dialog never appears.

Did I make any error in writing the Kotlin equivalent of the Java code in the mentioned reference example?

The app assumes to call the pre-defined number upon clicking the button.

string.xml:

<resources>
    <string name="app_name">Kotlin</string>
    <string name="title_activity_display">Call</string>
</resources>

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.home.kotlin.MainActivity">

    <Button
        android:id="@+id/button"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Display" />

</LinearLayout>

MainActivity.kt:

package com.example.home.kotlin

import android.Manifest
import android.app.AlertDialog
import android.content.DialogInterface
import android.content.Intent
import android.content.pm.PackageManager
import android.net.Uri
import android.support.v7.app.AppCompatActivity
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.Toast

class MainActivity : AppCompatActivity() {

    private var mCall: Button? = null
    private var callIntent: Intent? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        mCall = findViewById(R.id.button)

        mCall!!.setOnClickListener { _: View ->
            callIntent = Intent(Intent.ACTION_CALL)
            callIntent!!.data = Uri.parse("tel:0123456789")

            val hasCallPhone = checkSelfPermission(Manifest.permission.CALL_PHONE)
            if (hasCallPhone != PackageManager.PERMISSION_GRANTED) {
                if (!shouldShowRequestPermissionRationale(Manifest.permission.CALL_PHONE)) {
                    showMessageOKCancel("You need to allow access to dialer",
                    DialogInterface.OnClickListener { _, _ ->
                        requestPermissions(arrayOf(Manifest.permission.CALL_PHONE),
                                1)
                    })
                    return@setOnClickListener
                }
                requestPermissions(arrayOf(Manifest.permission.CALL_PHONE),
                        1)
                return@setOnClickListener
            }
        }
    }

    private fun showMessageOKCancel(message: String, okListener: DialogInterface.OnClickListener) {
        AlertDialog.Builder(this@MainActivity)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show()
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
        when (requestCode) {
            1 -> if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // Permission Granted
                Toast.makeText(this@MainActivity, "Permission Granted", Toast.LENGTH_SHORT)
                        .show()
                startActivity(callIntent)
                this.finish()
            } else {
                // Permission Denied
                Toast.makeText(this@MainActivity, "Permission Denied", Toast.LENGTH_SHORT)
                        .show()
            }
            else -> super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        }
    }

}

Body:
You need to add the permission to the manifest.xml too.

 <uses-permission android:name="android.permission.CALL_PHONE" />


问:
Fast lexicon lookup with phrases and stemming in python
I'm building a text classifier in python and I have a list of key phrases for each class. For example the classes can be "travel" and "science" and lists could contain:

travel: "New York", "South Korea", "Seoul", etc.

science: "scientist", "chemical", etc.

I'm looking for the best way to match phrases from such lists in python.

For instance, the result for the document:

A famous scientist traveled from New York to Seoul, South Korea

should be:
"science": 1
"travel": 3

Even if the "in" operator for strings is well optimized, there are a few situations which should be handled as well:

word boundaries: at some point I can have "to" in the dictionary, and wouldn't want to match "to" in "tomorrow". Tokenization would work in this case, but some custom logic would be required for phrases, maybe sub-list lookup in the list of tokens.

stemming: "scientists discovered" should also be matched when there is "scientist discover" in the list

Is there a python library which could handle this efficiently? If I need to implement it from scratch, what would be the best way to handle the above issues in terms of performance?

答:
In this case, a simple solution is to use dictionary comprehension:

```<code>s = "A famous scientist traveled from New York to Seoul, South Korea"
d = {"travel":["New York", "South Korea", "Seoul"], "science": ["scientist", "chemical"]}
final_results = {a:sum(i in s for i in b) for a, b in d.items()}
</code>```

Output:

```<code>{'science': 1, 'travel': 3}
</code>```

Body:
In this case, a simple solution is to use dictionary comprehension:

s = "A famous scientist traveled from New York to Seoul, South Korea"
d = {"travel":["New York", "South Korea", "Seoul"], "science": ["scientist", "chemical"]}
final_results = {a:sum(i in s for i in b) for a, b in d.items()}

Output:

{'science': 1, 'travel': 3}


问:
Mongodb: compute a value before using it as connectFromField in an aggregate
I have mongo tree structure that looks like this:

```<code>{"_id":uid1,"parent": null, "path": "#uid1", "name": "a"}
{"_id":uid2,"parent": "uid1", "path": "#uid1#uid2", "name": "b"}
{"_id":uid3,"parent": "uid1", "path": "#uid1#uid3", "name": "c"}
{"_id":uid4,"parent": "uid2", "path": "#uid1#uid2#uid4", "name": "1"}
{"_id":uid5,"parent": "uid2", "path": "#uid1#uid2#uid5", "name": "2"}
{"_id":uid6,"parent": "uid1", "path": "#uid1#uid6", "name": "1"}
{"_id":uid7,"parent": "uid6", "path": "#uid1#uid6#uid7", "name": "x"}
</code>```

where every node is represented by its unique id uidx and located thanks to its parent's uid. Everytime the parent of a node is modified its path and the paths of its children are automatically modified (inside a mongoose pre-save).

The example above can be represented as follows:

```<code>a
|_b
|    |_1
|    |_2
|_c
    |_1
          |_x
</code>```

My goal is to build a request that will get only the leaves under a specified node.

Had I stored the parent path inside the field parent instead of only the parent identifier I would have been able to do it using the following request:

```<code>db.tree.aggregate([
        {$match:{"parent": {$regex:"^#uid1#uid2"}}},
        {$graphLookup:{
                       from:"tree",
                       startWith:"$path",
                       connectFromField:"path",
                       connectToField:"parent",
                       as:"dep"}},
        {$match:{dep:[]}},
        {$project:{"_id":0, path:1}}
])
</code>```

as already answered in my previous question here: Mongodb: get only leaves of tree

The problem is I did not.

So I have to somehow transform the 'connectToField' in my request so that it represents the path of my parent instead of the id of my parent. Does anybody have an idea on how to do this?

This question is a rewritten version of my previous question here:previous version

答:
You don't need to calculate anything, nor rely on the path.
It is the exact usecase from https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/. The { $match: { dep: [] } } stage returns nodes with no children, i.e. leaves.

```<code>db.tree.aggregate([
    { $graphLookup: {
        from:"tree",
        startWith:"$_id",
        connectFromField:"_id",
        connectToField:"parent",
        as:"dep",
        maxDepth: 1
    } },
    { $match: { dep: [] } },
])
</code>```

maxDepth: 1 is added to speed things up a bit. As soon as the node have a direct child you don't care about rest of the branch, so 1 level depth for direct children is sufficient:

Body:
I have mongo tree structure that looks like this:

{"_id":uid1,"parent": null, "path": "#uid1", "name": "a"}
{"_id":uid2,"parent": "uid1", "path": "#uid1#uid2", "name": "b"}
{"_id":uid3,"parent": "uid1", "path": "#uid1#uid3", "name": "c"}
{"_id":uid4,"parent": "uid2", "path": "#uid1#uid2#uid4", "name": "1"}
{"_id":uid5,"parent": "uid2", "path": "#uid1#uid2#uid5", "name": "2"}
{"_id":uid6,"parent": "uid1", "path": "#uid1#uid6", "name": "1"}
{"_id":uid7,"parent": "uid6", "path": "#uid1#uid6#uid7", "name": "x"}

where every node is represented by its unique id uidx and located thanks to its parent's uid. Everytime the parent of a node is modified its path and the paths of its children are automatically modified (inside a mongoose pre-save).

The example above can be represented as follows:

a
|_b
|    |_1
|    |_2
|_c
    |_1
          |_x

My goal is to build a request that will get only the leaves under a specified node.

Had I stored the parent path inside the field parent instead of only the parent identifier I would have been able to do it using the following request:

db.tree.aggregate([
        {$match:{"parent": {$regex:"^#uid1#uid2"}}},
        {$graphLookup:{
                       from:"tree",
                       startWith:"$path",
                       connectFromField:"path",
                       connectToField:"parent",
                       as:"dep"}},
        {$match:{dep:[]}},
        {$project:{"_id":0, path:1}}
])

as already answered in my previous question here: Mongodb: get only leaves of tree

The problem is I did not.

So I have to somehow transform the 'connectToField' in my request so that it represents the path of my parent instead of the id of my parent. Does anybody have an idea on how to do this?

This question is a rewritten version of my previous question here:previous version

Body:
You don't need to calculate anything, nor rely on the path.
It is the exact usecase from https://docs.mongodb.com/manual/reference/operator/aggregation/graphLookup/. The { $match: { dep: [] } } stage returns nodes with no children, i.e. leaves.

db.tree.aggregate([
    { $graphLookup: {
        from:"tree",
        startWith:"$_id",
        connectFromField:"_id",
        connectToField:"parent",
        as:"dep",
        maxDepth: 1
    } },
    { $match: { dep: [] } },
])

maxDepth: 1 is added to speed things up a bit. As soon as the node have a direct child you don't care about rest of the branch, so 1 level depth for direct children is sufficient:


问:
Building and using a pure llvm toolchain for c++ on linux
Assuming this is possible, could someone tell me, how I have to configure the cmake build to create a "pure" llvm toolchain on ubuntu-16.04 consisting of

clang

lld

libc++

libc++abi

libunwind (llvm)

compiler-rt

any other pieces that might be relevant and are "production ready"

The resulting compiler should

be as fast as possible (optimizations turned on, no unnecessary asserts or other checks in the compiler binary itself)

be installed in a separate, local directory (lets call it <llvm_install>)

not have dependencies to the llvm tolchain provided by packet manager

use libc++, libc++abi etc by default.

support the sanitizers (ubsan, address, memory, thread) (which probably means that I have to compile libc++ a second time)

So far I have cloned

llvm from http://llvm.org/git/llvm.git into <llvm_root>

clang from http://llvm.org/git/clang.git into <llvm_root>/tools/clang

lld from http://llvm.org/git/lld.git into <llvm_root>/tools/lld

compiler-rt, libcxx, libcxxabi, libunwind from http://llvm.org/git/<project_name> into <llvm_root>/projects/<project_name>

Then run ccmake in a separate directory - I have tried various settings, but as soon as I try anything more fancy beyond turning optimizations on, I almost always get some sort of build error. Unfortunately, I have yet to find a way to export my changes from ccmake otherwise I'd give you an example with the settings and according error, but I'm more interested in a best practice than a fix to my test configs anyway.

Bonus points: By default, this should build with the default g++ toolchain, but I'd also be interested in a two stage build if that improves the performance of the final toolchain (e.g. by using LTO).

Btw.: The whole Idea came from watching chandler's talk

Pacific++ 2017: Chandler Carruth "LLVM: A Modern, Open C++ Toolchain"

答:
My usual procedure is to build a small enough LLVM/Clang so that I have something working with libc++ and libc++abi. I guess you can use the system-provided LLVM, but I haven't tried it. For this step, what you have checked-out is probably enough. A sample script for this:

```<code>cmake
-G Ninja \
-DCMAKE_EXPORT_COMPILE_COMMANDS=On \
-DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DBUILD_SHARED_LIBS=On \
-DLLVM_ENABLE_ASSERTIONS=Off \
-DLLVM_TARGETS_TO_BUILD="X86" \
-DLLVM_ENABLE_SPHINX=Off \
-DLLVM_ENABLE_THREADS=On \
-DLIBCXX_ENABLE_EXCEPTIONS=On \
-DLIBCXX_ENABLE_RTTI=On \
-DCMAKE_INSTALL_PREFIX=[path-to-install-dir] \
[path-to-source-dir]
</code>```

Having the aforementioned clang in your PATH environment variable,
you can use the below build script again and adjust based on your needs (sanitizers, etc). Apart from the main documentation page on the subject, poking around the CMakeLists.txt of each respective tool is also illuminating and helps adjust the build process from version to version.

```<code>LLVM_TOOLCHAIN_LIB_DIR=$(llvm-config --libdir)
LD_FLAGS=""
LD_FLAGS="${LD_FLAGS} -Wl,-L ${LLVM_TOOLCHAIN_LIB_DIR}"
LD_FLAGS="${LD_FLAGS} -Wl,-rpath-link ${LLVM_TOOLCHAIN_LIB_DIR}"
LD_FLAGS="${LD_FLAGS} -lc++ -lc++abi"

CXX_FLAGS=""
CXX_FLAGS="${CXX_FLAGS} -stdlib=libc++ -pthread"

CC=clang CXX=clang++ \
cmake -G Ninja \
-DCMAKE_EXPORT_COMPILE_COMMANDS=On \
-DBUILD_SHARED_LIBS=On \
-DLLVM_ENABLE_LIBCXX=On \
-DLLVM_ENABLE_LIBCXXABI=On \
-DLLVM_ENABLE_ASSERTIONS=On \
-DLLVM_TARGETS_TO_BUILD="X86" \
-DLLVM_ENABLE_SPHINX=Off \
-DLLVM_ENABLE_THREADS=On \
-DLLVM_INSTALL_UTILS=On \
-DLIBCXX_ENABLE_EXCEPTIONS=On \
-DLIBCXX_ENABLE_RTTI=On \
-DCMAKE_BUILD_TYPE=Debug \
-DCMAKE_CXX_FLAGS="${CXX_FLAGS}" \
-DCMAKE_SHARED_LINKER_FLAGS="${LD_FLAGS}" \
-DCMAKE_MODULE_LINKER_FLAGS="${LD_FLAGS}" \
-DCMAKE_EXE_LINKER_FLAGS="${LD_FLAGS}" \
-DCMAKE_POLICY_DEFAULT_CMP0056=NEW \
-DCMAKE_POLICY_DEFAULT_CMP0058=NEW \
-DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} \
[path-to-source-dir]
</code>```

A note on performance: I haven't watched that talk yet, but my motivation behind this 2 step build was to have a toolchain that I can easily relocate between systems since the minimal system dependence that matters is libc.

Lastly, relevant to the above procedure is this older question of mine, which still bugs me. If you have any insight on this, please don't hesitate.

PS: Scripts have been tested with LLVM 3.7 through 3.9 and current trunk 6.0.0.

Update: I've also applied these suggestions, and there is marked improvement when using the gold linker instead of ld. LTO is also a boost.

Body:
My usual procedure is to build a small enough LLVM/Clang so that I have something working with libc++ and libc++abi. I guess you can use the system-provided LLVM, but I haven't tried it. For this step, what you have checked-out is probably enough. A sample script for this:

cmake
-G Ninja \
-DCMAKE_EXPORT_COMPILE_COMMANDS=On \
-DCMAKE_BUILD_TYPE=RelWithDebInfo \
-DBUILD_SHARED_LIBS=On \
-DLLVM_ENABLE_ASSERTIONS=Off \
-DLLVM_TARGETS_TO_BUILD="X86" \
-DLLVM_ENABLE_SPHINX=Off \
-DLLVM_ENABLE_THREADS=On \
-DLIBCXX_ENABLE_EXCEPTIONS=On \
-DLIBCXX_ENABLE_RTTI=On \
-DCMAKE_INSTALL_PREFIX=[path-to-install-dir] \
[path-to-source-dir]

Having the aforementioned clang in your PATH environment variable,
you can use the below build script again and adjust based on your needs (sanitizers, etc). Apart from the main documentation page on the subject, poking around the CMakeLists.txt of each respective tool is also illuminating and helps adjust the build process from version to version.

LLVM_TOOLCHAIN_LIB_DIR=$(llvm-config --libdir)
LD_FLAGS=""
LD_FLAGS="${LD_FLAGS} -Wl,-L ${LLVM_TOOLCHAIN_LIB_DIR}"
LD_FLAGS="${LD_FLAGS} -Wl,-rpath-link ${LLVM_TOOLCHAIN_LIB_DIR}"
LD_FLAGS="${LD_FLAGS} -lc++ -lc++abi"

CXX_FLAGS=""
CXX_FLAGS="${CXX_FLAGS} -stdlib=libc++ -pthread"

CC=clang CXX=clang++ \
cmake -G Ninja \
-DCMAKE_EXPORT_COMPILE_COMMANDS=On \
-DBUILD_SHARED_LIBS=On \
-DLLVM_ENABLE_LIBCXX=On \
-DLLVM_ENABLE_LIBCXXABI=On \
-DLLVM_ENABLE_ASSERTIONS=On \
-DLLVM_TARGETS_TO_BUILD="X86" \
-DLLVM_ENABLE_SPHINX=Off \
-DLLVM_ENABLE_THREADS=On \
-DLLVM_INSTALL_UTILS=On \
-DLIBCXX_ENABLE_EXCEPTIONS=On \
-DLIBCXX_ENABLE_RTTI=On \
-DCMAKE_BUILD_TYPE=Debug \
-DCMAKE_CXX_FLAGS="${CXX_FLAGS}" \
-DCMAKE_SHARED_LINKER_FLAGS="${LD_FLAGS}" \
-DCMAKE_MODULE_LINKER_FLAGS="${LD_FLAGS}" \
-DCMAKE_EXE_LINKER_FLAGS="${LD_FLAGS}" \
-DCMAKE_POLICY_DEFAULT_CMP0056=NEW \
-DCMAKE_POLICY_DEFAULT_CMP0058=NEW \
-DCMAKE_INSTALL_PREFIX=${INSTALL_DIR} \
[path-to-source-dir]

A note on performance: I haven't watched that talk yet, but my motivation behind this 2 step build was to have a toolchain that I can easily relocate between systems since the minimal system dependence that matters is libc.

Lastly, relevant to the above procedure is this older question of mine, which still bugs me. If you have any insight on this, please don't hesitate.

PS: Scripts have been tested with LLVM 3.7 through 3.9 and current trunk 6.0.0.

Update: I've also applied these suggestions, and there is marked improvement when using the gold linker instead of ld. LTO is also a boost.


问:
How can I make .goto non-blocking?
I'm writing a rails app which fetches text from an HTML page using Watir and Chrome Headless. All good so far!

The problem starts when I request a page which has a long load time to completely load all elements despite the fact that I don't need them.

Current code I use:

```<code>browser = Watir::Browser.new :chrome, headless: true

browser.goto(url)
</code>```

The .goto function call, however, blocks until ALL elements have loaded. That's not really what I need - what I need is for goto to just start fetching the page, then continue running code since I really just want to wait until the text I need is present, then fetch it.

Any ideas?

答:
Goto will not leave the control until 60 seconds, If page load time exceeds 60 seconds, then it would throw the error. And also Watir.default_timeout has nothing to do with Goto's page loading. You need to set the timings for page_load which you can do by directly calling selenium driver as I have done below because Watir hasn't offered any systax for that

Write the below code, you could achieve what you want

```<code> begin
  b.driver.manage.timeouts.page_load=5
  b=Watir::Browser.new
  b.goto(url)
rescue            #I have written the rescue block here because goto will the error for you If page is not loaded within a given time
end
</code>```

AND THEN you can write your rest of the code here, for an example,

```<code>puts b.span(text: 'something').text
</code>```

What happens here is, goto will be block the execution of the code followed by goto for 5 seconds, and then it would fall into the rescue block, so program would continue to execute next line as you expected.

Title: How can I make .goto non-blocking?

Body:
I'm writing a rails app which fetches text from an HTML page using Watir and Chrome Headless. All good so far!

The problem starts when I request a page which has a long load time to completely load all elements despite the fact that I don't need them.

Current code I use:

browser = Watir::Browser.new :chrome, headless: true

browser.goto(url)

The .goto function call, however, blocks until ALL elements have loaded. That's not really what I need - what I need is for goto to just start fetching the page, then continue running code since I really just want to wait until the text I need is present, then fetch it.

Any ideas?

Body:
Goto will not leave the control until 60 seconds, If page load time exceeds 60 seconds, then it would throw the error. And also Watir.default_timeout has nothing to do with Goto's page loading. You need to set the timings for page_load which you can do by directly calling selenium driver as I have done below because Watir hasn't offered any systax for that

Write the below code, you could achieve what you want

 begin
  b.driver.manage.timeouts.page_load=5
  b=Watir::Browser.new
  b.goto(url)
rescue            #I have written the rescue block here because goto will the error for you If page is not loaded within a given time
end

AND THEN you can write your rest of the code here, for an example,

puts b.span(text: 'something').text

What happens here is, goto will be block the execution of the code followed by goto for 5 seconds, and then it would fall into the rescue block, so program would continue to execute next line as you expected.