问:
Forcing flexbox element to float right
I'm currently working on responsiveness on my website and I hit the wall. On smaller resolutions I changed the flex-direction to column from row, changed the ordering of flex elements, changed the main textbox width to 100% and sideboxes to 50%.

Code looks like this:

```<code><section class="about" id="ABOUT">
    <div class="about-sidebox l">
    </div>

    <div class="about-mainbox">
    </div>

    <div class="about-sidebox r">
    </div>
</section>
</code>```

As you can see the sideboxes are not within the container. Putting them in container helps but completely ruins my previous layout.

CSS for wanted resolution is:

```<code>.about {
    flex-direction: column;
}

.about-mainbox {
    order: 1;
}

.about-sidebox {
    order: 2;
    width: 50%;
    flex-wrap: wrap;
}
</code>```

Effect is like this:

As you can see I want the sideboxes to be next to each other. Any solution I can't think of without adding additional container?

答:
I hope I've understood you correctly. You could remove the flex-direction property from .about

Add flex-wrap. Then just give .about-mainbox a width of 100%

.about {
  display: flex;
  flex-wrap: wrap;
}

.about-mainbox {
  order: 1;
  width: 100%;
}

.about-sidebox {
  order: 2;
  width: 50%;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><section class="about" id="ABOUT">
  <div class="about-sidebox l">demo left
  </div>
  <div class="about-mainbox">demo
  </div>
  <div class="about-sidebox r">demo right
  </div>
</section></code>```

Title: Forcing flexbox element to float right

Body:
I'm currently working on responsiveness on my website and I hit the wall. On smaller resolutions I changed the flex-direction to column from row, changed the ordering of flex elements, changed the main textbox width to 100% and sideboxes to 50%.

Code looks like this:

As you can see the sideboxes are not within the container. Putting them in container helps but completely ruins my previous layout.

CSS for wanted resolution is:

.about {
    flex-direction: column;
}

.about-mainbox {
    order: 1;
}

.about-sidebox {
    order: 2;
    width: 50%;
    flex-wrap: wrap;
}

Effect is like this:

As you can see I want the sideboxes to be next to each other. Any solution I can't think of without adding additional container?

Body:
I hope I've understood you correctly. You could remove the flex-direction property from .about

Add flex-wrap. Then just give .about-mainbox a width of 100%

.about {
  display: flex;
  flex-wrap: wrap;
}

.about-mainbox {
  order: 1;
  width: 100%;
}

.about-sidebox {
  order: 2;
  width: 50%;
}

<section class="about" id="ABOUT">
  <div class="about-sidebox l">demo left
  </div>
  <div class="about-mainbox">demo
  </div>
  <div class="about-sidebox r">demo right
  </div>
</section>


来源: stackexchange

问:
Django : Migration of polymorphic models back to a single base class
Let's suppose I have a polymorphic model and I want to get rid of it.

```<code>class AnswerBase(models.Model):

    question = models.ForeignKey(Question, related_name="answers")
    response = models.ForeignKey(Response, related_name="answers")

class AnswerText(AnswerBase):
    body = models.TextField(blank=True, null=True)

class AnswerInteger(AnswerBase):
    body = models.IntegerField(blank=True, null=True)
</code>```

When I want to get all the answers I can never access "body" or I need to try to get the instance of a sub-class by trial and error.

```<code># Query set of answerBase, no access to body
AnswerBase.objects.all()
question = Question.objects.get(pk=1)
# Query set of answerBase, no access to body (even with django-polymorphic)
question.answers.all()
</code>```

I don't want to use django-polymorphic because of performances, because it does not seem to work for foreignKey relation, and because I don't want my model to be too complicated. So I want this polymorphic architecture to become this simplified one :

```<code>class Answer(models.Model):

    question = models.ForeignKey(Question, related_name="answers")
    response = models.ForeignKey(Response, related_name="answers")
    body = models.TextField(blank=True, null=True)
</code>```

The migrations cannot be created automatically, it would delete all older answers in the database. I've read the Schema Editor documentation but it does not seem there is a buildin to migrate a model to something that already exists. So I want to create my own operation to save the AnswerText and AnswerInteger as an Answer then delete AnswerText and AnswerInteger. I'm hoping I won't have to write SQL directly, but maybe that's the only solution ? My migration file looks like this. I created an Operation called MigrateAnswer :

```<code>from myapp.migrations import MigrateAnswer

class Migration(migrations.Migration):

    operations = [
        migrations.RenameModel("AnswerBase", "Answer"),
        migrations.AddField(
            model_name='answer',
            name='body',
            field=models.TextField(blank=True, null=True),
        ),
        MigrateAnswer("AnswerInteger"),
        MigrateAnswer("AnswerText"),
        migrations.DeleteModel(name='AnswerInteger',),
        migrations.DeleteModel(name='AnswerText',),
    ]
</code>```

So what I want to do in MigrateAnswer is to migrate the value for an old model (AnswerInteger and AnswerText) to the base class (now named Answer, previousely AnswerBase). Here's my operation class :

```<code>from django.db.migrations.operations.base import Operation

class MigrateAnswer(Operation):

    reversible = False

    def __init__(self, model_name):
        self.old_name = model_name

    def database_forwards(self, app_label, schema_editor, from_state,
                          to_state):
        new_model = to_state.apps.get_model(app_label, "Answer")
        old_model = from_state.apps.get_model(app_label, self.old_name)
        for field in old_model._meta.local_fields:
            # loop on "question", "reponse" and "body"
            # schema_editor.alter_field() Alter a field on a single model
            # schema_editor.add_field() + remove_field() Does not permit
            # to migrate the value from the old field to the new one
            pass
</code>```

So my question is : Is it possible to do this wihout using "execute" (ie : without writing SQL). If so what should I do in the for loop of my Operation ?

Thanks in advance !

答:
There is no need to write an Operations class; data migrations can be done simply with a RunPython call, as the docs show.

Within that function you can use perfectly normal model instance methods; since you know the fields you want to move the data for, there is no need to get them via meta lookups.

However you will need to temporarily call the new body field a different name, so it doesn't conflict with the old fields on the subclasses; you can rename it back at the end and delete the child classes because the value will be in the base class.

```<code>def migrate_answers(apps, schema_editor):
    classes = []
    classes_str = ['AnswerText', 'AnswerInteger']
    for class_name in classes_str:
        classes.append(apps.get_model('survey', class_name))
    for class_ in classes:
        for answer in class_.objects.all():
            answer.new_body = answer.body
            answer.save()

operations = [
    migrations.AddField(
        model_name='answerbase',
        name='new_body',
        field=models.TextField(blank=True, null=True),
    ),
    migrations.RunPython(migrate_answers),
    migrations.DeleteModel(name='AnswerInteger',),
    migrations.DeleteModel(name='AnswerText',),
    migrations.RenameField('AnswerBase', 'new_body', 'body'),
    migrations.RenameModel("AnswerBase", "Answer"),
]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Let's suppose I have a polymorphic model and I want to get rid of it.

class AnswerBase(models.Model):

    question = models.ForeignKey(Question, related_name="answers")
    response = models.ForeignKey(Response, related_name="answers")

class AnswerText(AnswerBase):
    body = models.TextField(blank=True, null=True)

class AnswerInteger(AnswerBase):
    body = models.IntegerField(blank=True, null=True)

When I want to get all the answers I can never access "body" or I need to try to get the instance of a sub-class by trial and error.

# Query set of answerBase, no access to body
AnswerBase.objects.all()
question = Question.objects.get(pk=1)
# Query set of answerBase, no access to body (even with django-polymorphic)
question.answers.all()

I don't want to use django-polymorphic because of performances, because it does not seem to work for foreignKey relation, and because I don't want my model to be too complicated. So I want this polymorphic architecture to become this simplified one :

class Answer(models.Model):

    question = models.ForeignKey(Question, related_name="answers")
    response = models.ForeignKey(Response, related_name="answers")
    body = models.TextField(blank=True, null=True)

The migrations cannot be created automatically, it would delete all older answers in the database. I've read the Schema Editor documentation but it does not seem there is a buildin to migrate a model to something that already exists. So I want to create my own operation to save the AnswerText and AnswerInteger as an Answer then delete AnswerText and AnswerInteger. I'm hoping I won't have to write SQL directly, but maybe that's the only solution ? My migration file looks like this. I created an Operation called MigrateAnswer :

from myapp.migrations import MigrateAnswer

class Migration(migrations.Migration):

    operations = [
        migrations.RenameModel("AnswerBase", "Answer"),
        migrations.AddField(
            model_name='answer',
            name='body',
            field=models.TextField(blank=True, null=True),
        ),
        MigrateAnswer("AnswerInteger"),
        MigrateAnswer("AnswerText"),
        migrations.DeleteModel(name='AnswerInteger',),
        migrations.DeleteModel(name='AnswerText',),
    ]

So what I want to do in MigrateAnswer is to migrate the value for an old model (AnswerInteger and AnswerText) to the base class (now named Answer, previousely AnswerBase). Here's my operation class :

from django.db.migrations.operations.base import Operation

class MigrateAnswer(Operation):

    reversible = False

    def __init__(self, model_name):
        self.old_name = model_name

    def database_forwards(self, app_label, schema_editor, from_state,
                          to_state):
        new_model = to_state.apps.get_model(app_label, "Answer")
        old_model = from_state.apps.get_model(app_label, self.old_name)
        for field in old_model._meta.local_fields:
            # loop on "question", "reponse" and "body"
            # schema_editor.alter_field() Alter a field on a single model
            # schema_editor.add_field() + remove_field() Does not permit
            # to migrate the value from the old field to the new one
            pass

So my question is : Is it possible to do this wihout using "execute" (ie : without writing SQL). If so what should I do in the for loop of my Operation ?

Thanks in advance !

Body:
There is no need to write an Operations class; data migrations can be done simply with a RunPython call, as the docs show.

Within that function you can use perfectly normal model instance methods; since you know the fields you want to move the data for, there is no need to get them via meta lookups.

However you will need to temporarily call the new body field a different name, so it doesn't conflict with the old fields on the subclasses; you can rename it back at the end and delete the child classes because the value will be in the base class.

def migrate_answers(apps, schema_editor):
    classes = []
    classes_str = ['AnswerText', 'AnswerInteger']
    for class_name in classes_str:
        classes.append(apps.get_model('survey', class_name))
    for class_ in classes:
        for answer in class_.objects.all():
            answer.new_body = answer.body
            answer.save()

operations = [
    migrations.AddField(
        model_name='answerbase',
        name='new_body',
        field=models.TextField(blank=True, null=True),
    ),
    migrations.RunPython(migrate_answers),
    migrations.DeleteModel(name='AnswerInteger',),
    migrations.DeleteModel(name='AnswerText',),
    migrations.RenameField('AnswerBase', 'new_body', 'body'),
    migrations.RenameModel("AnswerBase", "Answer"),
]


问:
PopupMenu avoid dismiss on click of Keyboard
I'm facing an issue without being able to find an answer. I have an editText with a TextWatcher to find a list of results in a database. I display the result in a PopupMenu. It looks like this :

```<code>final List<SearchResult> searchResults = new ArrayList<>();

    final PopupMenu menu = new PopupMenu(getActivity(), binding.bottomSheetWriteNews.editTextNewsSubCategory);
    menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            binding
                    .bottomSheetWriteNews
                    .editTextNewsSubCategory
                    .setText(item.getTitle());

            return false;
        }
    });

    final Realm realm = Realm.getDefaultInstance();

    binding.bottomSheetWriteNews.editTextNewsSubCategory.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            searchResults.clear();
            menu.getMenu().clear();

            RealmResults<SubCategory> subCategoriesResult = realm.where(SubCategory.class).contains("name", s.toString(), Case.INSENSITIVE).findAll();
            for(SubCategory subCategory : subCategoriesResult) {
                searchResults.add(new SearchResult(subCategory.getId(), subCategory.getName(), false));
                menu.getMenu().add(subCategory.getName());
            }
            menu.show();
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });
</code>```

My issue is every-time I click on the Keyboard the PopupMenu is dismiss instead of typing the character I wanted. That's annoying and unusable for users. I want the click on keyboard to not dismiss the PopupMenu. I know that in the official documentation it's written Touching outside of the popup will dismiss it, but I'm using Google Keep, and they have the same feature (typing text display a PopupMenu to filter results) without my issue.

Thanks for your help !

答:
Responding to my own answer after I found an alternative solution with a coworker. There is a specific EditText named autoCompleteTextView which can take an ArrayAdapter. And it will do the search for you. Here is how I implemented it :

```<code>final Realm realm = Realm.getDefaultInstance();
    RealmResults<SubCategory> subCategoriesResult = realm.where(SubCategory.class).findAll();
    List<String> categoryName = new ArrayList<>();
    for(SubCategory subCategory : subCategoriesResult) {
        categoryName.add(subCategory.getName());
    }
    String[] stringArray = categoryName.toArray(new String[0]);

    ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
            android.R.layout.simple_dropdown_item_1line, stringArray);
    binding.bottomSheetWriteNews.autoCompleteTextViewNewsSubCategory.setAdapter(adapter);
</code>```

And nothing more ! After typing two characters the list of result will show as a PopupMenu.

In any case, if someone has a solution to avoid dismiss after clicking on keyboard when a PopupMenu is showed, I'm interested. Thanks !

Body:
I'm facing an issue without being able to find an answer. I have an editText with a TextWatcher to find a list of results in a database. I display the result in a PopupMenu. It looks like this :

final List<SearchResult> searchResults = new ArrayList<>();

    final PopupMenu menu = new PopupMenu(getActivity(), binding.bottomSheetWriteNews.editTextNewsSubCategory);
    menu.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
        @Override
        public boolean onMenuItemClick(MenuItem item) {
            binding
                    .bottomSheetWriteNews
                    .editTextNewsSubCategory
                    .setText(item.getTitle());

            return false;
        }
    });

    final Realm realm = Realm.getDefaultInstance();

    binding.bottomSheetWriteNews.editTextNewsSubCategory.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

            searchResults.clear();
            menu.getMenu().clear();

            RealmResults<SubCategory> subCategoriesResult = realm.where(SubCategory.class).contains("name", s.toString(), Case.INSENSITIVE).findAll();
            for(SubCategory subCategory : subCategoriesResult) {
                searchResults.add(new SearchResult(subCategory.getId(), subCategory.getName(), false));
                menu.getMenu().add(subCategory.getName());
            }
            menu.show();
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count,
                                      int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });

My issue is every-time I click on the Keyboard the PopupMenu is dismiss instead of typing the character I wanted. That's annoying and unusable for users. I want the click on keyboard to not dismiss the PopupMenu. I know that in the official documentation it's written Touching outside of the popup will dismiss it, but I'm using Google Keep, and they have the same feature (typing text display a PopupMenu to filter results) without my issue.

Thanks for your help !

Body:
Responding to my own answer after I found an alternative solution with a coworker. There is a specific EditText named autoCompleteTextView which can take an ArrayAdapter. And it will do the search for you. Here is how I implemented it :

final Realm realm = Realm.getDefaultInstance();
    RealmResults<SubCategory> subCategoriesResult = realm.where(SubCategory.class).findAll();
    List<String> categoryName = new ArrayList<>();
    for(SubCategory subCategory : subCategoriesResult) {
        categoryName.add(subCategory.getName());
    }
    String[] stringArray = categoryName.toArray(new String[0]);

    ArrayAdapter<String> adapter = new ArrayAdapter<>(getActivity(),
            android.R.layout.simple_dropdown_item_1line, stringArray);
    binding.bottomSheetWriteNews.autoCompleteTextViewNewsSubCategory.setAdapter(adapter);

And nothing more ! After typing two characters the list of result will show as a PopupMenu.

In any case, if someone has a solution to avoid dismiss after clicking on keyboard when a PopupMenu is showed, I'm interested. Thanks !


问:
Azure SQL POOL Elasticity
Just wanted to be sure if this is possible:

I am having all my app services in separate subscription, I want to use Sql pool elasticity for which I will create a separate subscription in which only my DBs will reside and will add all my DBs to this pool which I will create on this subscription.

Problems:

    1.Is it possible for my apps in different subscription to access the DB in another subscription?

    2. If the above scenario is possible then will it hamper performance of my apps?

    3. Will I be charged Data Transfer Cost for this? What if the region of the app and Db is same?

Thanks in advance.

答:
1.Is it possible for my apps in different subscription to access the DB in another subscription?

Yes.  The Firewall and Authentication are not related to the subscription at all.

If the above scenario is possible then will it hamper performance of my apps?

No.

Will I be charged Data Transfer Cost for this? What if the region of the app and Db is same?

There is no data egress charge between resources in the same region.

Title: Azure SQL POOL Elasticity


问:
Load and dump to file in multithreading using Pickle and filelock - IOError: [Errno 13]
I have a service that load and dump data from a python dict into a file using python 2.7 cPickle. This service can be called simultaneously by many users.

What approach would allow cPickle to read and dump data into a single file in a multithreading context in order to avoid problems of desynchronization (loading while another process is dumping) of the data during operations?

I was thinking of using filelock but I havent been successful yet.

With my code below, the file is always have cPickle.load(cache_file)IOError: [Errno 13] Permission denied" error in init_cache() or update_cache()

```<code>''' example of a dict dumped by pickle

  {
     "version": "1499180895",
     "queries": {
         "001::id,name,age" : "aBase64EncodedString==",
         "002::id,name,sex" : "anotherBase64EncodedString=="
      }
   }

'''

import cPickle as pickle
import filelock
from os import path

self.cache_file_path = "\\\\serverDisk\\cache\\cache.pkl"
self.select_by_values = "001"
self.out_fields = ["id", "name", "age"]

def get_from_cache_fn(self):
    try:
        server_version = self.query_version()
        query_id = "{}::{}".format(self.select_by_values, ",".join(self.out_fields))
        if path.isfile(self.cache_file_path):
            cache_dict = self.load_cache(server_version, query_id)
            if cache_dict["version"] == server_version:
                if query_id in cache_dict["queries"]:
                     return cache_dict["queries"][query_id]
                else:
                    return self.update_cache(cache_dict, query_id)["queries"][query_id]
            else:
                return self.init_cache(server_version, query_id)["queries"][query_id]
        else:
            return self.init_cache(server_version, query_id)["queries"][query_id]
    except Exception:
        self.add_service_error(ERRORS["get_from_cache"][0], traceback.format_exc())

def load_cache(self, server_version, query_id):
    with open(self.cache_file_path, "rb") as cache_file:
        try:
            cache_dict = pickle.load(cache_file)
            return cache_dict
        except StandardError:
            return self.init_cache(server_version, query_id)

def init_cache(self, server_version, query_id):
    cache_dict = {
        "version" : server_version,
        "queries" : {
            query_id : base64.b64encode(zlib.compress(json.dumps(self.query_features())))
        }
    }
    lock = filelock.FileLock(self.cache_file_path)
    try:
        with lock.acquire(timeout=10):
            with open(self.cache_file_path, "wb") as cache_file:
                pickle.dump(cache_dict, cache_file)
                return cache_dict
    except lock.Timeout:
        self.add_service_error("init_cache timeout", traceback.format_exc())

def update_cache(self, cache_dict, query_id):
    cache_dict["queries"][query_id] = base64.b64encode(zlib.compress(json.dumps(self.query_features())))
    lock = filelock.FileLock(self.cache_file_path)
    try:
        with lock.acquire(timeout = 10):
            with open(self.cache_file_path, "wb") as cache_file:
                pickle.dump(cache_dict, cache_file)
                return cache_dict
    except lock.Timeout:
        self.add_service_error("update_cache timeout", traceback.format_exc())
</code>```

答: According to Filelock documentation you should wrap the lock.acquire inside the try{}except{}. Otherwise it might just crash your app with unhandled exception when your acquire times out. See https://pypi.python.org/pypi/filelock

Body:
I have a service that load and dump data from a python dict into a file using python 2.7 cPickle. This service can be called simultaneously by many users.

What approach would allow cPickle to read and dump data into a single file in a multithreading context in order to avoid problems of desynchronization (loading while another process is dumping) of the data during operations?

I was thinking of using filelock but I havent been successful yet.

With my code below, the file is always have cPickle.load(cache_file)IOError: [Errno 13] Permission denied" error in init_cache() or update_cache()

''' example of a dict dumped by pickle

  {
     "version": "1499180895",
     "queries": {
         "001::id,name,age" : "aBase64EncodedString==",
         "002::id,name,sex" : "anotherBase64EncodedString=="
      }
   }

'''

import cPickle as pickle
import filelock
from os import path

self.cache_file_path = "\\\\serverDisk\\cache\\cache.pkl"
self.select_by_values = "001"
self.out_fields = ["id", "name", "age"]

def get_from_cache_fn(self):
    try:
        server_version = self.query_version()
        query_id = "{}::{}".format(self.select_by_values, ",".join(self.out_fields))
        if path.isfile(self.cache_file_path):
            cache_dict = self.load_cache(server_version, query_id)
            if cache_dict["version"] == server_version:
                if query_id in cache_dict["queries"]:
                     return cache_dict["queries"][query_id]
                else:
                    return self.update_cache(cache_dict, query_id)["queries"][query_id]
            else:
                return self.init_cache(server_version, query_id)["queries"][query_id]
        else:
            return self.init_cache(server_version, query_id)["queries"][query_id]
    except Exception:
        self.add_service_error(ERRORS["get_from_cache"][0], traceback.format_exc())

def load_cache(self, server_version, query_id):
    with open(self.cache_file_path, "rb") as cache_file:
        try:
            cache_dict = pickle.load(cache_file)
            return cache_dict
        except StandardError:
            return self.init_cache(server_version, query_id)

def init_cache(self, server_version, query_id):
    cache_dict = {
        "version" : server_version,
        "queries" : {
            query_id : base64.b64encode(zlib.compress(json.dumps(self.query_features())))
        }
    }
    lock = filelock.FileLock(self.cache_file_path)
    try:
        with lock.acquire(timeout=10):
            with open(self.cache_file_path, "wb") as cache_file:
                pickle.dump(cache_dict, cache_file)
                return cache_dict
    except lock.Timeout:
        self.add_service_error("init_cache timeout", traceback.format_exc())

def update_cache(self, cache_dict, query_id):
    cache_dict["queries"][query_id] = base64.b64encode(zlib.compress(json.dumps(self.query_features())))
    lock = filelock.FileLock(self.cache_file_path)
    try:
        with lock.acquire(timeout = 10):
            with open(self.cache_file_path, "wb") as cache_file:
                pickle.dump(cache_dict, cache_file)
                return cache_dict
    except lock.Timeout:
        self.add_service_error("update_cache timeout", traceback.format_exc())


问:
How to upload particular image on particular imageView click from gallery and camera in android
i have 4 diffrent imageview and try to click on all to upload diffrent images like LIcence,Rc,Profile  etc . I want to uploaded image from gallery or camera dialog..
 like this layout.
like uper layout example</p>

答:
EDIT
Since you are using recyclerview or listview kind of view, you can associate tag to each viewholder and then use that tag for resolving imageview. Now you can get unique tag based on position in view. For eg in recyclerview you can use getAdapterPosition().

Associate OnClicks of each imageview with a request code. In onActivityResult resolve them and put images accordingly.


问:
BST Supernodes Generation in C/C++
How can I generate a binary search tree with supernodes in C/C++?</p>

答:
Obtain a reference describing the data structure. http://www.cise.ufl.edu/~sahni/papers/super.pdf

Implement the data structure in C/C++.

ContentLicense: CC BY-SA 2.5

Title: BST Supernodes Generation in C/C++


问:
How to get value from function with typescript (ionic2)
I´m trying to get a value from a function. This is what I´m trying to do:

In file favorite.ts

getUserFavsCount(userId: string){
    let count = 0;
    let favs = this.af.list(`/favorites/${userId}`).subscribe(data =>{
      count = data.length;
    });
    console.log(count) // getting the value. here it shows correct
    return count;

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

<p>Now, in my profile.ts I´m trying to get this value:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>countUserFav() {
    this.userProvider.currentUser.first().subscribe((currentUser: User) => {
      console.log("---->",this.favoriteProvider.getUserFavsCount(currentUser.$key)); // here I get 0 value always :(
      this.myFavs = this.favoriteProvider.getUserFavsCount(currentUser.$key)

    });
  }</code>```

What Am I doing wrong?

答:
As TheFallen has commented you'll need to return a promise. Always use promises or you'll have concurrence problems. Try this

```<code>getUserFavsCount = (userId: string): Promise<number> => {
  // SINCE YOU RETURN A LENGTH, THEN THE PROMISE SHOULD RETURN A NUMBER
  // THERE'S NO NEED TO DECLARE A COUNT VARIABLE SINCE YOU'LL NOT USE IT
  return new Promise<number>(resolve =>{
    let favs = this.af.list(`/favorites/${userId}`).subscribe(data =>{
      resolve(data.length);
    });
  });
}
</code>```

And then get your data

```<code>countUserFav() {
  this.userProvider.currentUser.first().subscribe((currentUser: User) => {
    this.favoriteProvider.getUserFavsCount(currentUser.$key).then(res =>{
      this.myFavs = res;
    });
  });
}
</code>```

Hope this helps :D

Body:
I´m trying to get a value from a function. This is what I´m trying to do:

In file favorite.ts

getUserFavsCount(userId: string){
    let count = 0;
    let favs = this.af.list(`/favorites/${userId}`).subscribe(data =>{
      count = data.length;
    });
    console.log(count) // getting the value. here it shows correct
    return count;

  }

Now, in my profile.ts I´m trying to get this value:

countUserFav() {
    this.userProvider.currentUser.first().subscribe((currentUser: User) => {
      console.log("---->",this.favoriteProvider.getUserFavsCount(currentUser.$key)); // here I get 0 value always :(
      this.myFavs = this.favoriteProvider.getUserFavsCount(currentUser.$key)

    });
  }

What Am I doing wrong?

Body:
As TheFallen has commented you'll need to return a promise. Always use promises or you'll have concurrence problems. Try this

getUserFavsCount = (userId: string): Promise<number> => {
  // SINCE YOU RETURN A LENGTH, THEN THE PROMISE SHOULD RETURN A NUMBER
  // THERE'S NO NEED TO DECLARE A COUNT VARIABLE SINCE YOU'LL NOT USE IT
  return new Promise<number>(resolve =>{
    let favs = this.af.list(`/favorites/${userId}`).subscribe(data =>{
      resolve(data.length);
    });
  });
}

And then get your data

countUserFav() {
  this.userProvider.currentUser.first().subscribe((currentUser: User) => {
    this.favoriteProvider.getUserFavsCount(currentUser.$key).then(res =>{
      this.myFavs = res;
    });
  });
}

Hope this helps :D


问:
Session management in Selenium webdriver
I have a class under which I have different methods one of them is login and other are related to the adding product to cart, checkout and shipping.
When I try to run the methods using TestNG in one go, it execute all the methods in different browsers session and I lost  my login session.
I want some solution so that either all the methods execute in same browser or I can use the session of login method in other consecutive methods
Thanks in advance

I have same login for both

I am creating new instance of driver in both methods

Here is my code :

public class purchase {

```<code>    @Test
    public void login(){
        System.setProperty("webdriver.chrome.driver", "{path}/chromedriver.exe");
        WebDriver fd= new ChromeDriver();
        fd.get("{domain}/login/");
        /*{login script here}*/
    }
    @Test
    public void purchaseItem(){
        System.setProperty("webdriver.chrome.driver", "{path}/chromedriver.exe");
        WebDriver fd1= new ChromeDriver();
        fd1.get("{domain}/travel");
        /*add item to cart*/
    }
</code>```

}

答:
Here you go.. as per your comment - "I am creating new instance of driver in both methods"..

So, if you want to maintain the session, you have to use a single instance of driver in both methods.

You can achieve it using beforeClass method (Use it for driver initializing and login), and write your logic in different test methods.. So it will make sure complete test cycle for the class is 1 and then your session will not be lost.

Let me know if this helps.

Body:
I have a class under which I have different methods one of them is login and other are related to the adding product to cart, checkout and shipping.
When I try to run the methods using TestNG in one go, it execute all the methods in different browsers session and I lost  my login session.
I want some solution so that either all the methods execute in same browser or I can use the session of login method in other consecutive methods
Thanks in advance

I have same login for both

I am creating new instance of driver in both methods

Here is my code :

public class purchase {

    @Test
    public void login(){
        System.setProperty("webdriver.chrome.driver", "{path}/chromedriver.exe");
        WebDriver fd= new ChromeDriver();
        fd.get("{domain}/login/");
        /*{login script here}*/
    }
    @Test
    public void purchaseItem(){
        System.setProperty("webdriver.chrome.driver", "{path}/chromedriver.exe");
        WebDriver fd1= new ChromeDriver();
        fd1.get("{domain}/travel");
        /*add item to cart*/
    }

}

ContentLicense: CC BY-SA 4.0


问:
How can I avoid entering a character in an EditBox in Android Studio?
I want to prevent the user from entering a character in an EditText a second time, for example, if you enter the number zero, it's OK but if you want to enter the number zero for the second time, that action should be canceled.

In other words, I don't want the user to write 00.

Is there any way to do it?

答:
You can do it this way:</p>

```<code>   EditText editText  = new EditText(this);
   InputFilter inputFilter = new InputFilter() {
       @Override
       public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            //Write your logic to remove the zero
            //remove the zero here and return it.
            return null;
       }};

   editText.setFilters(new InputFilter[]{inputFilter});
</code>```

Body:
You can do it this way:

   EditText editText  = new EditText(this);
   InputFilter inputFilter = new InputFilter() {
       @Override
       public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
            //Write your logic to remove the zero
            //remove the zero here and return it.
            return null;
       }};

   editText.setFilters(new InputFilter[]{inputFilter});


问:
Where does the business logic go in MVC?
I am a beginner to the ASP.Net MVC. After reading many tutorials and digesting its concepts, I have yet to see an approach that clearly demonstrates where does the business logic go.

My app will have a lot of use of jQuery AJAX usage (which will be calling Controller's Actions for various purposes such as dependent interaction, validation). I will definitely use the ViewModel concept, but I am still unclear where the business logic should reside. I do not want to put in the controller or a model. Should I put it in a separate service layer?

答: Business logic in theory engaged the middle tier of a 3-tier architecture.


问:
App rejected due to launch crash
Yesterday I have submitted binary to iTunes. And they rejected the binary due to launch crash. Also they rejected due to iPv6. I have tested my app on iPv6 network and its working fine. I don't know why this is happening.

Here is the crash report:

```<code>Version:             11 (2)
Code Type:           ARM-64 (Native)
Role:                Foreground
Parent Process:      launchd [1]
Coalition:           com.identifier

Date/Time:           2017-07-05 10:28:28.1687 -0700
Launch Time:         2017-07-05 10:28:08.0087 -0700
OS Version:          iPhone OS 10.3.2 (14F89)
Report Version:      104

Exception Type:  EXC_CRASH (SIGKILL)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Termination Reason: Namespace SPRINGBOARD, Code 0x8badf00d
Triggered by Thread:  0

Filtered syslog:
None found

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libsystem_kernel.dylib          0x000000018559f224 0x18559e000 + 4644
1   libsystem_kernel.dylib          0x000000018559f09c 0x18559e000 + 4252
2   libdispatch.dylib               0x0000000185490ee4 0x185479000 + 98020
3   libdispatch.dylib               0x00000001854912e8 0x185479000 + 99048
4   libxpc.dylib                    0x00000001856b8ee0 0x1856b2000 + 28384
5   Security                        0x00000001869dbe44 0x1869b1000 + 175684
6   Security                        0x00000001869dc114 0x1869b1000 + 176404
7   Security                        0x0000000186a016ec 0x1869b1000 + 329452
8   Security                        0x0000000186a03730 0x1869b1000 + 337712
9   Security                        0x0000000186a0078c 0x1869b1000 + 325516
10  Security                        0x0000000186a01424 0x1869b1000 + 328740
11  Security                        0x0000000186a0122c 0x1869b1000 + 328236
12  Security                        0x00000001869ffc3c 0x1869b1000 + 322620
13  Security                        0x0000000186a00d58 0x1869b1000 + 327000
14  APPNAME                     0x0000000100112cf0 0x1000c8000 + 306416
15  APPNAME                     0x0000000100222898 0x1000c8000 + 1419416
16  APPNAME                     0x00000001002225a8 0x1000c8000 + 1418664
17  APPNAME                     0x0000000100199584 0x1000c8000 + 857476
18  APPNAME                     0x00000001001936f4 0x1000c8000 + 833268
19  APPNAME                     0x0000000100194690 0x1000c8000 + 837264
20  UIKit                           0x000000018c75e204 0x18c6dd000 + 528900
21  UIKit                           0x000000018c96a738 0x18c6dd000 + 2676536
22  UIKit                           0x000000018c9701e0 0x18c6dd000 + 2699744
23  UIKit                           0x000000018c984d18 0x18c6dd000 + 2784536
24  UIKit                           0x000000018c96d474 0x18c6dd000 + 2688116
25  FrontBoardServices              0x000000018816b884 0x188131000 + 239748
26  FrontBoardServices              0x000000018816b6f0 0x188131000 + 239344
27  FrontBoardServices              0x000000018816baa0 0x188131000 + 240288
28  CoreFoundation                  0x000000018657142c 0x186496000 + 898092
29  CoreFoundation                  0x0000000186570d9c 0x186496000 + 896412
30  CoreFoundation                  0x000000018656e9a8 0x186496000 + 887208
31  CoreFoundation                  0x000000018649eda4 0x186496000 + 36260
32  UIKit                           0x000000018c757384 0x18c6dd000 + 500612
33  UIKit                           0x000000018c752058 0x18c6dd000 + 479320
34  APPNAME                     0x00000001001a2a98 0x1000c8000 + 895640
35  libdyld.dylib                   0x00000001854ad59c 0x1854a9000 + 17820

Thread 1:
0   libsystem_pthread.dylib         0x0000000185682ca8 0x185682000 + 3240

Thread 2 name:  com.apple.uikit.eventfetch-thread
Thread 2:
0   libsystem_kernel.dylib          0x000000018559f224 0x18559e000 + 4644
1   libsystem_kernel.dylib          0x000000018559f09c 0x18559e000 + 4252
2   CoreFoundation                  0x0000000186570e90 0x186496000 + 896656
3   CoreFoundation                  0x000000018656eae4 0x186496000 + 887524
4   CoreFoundation                  0x000000018649eda4 0x186496000 + 36260
5   Foundation                      0x0000000186fb8d74 0x186fac000 + 52596
6   Foundation                      0x0000000186fd9b44 0x186fac000 + 187204
7   UIKit                           0x000000018d0dc6a8 0x18c6dd000 + 10483368
8   Foundation                      0x00000001870b62d8 0x186fac000 + 1090264
9   libsystem_pthread.dylib         0x000000018568568c 0x185682000 + 13964
10  libsystem_pthread.dylib         0x000000018568559c 0x185682000 + 13724
11  libsystem_pthread.dylib         0x0000000185682cb4 0x185682000 + 3252

Thread 0 crashed with ARM Thread State (64-bit):
    x0: 0x0000000010004005   x1: 0x000000000400000e   x2: 0x0000000000000000   x3: 0x0000000000004000
    x4: 0x000000000000680b   x5: 0x0000000000000000   x6: 0x0000000000000000   x7: 0x0000000000000050
    x8: 0x00000000fffffbbf   x9: 0x000000016fd90000  x10: 0x000000016fd352f0  x11: 0x0000000000000018
   x12: 0x000000016fd352f0  x13: 0x00000000000000d3  x14: 0x0000000000000000  x15: 0x0000000800000000
   x16: 0xffffffffffffffe1  x17: 0xfffffff2ffffffff  x18: 0x0000000000000000  x19: 0x0000000000000000
   x20: 0x0000000000000000  x21: 0x000000000000680b  x22: 0x0000000000004000  x23: 0x000000016fd312f0
   x24: 0x000000000400000e  x25: 0x0000000000000000  x26: 0x000000000400000e  x27: 0x00000000fffffefb
   x28: 0x00000000efffbffe   fp: 0x000000016fd312e0   lr: 0x000000018559f09c
    sp: 0x000000016fd31290   pc: 0x000000018559f224 cpsr: 0x20000000
</code>```

Please help me out.

答:
I had faced the same issue. Mine was also rejected due to IPV6. Check below two things for your application:

1) Make sure you API link which you used in your application, doesn't have any ip address. If you calling API using IPAddress then your application will be rejected.

2) Do testing your application using IPV6 network through your system. Here is the link.

If your application is fullfill both testcase, then don't do any thing, just right comment in iTuneConnect and told them that my application is running in IPV6 network. Can you please guide to find my issue? If possible then can I have a call with your representative?

So they ask your contact detail and give you call and your issue will resvoled. I have wasted around 20 days to solved this issue. But apple representative told that this is them internal issue.

So my humble advice to contact Apple representative as soon as possible and your issue will resolve without doing anything.

Title: App rejected due to launch crash

Body:
Yesterday I have submitted binary to iTunes. And they rejected the binary due to launch crash. Also they rejected due to iPv6. I have tested my app on iPv6 network and its working fine. I don't know why this is happening.

Here is the crash report:

Version:             11 (2)
Code Type:           ARM-64 (Native)
Role:                Foreground
Parent Process:      launchd [1]
Coalition:           com.identifier

Date/Time:           2017-07-05 10:28:28.1687 -0700
Launch Time:         2017-07-05 10:28:08.0087 -0700
OS Version:          iPhone OS 10.3.2 (14F89)
Report Version:      104

Exception Type:  EXC_CRASH (SIGKILL)
Exception Codes: 0x0000000000000000, 0x0000000000000000
Exception Note:  EXC_CORPSE_NOTIFY
Termination Reason: Namespace SPRINGBOARD, Code 0x8badf00d
Triggered by Thread:  0

Filtered syslog:
None found

Thread 0 name:  Dispatch queue: com.apple.main-thread
Thread 0 Crashed:
0   libsystem_kernel.dylib          0x000000018559f224 0x18559e000 + 4644
1   libsystem_kernel.dylib          0x000000018559f09c 0x18559e000 + 4252
2   libdispatch.dylib               0x0000000185490ee4 0x185479000 + 98020
3   libdispatch.dylib               0x00000001854912e8 0x185479000 + 99048
4   libxpc.dylib                    0x00000001856b8ee0 0x1856b2000 + 28384
5   Security                        0x00000001869dbe44 0x1869b1000 + 175684
6   Security                        0x00000001869dc114 0x1869b1000 + 176404
7   Security                        0x0000000186a016ec 0x1869b1000 + 329452
8   Security                        0x0000000186a03730 0x1869b1000 + 337712
9   Security                        0x0000000186a0078c 0x1869b1000 + 325516
10  Security                        0x0000000186a01424 0x1869b1000 + 328740
11  Security                        0x0000000186a0122c 0x1869b1000 + 328236
12  Security                        0x00000001869ffc3c 0x1869b1000 + 322620
13  Security                        0x0000000186a00d58 0x1869b1000 + 327000
14  APPNAME                     0x0000000100112cf0 0x1000c8000 + 306416
15  APPNAME                     0x0000000100222898 0x1000c8000 + 1419416
16  APPNAME                     0x00000001002225a8 0x1000c8000 + 1418664
17  APPNAME                     0x0000000100199584 0x1000c8000 + 857476
18  APPNAME                     0x00000001001936f4 0x1000c8000 + 833268
19  APPNAME                     0x0000000100194690 0x1000c8000 + 837264
20  UIKit                           0x000000018c75e204 0x18c6dd000 + 528900
21  UIKit                           0x000000018c96a738 0x18c6dd000 + 2676536
22  UIKit                           0x000000018c9701e0 0x18c6dd000 + 2699744
23  UIKit                           0x000000018c984d18 0x18c6dd000 + 2784536
24  UIKit                           0x000000018c96d474 0x18c6dd000 + 2688116
25  FrontBoardServices              0x000000018816b884 0x188131000 + 239748
26  FrontBoardServices              0x000000018816b6f0 0x188131000 + 239344
27  FrontBoardServices              0x000000018816baa0 0x188131000 + 240288
28  CoreFoundation                  0x000000018657142c 0x186496000 + 898092
29  CoreFoundation                  0x0000000186570d9c 0x186496000 + 896412
30  CoreFoundation                  0x000000018656e9a8 0x186496000 + 887208
31  CoreFoundation                  0x000000018649eda4 0x186496000 + 36260
32  UIKit                           0x000000018c757384 0x18c6dd000 + 500612
33  UIKit                           0x000000018c752058 0x18c6dd000 + 479320
34  APPNAME                     0x00000001001a2a98 0x1000c8000 + 895640
35  libdyld.dylib                   0x00000001854ad59c 0x1854a9000 + 17820

Thread 1:
0   libsystem_pthread.dylib         0x0000000185682ca8 0x185682000 + 3240

Thread 2 name:  com.apple.uikit.eventfetch-thread
Thread 2:
0   libsystem_kernel.dylib          0x000000018559f224 0x18559e000 + 4644
1   libsystem_kernel.dylib          0x000000018559f09c 0x18559e000 + 4252
2   CoreFoundation                  0x0000000186570e90 0x186496000 + 896656
3   CoreFoundation                  0x000000018656eae4 0x186496000 + 887524
4   CoreFoundation                  0x000000018649eda4 0x186496000 + 36260
5   Foundation                      0x0000000186fb8d74 0x186fac000 + 52596
6   Foundation                      0x0000000186fd9b44 0x186fac000 + 187204
7   UIKit                           0x000000018d0dc6a8 0x18c6dd000 + 10483368
8   Foundation                      0x00000001870b62d8 0x186fac000 + 1090264
9   libsystem_pthread.dylib         0x000000018568568c 0x185682000 + 13964
10  libsystem_pthread.dylib         0x000000018568559c 0x185682000 + 13724
11  libsystem_pthread.dylib         0x0000000185682cb4 0x185682000 + 3252

Thread 0 crashed with ARM Thread State (64-bit):
    x0: 0x0000000010004005   x1: 0x000000000400000e   x2: 0x0000000000000000   x3: 0x0000000000004000
    x4: 0x000000000000680b   x5: 0x0000000000000000   x6: 0x0000000000000000   x7: 0x0000000000000050
    x8: 0x00000000fffffbbf   x9: 0x000000016fd90000  x10: 0x000000016fd352f0  x11: 0x0000000000000018
   x12: 0x000000016fd352f0  x13: 0x00000000000000d3  x14: 0x0000000000000000  x15: 0x0000000800000000
   x16: 0xffffffffffffffe1  x17: 0xfffffff2ffffffff  x18: 0x0000000000000000  x19: 0x0000000000000000
   x20: 0x0000000000000000  x21: 0x000000000000680b  x22: 0x0000000000004000  x23: 0x000000016fd312f0
   x24: 0x000000000400000e  x25: 0x0000000000000000  x26: 0x000000000400000e  x27: 0x00000000fffffefb
   x28: 0x00000000efffbffe   fp: 0x000000016fd312e0   lr: 0x000000018559f09c
    sp: 0x000000016fd31290   pc: 0x000000018559f224 cpsr: 0x20000000

Please help me out.


问:
docker-compose copies files as folder
I am trying to copy elasticsearch.yml with CORS enabled from my host to a container using docker-compose volumes option.
But when I copy the config folder it copies the elasticsearch.yml file in it as a folder.

Here is my docker-compose file:

```<code>version: "3"

services:
elasticsearch1:
    container_name: my_container_name
    image: elasticsearch
    environment:
      - "ES_JAVA_OPTS=-Xms1024m -Xmx1024m"
    volumes:
      - /config/:/usr/share/elasticsearch/config/
    ports:
      - '9200:9200'
      - '9300:9300'
</code>```

And this is the error message i get whe running docker-compose up:

Exception in thread "main" SettingsException[Failed to load settings from /usr/share/elasticsearch/config/elasticsearch.yml]; nested: IOException[Is a directory];

I also tried copying to tmp folder, and  file was listed as a folder:

drwxr-xr-x 2 root root 40 Jul  6 08:25 elasticsearch.yml

What am I doing wrong?

答:
With Docker for Windows and Docker for Mac, you are running docker inside of a VM and mounting directories from inside that VM into your container. When the file or directory doesn't exist inside the VM, it will get mounted as an empty folder by Docker as a default behavior (this behavior appears to be changing with swarm mode).

To get a folder from the windows host into the VM where it can then be mapped into a container, you need to go into the docker settings and configure your shared drives:

https://docs.docker.com/docker-for-windows/#shared-drives

Title: docker-compose copies files as folder

Body:
I am trying to copy elasticsearch.yml with CORS enabled from my host to a container using docker-compose volumes option.
But when I copy the config folder it copies the elasticsearch.yml file in it as a folder.

Here is my docker-compose file:

version: "3"

services:
elasticsearch1:
    container_name: my_container_name
    image: elasticsearch
    environment:
      - "ES_JAVA_OPTS=-Xms1024m -Xmx1024m"
    volumes:
      - /config/:/usr/share/elasticsearch/config/
    ports:
      - '9200:9200'
      - '9300:9300'

And this is the error message i get whe running docker-compose up:

Exception in thread "main" SettingsException[Failed to load settings from /usr/share/elasticsearch/config/elasticsearch.yml]; nested: IOException[Is a directory];

I also tried copying to tmp folder, and  file was listed as a folder:

drwxr-xr-x 2 root root 40 Jul  6 08:25 elasticsearch.yml

What am I doing wrong?


问:
Android NumberPicker with Formatter doesn't format on first rendering
I have a NumberPicker that has a formatter that formats the displayed numbers either when the NumberPicker spins or when a value is entered manually. This works fine, but when the NumberPicker is first shown and I initialize it with setValue(0) the 0 does not get formatted (it should display as "-" instead of 0). As soon as I spin the NumberPicker from that point on everything works.

How can I force the NumberPicker to format always - Both on first rendering and also when I enter a number manually with the keyboard?

This is my formatter

```<code>public class PickerFormatter implements Formatter {

 private String mSingle;
 private String mMultiple;

 public PickerFormatter(String single, String multiple) {
    mSingle = single;
    mMultiple = multiple;
 }

 @Override
 public String format(int num) {
    if (num == 0) {
        return "-";
    }
    if (num == 1) {
        return num + " " + mSingle;
    }
    return num + " " + mMultiple;
 }

}
</code>```

I add my formatter to the picker with setFormatter(), this is all I do to the picker.

```<code>    picker.setMaxValue(max);
    picker.setMinValue(min);
    picker.setFormatter(new PickerFormatter(single, multiple));
    picker.setWrapSelectorWheel(wrap);
</code>```

答:
The following solution worked out for me for APIs 18-26 without using reflection, and without using setDisplayedValues().

It consists of two steps:

Make sure the first element shows by setting it's visibility to invisible (I used Layout Inspector to see the difference with when it shows, it's not logical but View.INVISIBLE actually makes the view visible).

```<code>private void initNumberPicker() {
 // Inflate or create your BugFixNumberPicker class
 // Do your initialization on bugFixNumberPicker...

 bugFixNumberPicker.setFormatter(new NumberPicker.Formatter() {
    @Override
    public String format(final int value) {
        // Format to your needs
        return aFormatMethod(value);
    }
 });

 // Fix for bug in Android Picker where the first element is not shown
 View firstItem = bugFixNumberPicker.getChildAt(0);
  if (firstItem != null) {
    firstItem.setVisibility(View.INVISIBLE);
  }
}
</code>```

Subclass NumberPicker and make sure no click events go through so the glitch where picker elements disapear on touch can't happen.

```<code>public class BugFixNumberPicker extends NumberPicker {

 public BugFixNumberPicker(Context context) {
    super(context);
 }

 public BugFixNumberPicker(Context context, AttributeSet attrs) {
    super(context, attrs);
 }

 public BugFixNumberPicker(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
 }

 @Override
 public boolean performClick() {
    return false;
 }

 @Override
 public boolean performLongClick() {
    return false;
 }

 @Override
 public boolean onInterceptTouchEvent(MotionEvent event) {
    return false;
 }
}
</code>```

Body:
I have a NumberPicker that has a formatter that formats the displayed numbers either when the NumberPicker spins or when a value is entered manually. This works fine, but when the NumberPicker is first shown and I initialize it with setValue(0) the 0 does not get formatted (it should display as "-" instead of 0). As soon as I spin the NumberPicker from that point on everything works.

How can I force the NumberPicker to format always - Both on first rendering and also when I enter a number manually with the keyboard?

This is my formatter

public class PickerFormatter implements Formatter {

 private String mSingle;
 private String mMultiple;

 public PickerFormatter(String single, String multiple) {
    mSingle = single;
    mMultiple = multiple;
 }

 @Override
 public String format(int num) {
    if (num == 0) {
        return "-";
    }
    if (num == 1) {
        return num + " " + mSingle;
    }
    return num + " " + mMultiple;
 }

}

I add my formatter to the picker with setFormatter(), this is all I do to the picker.

    picker.setMaxValue(max);
    picker.setMinValue(min);
    picker.setFormatter(new PickerFormatter(single, multiple));
    picker.setWrapSelectorWheel(wrap);

Body:
The following solution worked out for me for APIs 18-26 without using reflection, and without using setDisplayedValues().

It consists of two steps:

Make sure the first element shows by setting it's visibility to invisible (I used Layout Inspector to see the difference with when it shows, it's not logical but View.INVISIBLE actually makes the view visible).

private void initNumberPicker() {
 // Inflate or create your BugFixNumberPicker class
 // Do your initialization on bugFixNumberPicker...

 bugFixNumberPicker.setFormatter(new NumberPicker.Formatter() {
    @Override
    public String format(final int value) {
        // Format to your needs
        return aFormatMethod(value);
    }
 });

 // Fix for bug in Android Picker where the first element is not shown
 View firstItem = bugFixNumberPicker.getChildAt(0);
  if (firstItem != null) {
    firstItem.setVisibility(View.INVISIBLE);
  }
}

Subclass NumberPicker and make sure no click events go through so the glitch where picker elements disapear on touch can't happen.

public class BugFixNumberPicker extends NumberPicker {

 public BugFixNumberPicker(Context context) {
    super(context);
 }

 public BugFixNumberPicker(Context context, AttributeSet attrs) {
    super(context, attrs);
 }

 public BugFixNumberPicker(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
 }

 @Override
 public boolean performClick() {
    return false;
 }

 @Override
 public boolean performLongClick() {
    return false;
 }

 @Override
 public boolean onInterceptTouchEvent(MotionEvent event) {
    return false;
 }
}


问:
Is Stata Turing-complete?
I have been doing some statistics work with Stata recently and not enjoying it very much.

It doesn't feel to me like it's a "proper" programming language: in particular I don't think there's a way to loop until a condition is met.

Am I right in my feeling, or is Stata truly Turing-complete?

答:
@eric.a.booth: I think your example is strange.  I'm not sure I've ever seen while { ... } else {...}

Also, note that Stata doesn't test the loop before you run it, and will allow itself to get caught in an infinite loop.

```<code>local x = 0
while `x'<5 {
   display `x' / 2
   local ++x
}
</code>```

Title: Is Stata Turing-complete?

Body:
@eric.a.booth: I think your example is strange.  I'm not sure I've ever seen while { ... } else {...}

Also, note that Stata doesn't test the loop before you run it, and will allow itself to get caught in an infinite loop.

local x = 0
while `x'<5 {
   display `x' / 2
   local ++x
}


问:
Program is not inserting into the database
My program doesn't insert into the database, tried various means, I'm new to php and tried to test myself with this but I'm finding it difficult to get. i think the problem is at the connection to the database but I'm not getting it </p>

```<code><!DOCTYPE html>
<html>
    <head>
        <title>LIST</title>
    </head>
    <body>
        <h1> TODO LIST </h1>
        <?php
            if(isset($_POST["submit"])){
                $servername = "localhost";
                $username = "root";
                $password = "";

                try {
                    //create a database conneection
                    $conn = mysqli_connect("localhost", "root", "");
                    if(!$conn){
                        die("Database connection failed: ". mysql_error());
                    }
                    $sql = "INSERT INTO tasks (task, date, time) VALUES (:task, :date, :time)";
                    $query = $conn->prepare($sql);
                    $query->execute(array(':task'=>$task,
                        ':date'=>$date,':time'=>$time));
                }
                catch(PDOException $e)
                {
                    echo "Connection failed: " . $e->getMessage();
                }
            }
        ?>

        <form action = "todolist.php" method = "post">
          Task: <input type="text" name="task" id="task"><br/>
          Date: <input type="date" name="date" id="date"><br/>
          Time: <input type="time" name="time" id="time"><br/>
        <input type = "submit" value = "submit" name="submit">
        </form>
    </body>
</html>
</code>```

答:
Are you connected to your database? You do not select any bdd and the logs are the right ones?

Maybe try:

```<code> $conn = mysqli_connect("localhost", "root", "", "databasename");
</code>```

At first, see if you are connected to your database

Body:
My program doesn't insert into the database, tried various means, I'm new to php and tried to test myself with this but I'm finding it difficult to get. i think the problem is at the connection to the database but I'm not getting it

<!DOCTYPE html>

        <title>LIST</title>

 TODO LIST

        <?php
            if(isset($_POST["submit"])){
                $servername = "localhost";
                $username = "root";
                $password = "";

                try {
                    //create a database conneection
                    $conn = mysqli_connect("localhost", "root", "");
                    if(!$conn){
                        die("Database connection failed: ". mysql_error());
                    }
                    $sql = "INSERT INTO tasks (task, date, time) VALUES (:task, :date, :time)";
                    $query = $conn->prepare($sql);
                    $query->execute(array(':task'=>$task,
                        ':date'=>$date,':time'=>$time));
                }
                catch(PDOException $e)
                {
                    echo "Connection failed: " . $e->getMessage();
                }
            }
        ?>

        <form action = "todolist.php" method = "post">
          Task: <input type="text" name="task" id="task">

          Date: <input type="date" name="date" id="date">

          Time: <input type="time" name="time" id="time">

        <input type = "submit" value = "submit" name="submit">
        </form>

Body:
Are you connected to your database? You do not select any bdd and the logs are the right ones?

Maybe try:

 $conn = mysqli_connect("localhost", "root", "", "databasename");

At first, see if you are connected to your database


问:
How to fix the last element of LineLayout that it does not go beyond the boundaries of the screen?
I try make layout with two TextView and one Linear Layout:

```<code><?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_orange_dark"
        android:text="testsdddddddddddddddddddddddddddasdsdfsdfsdf"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_dark"
        android:maxLines="1"
        android:text="NOT HIDE TEXT"/>
</LinearLayout>
</code>```

But when the first element has many characters second text is hidding.

But I want to do so:

And when first text is short (or second element may not fill all aviliable area):

How i can do it? May be i need use RelativeLayout?
Big thanks for your answers!)

答:
@Shahin Mursalov is Right but there is no need to take two LinearLayout just one will be good enough.

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

    <TextView
        android:id="@+id/kek1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="90dp"
        android:background="@android:color/holo_orange_dark"
        android:ellipsize="end"
        android:maxLines="1"
        android:text="tegetghrhrebbbbbbbbbbbbgetgetge" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="-90dp"
        android:layout_toRightOf="@id/kek1"
        android:background="@android:color/holo_red_dark"
        android:gravity="center"
        android:maxLines="1"
        android:minWidth="120dp"
        android:text="NOT HIDE TEXT" />
</RelativeLayout>
</code>```

OUTPUT

with long Text

with Short Text

Body:
I try make layout with two TextView and one Linear Layout:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_orange_dark"
        android:text="testsdddddddddddddddddddddddddddasdsdfsdfsdf"/>
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_red_dark"
        android:maxLines="1"
        android:text="NOT HIDE TEXT"/>
</LinearLayout>

But when the first element has many characters second text is hidding.

But I want to do so:

And when first text is short (or second element may not fill all aviliable area):

How i can do it? May be i need use RelativeLayout?
Big thanks for your answers!)

Body:
@Shahin Mursalov is Right but there is no need to take two LinearLayout just one will be good enough.

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

    <TextView
        android:id="@+id/kek1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="90dp"
        android:background="@android:color/holo_orange_dark"
        android:ellipsize="end"
        android:maxLines="1"
        android:text="tegetghrhrebbbbbbbbbbbbgetgetge" />

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_marginLeft="-90dp"
        android:layout_toRightOf="@id/kek1"
        android:background="@android:color/holo_red_dark"
        android:gravity="center"
        android:maxLines="1"
        android:minWidth="120dp"
        android:text="NOT HIDE TEXT" />
</RelativeLayout>

OUTPUT

with long Text

with Short Text


问:
My delegate is nil when trying to remove child from parent IOS swift 3
I have a child view which takes over the entire parent view. I want the child to be removed from the parent by call a method from the parent using a protocol but my delegate is nil every time. I add my sample work below if you need more information just let me know

```<code>protocol childDelegate: class {
           func removeFromParent()
        }
        class ChildAction: UITableViewController {
           @IBAction func btnRemove(_sender: Any){
              if(delegate != nil){
               self.delegate?.removeFromParent()
            }
          }
        }
        class ParentClass: UIViewController:childDelegate {

         var delegate:childDelegate?
         private ChildActionView:ChildAction{
             let storyboard = UIStoryBoard(name: "Main", bundle: Bundle.main)
             let viewC = storyboard.instantiateViewController(withIdentifier: "ChildAction") as! ChildAction
              self.delegate = viewC as? childDelegate
              self.addChildViewController(viewC)
              return viewC

         }
        @IBAction func btnAddChild(_sender: Any){
              addChild(child:ChildActionView)
            }

        func addChild(child: UIViewController){
            self.addChildViewController(child)
            view.addSubview(child.view)
            child.didMove(toParentViewController: self)
        }

          func removeFromParent(){
              //remove from parent

          }
        }
</code>```

Child view controller
parent view controller image

答: No where in your code did you set the delegate variable of your ChildAction instance (your childVC). You set parent's delegate to child but that is meaningless in your code. You need to set child's delegate to parent. Currently child do not have any reference of its parent, so naturally its delegate is nil. Let me know if something is unclear.

Body:
I have a child view which takes over the entire parent view. I want the child to be removed from the parent by call a method from the parent using a protocol but my delegate is nil every time. I add my sample work below if you need more information just let me know

protocol childDelegate: class {
           func removeFromParent()
        }
        class ChildAction: UITableViewController {
           @IBAction func btnRemove(_sender: Any){
              if(delegate != nil){
               self.delegate?.removeFromParent()
            }
          }
        }
        class ParentClass: UIViewController:childDelegate {

         var delegate:childDelegate?
         private ChildActionView:ChildAction{
             let storyboard = UIStoryBoard(name: "Main", bundle: Bundle.main)
             let viewC = storyboard.instantiateViewController(withIdentifier: "ChildAction") as! ChildAction
              self.delegate = viewC as? childDelegate
              self.addChildViewController(viewC)
              return viewC

         }
        @IBAction func btnAddChild(_sender: Any){
              addChild(child:ChildActionView)
            }

        func addChild(child: UIViewController){
            self.addChildViewController(child)
            view.addSubview(child.view)
            child.didMove(toParentViewController: self)
        }

          func removeFromParent(){
              //remove from parent

          }
        }

Child view controller
parent view controller image


问:
Text Parser with PHP, like Instapaper
I'm trying to write a text parser with PHP, like Instapaper did. What I want to do is; get a webpage and parse it in text-only mode.

It's simple to get the webpage with cURL and strip HTML tags. But every webpage have some common areas; like header, navigation, sidebar, footer, banners etc. I only want to get the article in text mode and exclude all other parts. It's also simple to exclude those parts if I know the "id" or "class" info. But I'm trying to automatize this process and apply for any page, like Instapaper.

I get all the content between  but I don't know how to exclude header, sidebar or footer and get only the main article body. I have to develop a logic to get only the main article part.

It's not important for me to find the exact code. It would also be useful to understand how to exclude unnecessary parts as I can try to write my own code with PHP. It would also be useful if there any examples in other languages.

Thanks for helping.

答:
you can take a look at the source from Goose -> it already does alot of this like instapaper text extractions

https://github.com/jiminoc/goose/wiki

Title: Text Parser with PHP, like Instapaper


问:
PHP dynamically create multidimensional array keys
I need to dynamically compute my multidimensional array keys  for an aggegration in Elasticsearch.

I have the following

$aggs['aggs']['name']

But aggs and name needs to be populated in a loop. So for example:

```<code> $aggs['aggs']['name']['aggs']  = $glue;

// looping

$aggs['aggs']['name']['aggs']['name']['aggs'] = $glue;

// looping

 $aggs['aggs']['name']['aggs']['name']['aggs']['name']['aggs']  = $glue;

// etc
</code>```

The array keys needs to be computed with the keys aggs and name

How can i dynamically create keys in an array?

Thanks

答:
Hope this is what you want. I have created one array with keys. Then traverse that array to create multi dimension array

```<code>$keys = array("aggs","name","aggs","name","aggs");
$aggs = array();

$aggs = add_keys_dynamic($aggs,$keys,"test");
echo "```";
print_r($aggs);

function add_keys_dynamic($main_array, $keys, $value){
    $tmp_array = &$main_array;
    while( count($keys) > 0 ){
        $k = array_shift($keys);
        if(!is_array($tmp_array)){
            $tmp_array = array();
        }
        $tmp_array = &$tmp_array[$k];
    }
    $tmp_array = $value;
    return $main_array;
}
```

Example

Body:
I need to dynamically compute my multidimensional array keys  for an aggegration in Elasticsearch.

I have the following

$aggs['aggs']['name']

But aggs and name needs to be populated in a loop. So for example:

 $aggs['aggs']['name']['aggs']  = $glue;

// looping

$aggs['aggs']['name']['aggs']['name']['aggs'] = $glue;

// looping

 $aggs['aggs']['name']['aggs']['name']['aggs']['name']['aggs']  = $glue;

// etc

The array keys needs to be computed with the keys aggs and name

How can i dynamically create keys in an array?

Thanks

Body:
Hope this is what you want. I have created one array with keys. Then traverse that array to create multi dimension array

$keys = array("aggs","name","aggs","name","aggs");
$aggs = array();

$aggs = add_keys_dynamic($aggs,$keys,"test");
echo "<pre>";
print_r($aggs);

function add_keys_dynamic($main_array, $keys, $value){
    $tmp_array = &$main_array;
    while( count($keys) > 0 ){
        $k = array_shift($keys);
        if(!is_array($tmp_array)){
            $tmp_array = array();
        }
        $tmp_array = &$tmp_array[$k];
    }
    $tmp_array = $value;
    return $main_array;
}

Example


问:
The server responded with a status of 500 AJAX Post
I have this javascript function which should redirect me to

http://localhost:8888/ID OF A PRODUCT/add-to-cart".

But instead I got this:

http://localhost:8888/undefined/add-to-cart".

```<code>$('.add-to-cart').on('click', function () {
        var productId = $(this).find('.indexImg').attr('id');

        $.ajax(productId+"/add-to-cart",
        {

        });
    });
</code>```

image}}" id="{{$product->id}}">

Can someone help me to get ID of a product ?

HTML:

```<code> @foreach($products as $product)
  <div class="col-md-3">
        <div class="box-product">
            <div class="img-wrapper item">
                <a href="/product/{{$product->id}}/{{$product->slug}}">
                    <a class="thumbnail" href="/product/{{$product->id}}/{{$product->slug}}" style="margin-bottom: 0px; border: none;">
                    <img class="indexImg" src="{{$product->image}}" id="{{$product->id}}">
                    </a>
                </a>
            <div class="tags">
            @if($product->discount > 0)
                <span class="label-tags"><span class="label label-danger">Išpardavimas</span></span>
            @endif
                <span class="label-tags"><span class="label label-info">Nauja</span></span>
            </div>
            <div class="option">
                <i class="fa fa-shopping-cart add-to-cart" aria-hidden="true" style="color: white"></i>
            </div>
        </div>
</code>```

答:
Do one thing
Change

With

id}}">

and get by

```<code>$(this).attr('id');
</code>```

So the code will be

```<code>$('.add-to-cart').on('click', function () {
        var productId =  $(this).attr('id');

        $.ajax(productId+"/add-to-cart",
        {

        });
    });
</code>```

Body:
I have this javascript function which should redirect me to

http://localhost:8888/ID OF A PRODUCT/add-to-cart".

But instead I got this:

http://localhost:8888/undefined/add-to-cart".

$('.add-to-cart').on('click', function () {
        var productId = $(this).find('.indexImg').attr('id');

        $.ajax(productId+"/add-to-cart",
        {

        });
    });

image}}" id="{{$product->id}}">

Can someone help me to get ID of a product ?

HTML:

 @foreach($products as $product)

                id}}/{{$product->slug}}">
                    id}}/{{$product->slug}}" style="margin-bottom: 0px; border: none;">
                    image}}" id="{{$product->id}}">

            @if($product->discount > 0)
                Išpardavimas
            @endif
                Nauja

Body:
Do one thing
Change

<i class="fa fa-shopping-cart add-to-cart" aria-hidden="true" style="color: white"></i>

With

<i class="fa fa-shopping-cart add-to-cart" aria-hidden="true" style="color: white" id="{{$product->id}}"></i>

and get by

$(this).attr('id');

So the code will be

$('.add-to-cart').on('click', function () {
        var productId =  $(this).attr('id');

        $.ajax(productId+"/add-to-cart",
        {

        });
    });


问:
RxJS - Observable.map generate objects with asynchronous initilatization
```<code>return this.http.get(url)
.map((response:Response) => {
  return (<any>response.json()).map(actu => new Actualite(actu));
});
</code>```

From this example.
The 'Actualite' constructor generate the value of one of its properties asynchronously (load image from url and manipulate it to a canvas)

```<code>export class Actualite {
Credit: string;
Mini: string;
/* ... */

constructor(fichier:any) {
    this.Credit =       fichier.Credit || '';
    this.Mini =         fichier.Mini || '';
    /* ... */

    if(this.Mini) {
        let img:HTMLImageElement = new Image();
        img.src = this.Mini;

        img.addEventListener('load', ()=> {

            let canvas:HTMLCanvasElement = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;
            let ctx:CanvasRenderingContext2D = canvas.getContext('2d');

            /*....... Image transformation......*/

            this.Data = canvas.toDataURL();

        })
    }
}
</code>```

}

So I want to subscribe this Observable first code when the asynchronous objects initialization is over and not, as in this example, when the objects are created

Thanks

答:
I'd suggest adding a reference to an observable created from the load event of the image in the actualite class.

Something like

```<code>constructor(fichier:any) {
    /*...*/
    this.loadObservable = Rx.Observable.empty() // case where `Mini` is false
    // you can also return a Rx.Observable.of(defaultValue) if you need something on the other side

    if (this.Mini) {
        let img:HTMLImageElement = new Image();
        img.src = this.Mini;

        this.loadObservable = Rx.Observable
          .fromEvent(img, "load")
          .map(event => /*... do you stuff with the image ...*/)
    }
}
</code>```

Now you can use this observable from the outside

```<code>return this.http.get(url)
  .map((response:Response) => {
    return (<any>response.json())
      .map(actu => new Actualite(actu))
      .mergeMap(actu => actu.loadObservable); // this will emit when the loadObservable emits
  });
</code>```

Body:
return this.http.get(url)
.map((response:Response) => {
  return (<any>response.json()).map(actu => new Actualite(actu));
});

From this example.
The 'Actualite' constructor generate the value of one of its properties asynchronously (load image from url and manipulate it to a canvas)

export class Actualite {
Credit: string;
Mini: string;
/* ... */

constructor(fichier:any) {
    this.Credit =       fichier.Credit || '';
    this.Mini =         fichier.Mini || '';
    /* ... */

    if(this.Mini) {
        let img:HTMLImageElement = new Image();
        img.src = this.Mini;

        img.addEventListener('load', ()=> {

            let canvas:HTMLCanvasElement = document.createElement('canvas');
            canvas.width = img.width;
            canvas.height = img.height;
            let ctx:CanvasRenderingContext2D = canvas.getContext('2d');

            /*....... Image transformation......*/

            this.Data = canvas.toDataURL();

        })
    }
}

}

So I want to subscribe this Observable first code when the asynchronous objects initialization is over and not, as in this example, when the objects are created

Thanks

Body:
I'd suggest adding a reference to an observable created from the load event of the image in the actualite class.

Something like

constructor(fichier:any) {
    /*...*/
    this.loadObservable = Rx.Observable.empty() // case where `Mini` is false
    // you can also return a Rx.Observable.of(defaultValue) if you need something on the other side

    if (this.Mini) {
        let img:HTMLImageElement = new Image();
        img.src = this.Mini;

        this.loadObservable = Rx.Observable
          .fromEvent(img, "load")
          .map(event => /*... do you stuff with the image ...*/)
    }
}

Now you can use this observable from the outside

return this.http.get(url)
  .map((response:Response) => {
    return (<any>response.json())
      .map(actu => new Actualite(actu))
      .mergeMap(actu => actu.loadObservable); // this will emit when the loadObservable emits
  });


问:
android - Format Double and put it in TextView without comma (if needed)
I get the "price" value from the server in Double and I need to put it in TextView in my application. The problem is: when price = 500 I get 500.0 because it's Double. I want it to look like 500.55 or 500.50 or just 500 - how do I format these numbers in the right way?

答:
Use the String#format method.

Read about it here: https://www.dotnetperls.com/format-java
or in the JavaDoc


问:
Why is my output Undefined or NaN?
For some reason, when I enter value, all of the output is
undefined and NaN and I have no idea why.I think the
error is really simple..so simple I would facepalm. Sorry
for my code, I'm still new to javascript. And also, nevermind about the Credit Card.

```<code>function processAmount(){
    var numOfLiters= parseInt(document.estore.noOfLiters.value);
    var result;
    var perLiterAmount;
    var gasType;

    switch(gasType){
    case "Premium":

            perLiterAmount= 50;
            result= 50*numOfLiters;
            break;
    case "Diesel":
           perLiterAmount= 38;
          result= 38*numOfLiters;
            break;

    case "Unleaded":
           perLiterAmount= 44;
            result= 44*numOfLiters;
            break;
    }

    var vat= result*0.12;

    document.write("<p>Fuel Type: " + gasType + "</p>");
    document.write("<p>Price per Liter amount: " + perLiterAmount + "</p>");
    document.write("<p>Purchase Amount: " + result + "</p>");
    document.write("<p>VAT: " + vat + "</p>");
    document.write("<p>TOTAL AMOUNT: " + (result+vat) + "</p>");
    document.write("<p>Credit Card : " + creditCard + "</p>");`
</code>```

and here is the form:

```<code> <form name='estore' id='estore'>
   <fieldset>
            <legend>Gasoline eStore</legend>
                <p>Enter gasoline type:
                    <select name='gastype' id='gastype'>
                        <option value="Premium"> Premium</option>
                        <option value="Unleaded"> Unleaded</option>
                        <option value="Diesel"> Diesel</option>
                        </select></p>

                <p> Enter number of Liters:
                    <input type='number' name='noOfLiters' id='noOfLiters'/>
                </p>

                <p> Enter Credit Card Number:
                    <input type="number" name='creditCardNumber' id='creditCardNumber'/>
                </p>

                <p>
                    <input type='button' value='Submit'
                        onclick="processAmount()"/>
                    <input type='reset'/>
                </p>
</code>```

答:
In your function assign the value to gastype

```<code>var gastype = $('#gastype :selected').val();
</code>```

Title: Why is my output Undefined or NaN?

Body:
For some reason, when I enter value, all of the output is
undefined and NaN and I have no idea why.I think the
error is really simple..so simple I would facepalm. Sorry
for my code, I'm still new to javascript. And also, nevermind about the Credit Card.

function processAmount(){
    var numOfLiters= parseInt(document.estore.noOfLiters.value);
    var result;
    var perLiterAmount;
    var gasType;

    switch(gasType){
    case "Premium":

            perLiterAmount= 50;
            result= 50*numOfLiters;
            break;
    case "Diesel":
           perLiterAmount= 38;
          result= 38*numOfLiters;
            break;

    case "Unleaded":
           perLiterAmount= 44;
            result= 44*numOfLiters;
            break;
    }

    var vat= result*0.12;

    document.write("
Fuel Type: " + gasType + "
");
    document.write("
Price per Liter amount: " + perLiterAmount + "
");
    document.write("
Purchase Amount: " + result + "
");
    document.write("
VAT: " + vat + "
");
    document.write("
TOTAL AMOUNT: " + (result+vat) + "
");
    document.write("
Credit Card : " + creditCard + "
");`

and here is the form:

 <form name='estore' id='estore'>
   <fieldset>
            <legend>Gasoline eStore</legend>

Enter gasoline type:
                    <select name='gastype' id='gastype'>
                        <option value="Premium"> Premium</option>
                        <option value="Unleaded"> Unleaded</option>
                        <option value="Diesel"> Diesel</option>
                        </select>

 Enter number of Liters:
                    <input type='number' name='noOfLiters' id='noOfLiters'/>

 Enter Credit Card Number:
                    <input type="number" name='creditCardNumber' id='creditCardNumber'/>

                    <input type='button' value='Submit'
                        onclick="processAmount()"/>
                    <input type='reset'/>

Body:
In your function assign the value to gastype

var gastype = $('#gastype :selected').val();


问:
I want to apply a overlay image on hover
But I am struggling.

Code I have for css is:

```
#gallery img {
width:700px;
height:213px;
margin:0;
padding:0;
}
```

So I thought ...

```
#gallery img:hover {
    width:700px;
    height:213px;
    position: relative;
    z-index:10000;
    background: transparent url(../images/imgOverlay-Zoom.png) no-repeat center center;
}
```

Would work, but it doesnt.

The image I am transparently overlaying on hover is:

What am I doing wrong.
I think I may have a corrupt css tag somewhere.

Any help appreciated.

答:
Hello there
I think you misunderstood the mechanics of CSS:
The image itself is an object and the background specified goes behind it.
So you have to make the non transparent image the background and specify the transparent one in the src. However this won't suit your needs.
A workaround would with CSS would be troublesome, so i would suggest to swap the whole image with a css hover or javascript onMouseover or jQuery - get familliar with those since it's the proper way.</p>

Body:
But I am struggling.

Code I have for css is:

#gallery img {
width:700px;
height:213px;
margin:0;
padding:0;
}

So I thought ...

#gallery img:hover {
    width:700px;
    height:213px;
    position: relative;
    z-index:10000;
    background: transparent url(../images/imgOverlay-Zoom.png) no-repeat center center;
}

Would work, but it doesnt.

The image I am transparently overlaying on hover is:

What am I doing wrong.
I think I may have a corrupt css tag somewhere.

Any help appreciated.


答:
use the array_walk_recursive function

```<code><?php
$aggs['aggs']['name'] = "name";

function addEnd(&$item, $key)
{
    if(is_array($item)){
        return;
    }elseif($key=='aggs'){
        $item=['name'=> ['aggs' => $item]];
    }else{
        $item=['aggs' => $item];
    }
}

for($i=0; $i<5; $i++){ // your loop
    array_walk_recursive($aggs, 'addEnd');
}

var_dump($aggs);
</code>```

check it here: https://3v4l.org/HmlYD

Title: PHP dynamically create multidimensional array keys

Body:
use the array_walk_recursive function

<?php
$aggs['aggs']['name'] = "name";

function addEnd(&$item, $key)
{
    if(is_array($item)){
        return;
    }elseif($key=='aggs'){
        $item=['name'=> ['aggs' => $item]];
    }else{
        $item=['aggs' => $item];
    }
}

for($i=0; $i<5; $i++){ // your loop
    array_walk_recursive($aggs, 'addEnd');
}

var_dump($aggs);

check it here: https://3v4l.org/HmlYD


问:
How to add column in Dataframe base on the value of other Columns spark
I have a Data-frame with column "Age" of type String,I want to get a new column containing the range in string format

Range as follows

[-1, 12, 17, 24, 34, 44, 54, 64, 100, 1000]

Input Values for example

```<code>Age
=====
-1
12
18
28
38
46
======
</code>```

Output Required

```<code>  Age    Age-Range
 =====  =========
 -1     (-1,12)
 12     (-1,12)
 18     (12-17)
 28     (24-34)
 38     (34-44)
 46     (44-54)
======  ==========
</code>```

Any Suggestion or Help is Highly Appreciated

答:
Here's a quick suggestion, I hope it helps:

case class AgeRange(lowerBound: Int, upperBound: Int) {
  def contains(value: Int): Boolean = value >= lowerBound && value < upperBound
}

val rangeList = List(-1, 12, 17, 24, 34, 44, 54, 64, 100, 1000)
val ranges = rangeList.sliding(2).map((list => AgeRange(list(0), list(1)))).toList
val dataset = Seq("-1", "12", "18", "28", "38", "46").toDS

def findRange(value: Int, ageRanges: List[AgeRange]): Option[AgeRange] = ageRanges.find(_.contains(value))

// With UDF
def myUdf(ageRanges: List[AgeRange]) = udf{
  i: Int => findRange(i, ageRanges)
}

val result1 = dataset.toDF("age").withColumn("age_range", myUdf(ranges)(col("age").cast("int")))

// With map
val result2 = dataset.map {
  i: String => (i, findRange(i.toInt, ranges))
}.toDF("age", "age_range")
```

<p>Resulting in:</p>

```result1: org.apache.spark.sql.DataFrame = [age: string, age_range: struct<lowerBound: int, upperBound: int>]
result2: org.apache.spark.sql.DataFrame = [age: string, age_range: struct<lowerBound: int, upperBound: int>]
+---+---------+
|age|age_range|
+---+---------+
| -1|  [-1,12]|
| 12|  [12,17]|
| 18|  [17,24]|
| 28|  [24,34]|
| 38|  [34,44]|
| 46|  [44,54]|
+---+---------+
```

Body:
I have a Data-frame with column "Age" of type String,I want to get a new column containing the range in string format

Range as follows

[-1, 12, 17, 24, 34, 44, 54, 64, 100, 1000]

Input Values for example

Age
=====
-1
12
18
28
38
46
======

Output Required

  Age    Age-Range
 =====  =========
 -1     (-1,12)
 12     (-1,12)
 18     (12-17)
 28     (24-34)
 38     (34-44)
 46     (44-54)
======  ==========

Any Suggestion or Help is Highly Appreciated

Body:
Here's a quick suggestion, I hope it helps:

case class AgeRange(lowerBound: Int, upperBound: Int) {
  def contains(value: Int): Boolean = value >= lowerBound && value < upperBound
}

val rangeList = List(-1, 12, 17, 24, 34, 44, 54, 64, 100, 1000)
val ranges = rangeList.sliding(2).map((list => AgeRange(list(0), list(1)))).toList
val dataset = Seq("-1", "12", "18", "28", "38", "46").toDS

def findRange(value: Int, ageRanges: List[AgeRange]): Option[AgeRange] = ageRanges.find(_.contains(value))

// With UDF
def myUdf(ageRanges: List[AgeRange]) = udf{
  i: Int => findRange(i, ageRanges)
}

val result1 = dataset.toDF("age").withColumn("age_range", myUdf(ranges)(col("age").cast("int")))

// With map
val result2 = dataset.map {
  i: String => (i, findRange(i.toInt, ranges))
}.toDF("age", "age_range")

Resulting in:

result1: org.apache.spark.sql.DataFrame = [age: string, age_range: struct<lowerBound: int, upperBound: int>]
result2: org.apache.spark.sql.DataFrame = [age: string, age_range: struct<lowerBound: int, upperBound: int>]
+---+---------+
|age|age_range|
+---+---------+
| -1|  [-1,12]|
| 12|  [12,17]|
| 18|  [17,24]|
| 28|  [24,34]|
| 38|  [34,44]|
| 46|  [44,54]|
+---+---------+


问:
I am trying to even spaced links in bootstrap navbar
I am looking for a way to easily utilize Bootstraps navbar but be able to instead of using

class="navbar-right"
or class="navbar-left"

I would like to be able to have the links to be evenly spaced across the view instead of always having to choose a side.

答:
Something like this? Try your own .navbar-justified class with flex:

```<code>.navbar-justified {
  display: flex;
  justify-content: space-between;
  float: none;
}
</code>```

Body:
Something like this? Try your own .navbar-justified class with flex:

.navbar-justified {
  display: flex;
  justify-content: space-between;
  float: none;
}


问:
Deleting files that belong to a post?
I have two tables called 'posts' and 'photos'. The 'photos' table store the images for the 'post'. A post can have many photos so the relationship is one-to-many. I've managed to create the store method, I already create the view to show a post with its photos as well. Below is the function :

```<code>public function show($titleslug) {
        $post = Post::where('titleslug', '=', $titleslug)->first();
        $images = $post->photos;
        return view('dashboard/posts/show', compact('post','images', $post, $images));
}
</code>```

The show view :

```<code><div class="contentpanel">
    <div class="row blog-content">
        <div class="col-sm-12">
            <div class="panel panel-default panel-blog">
                <div class="panel-body">
                    <div class="panel-body">
                        <h3 class="blogsingle-title">{{$post->title}}</h3>
                        <ul class="blog-meta">
                            <li><i class="fa fa-clock-o"></i> Jan 02, 2014</li>
                        </ul>
                        <div class="mb20"></div>
                        {!! $post->content !!}
                    </div><!-- panel-body -->

                    <div class="mb20"></div>
                </div><!-- panel-body -->
            </div><!-- panel -->
        </div><!-- col-sm-8 -->
    </div><!-- row -->
    <div class="row blog-content">
        <div class="col-sm-12">
            <div class="panel panel-default panel-blog">
                <div class="panel-body">
                    <h3 class="blogsingle-title">This post featured images :</h3>
                    <div class="mb20"></div>
                    <?php foreach ($images as $i): ?>
                        <div class="col-xs-12 col-sm-4 col-md-3">
                            <div class="blog-item">
                                <a href="#" class="blog-img"><img src="{{asset('image/'. $i->image)}}" class="img-responsive" alt="" style="height: 150px;"/></a>
                                <div class="blog-details">
                                    <ul class="blog-meta">
                                        <li><a class="btn btn-sm btn-warning" title="Edit" href="#"><i class="fa fa-edit"></i></a></li>
                                        <form action="#" method="POST">
                                            <input type="hidden" name="_method" value="DELETE">
                                            <input type="hidden" name="_token" value="{{ csrf_token() }}" />
                                            <li>
                                                <button type="submit" class="btn btn-sm btn-danger" title="Delete" onclick="return confirm('Are you sure deleting this photo ?');"><i class="fa fa-trash-o"></i></button>
                                            </li>
                                        </form>
                                    </ul>
                                </div>
                            </div><!-- blog-item -->
                        </div><!-- col-xs-6 -->
                    <?php endforeach; ?>
                </div>
                <div class="panel-body">
                    <div class="alert alert-info fade in">
                        <p>
                            <a href="#"><button type="button" class="btn btn-info">Add New Images</button></a>
                        </p>
                    </div>
                </div>
            </div><!-- panel -->
        </div>
    </div>
</div><!-- contentpanel -->
</code>```

I want to be able to delete the images from the show view, how to do that ? Do I need to create a function to it ? If so, then how will the function looks like ?
That's all and thanks, sorry for asking too much

答:
First, edit your delete form in the view by adding :

...
<input type="hidden" name="image_id" value="{{ $images->id }}" /> // Assuming that photo id is in your $images object
...
```

<p>Then, you could create a <code>POST</code> route <code>image/delete</code> associated to <code>delete</code> function from your <code>controller</code> to remove the expected image :</p>

<pre class="lang-php prettyprint-override"><code>public function delete() {
    $image_id = $request->only('image_id');

    $image = Photo::where('id', '=', $image_id)->delete(); // Assuming that you have a Photo model

    return view('dashboard/posts/show');
}
</code>```

Title: Deleting files that belong to a post?

Body:
I have two tables called 'posts' and 'photos'. The 'photos' table store the images for the 'post'. A post can have many photos so the relationship is one-to-many. I've managed to create the store method, I already create the view to show a post with its photos as well. Below is the function :

public function show($titleslug) {
        $post = Post::where('titleslug', '=', $titleslug)->first();
        $images = $post->photos;
        return view('dashboard/posts/show', compact('post','images', $post, $images));
}

The show view :

{{$post->title}}

 Jan 02, 2014

                        {!! $post->content !!}

This post featured images :

                    <?php foreach ($images as $i): ?>

                                image)}}" class="img-responsive" alt="" style="height: 150px;"/>

                                        <form action="#" method="POST">
                                            <input type="hidden" name="_method" value="DELETE">
                                            <input type="hidden" name="_token" value="{{ csrf_token() }}" />

                                                <button type="submit" class="btn btn-sm btn-danger" title="Delete" onclick="return confirm('Are you sure deleting this photo ?');"></button>

                                        </form>

                    <?php endforeach; ?>

                            <button type="button" class="btn btn-info">Add New Images</button>

I want to be able to delete the images from the show view, how to do that ? Do I need to create a function to it ? If so, then how will the function looks like ?
That's all and thanks, sorry for asking too much

Body:
First, edit your delete form in the view by adding :

...
<input type="hidden" name="image_id" value="{{ $images->id }}" /> // Assuming that photo id is in your $images object
...

Then, you could create a POST route image/delete associated to delete function from your controller to remove the expected image :

public function delete() {
    $image_id = $request->only('image_id');

    $image = Photo::where('id', '=', $image_id)->delete(); // Assuming that you have a Photo model

    return view('dashboard/posts/show');
}