How do I make a filter for ListView?

Question: I am developing an application, and I want to filter items in ListView, but items Ids are defined as Strings from another class(constructors) and filter doesn't work. (nothing happens)
I want filter to search through these Strings from that constructors, yet I do not know how to.
Here's my mainActivity Class:
    package com.example.industrialcraft;

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

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.example.R;

public class Items extends Activity {

    private List<Items_id> myItems = new ArrayList<Items_id>();
    ArrayAdapter<Items_id> adapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.items_industrialcraft);

        populateItems();
        adapter = new MyListAdapter();
        ListView list = (ListView) findViewById(R.id.list_industrialcraft);
        list.setAdapter(adapter);

        registerClickCallback();

    }

    private void populateItems() {

        myItems.add(new Items_id("Bronze Helmet", "Bronze_Helmet"));
        myItems.add(new Items_id("Bronze Chestplate", "Bronze_Chestplate"));
        myItems.add(new Items_id("Bronze Leggings", "Bronze_Leggings"));
        myItems.add(new Items_id("Bronze Boots", "Bronze_Boots"));
        myItems.add(new Items_id("Nano-Helmet", "Nano_Helmet"));
        myItems.add(new Items_id("Nano-Bodyarmor", "Nano_Bodyarmor"));
        myItems.add(new Items_id("Nano-Leggings", "Nano_Leggings"));
        myItems.add(new Items_id("Nano-Boots", "Nano_Boots"));
        myItems.add(new Items_id("QuantumSuit Helmet", "Quantumsuit_Helmet"));
        myItems.add(new Items_id("QuantumSuit Bodyarmor", "Quantumsuit_Bodyarmor"));
        myItems.add(new Items_id("QuantumSuit Leggings", "Quantumsuit_Leggings"));
        myItems.add(new Items_id("QuantumSuit Boots", "Quantumsuit_Boots"));
        myItems.add(new Items_id("Scuba Helmet", "Scuba_Helmet"));
        myItems.add(new Items_id("Hazmat Suit", "Hazmat_Suit"));
        myItems.add(new Items_id("Hazmat Suit Leggings", "Hazmat_Suit_Leggings"));
        myItems.add(new Items_id("Rubber Boots", "Rubber_Boots"));
        myItems.add(new Items_id("BatPack", "Batpack"));
        myItems.add(new Items_id("CF Backpack", "CF_Backpack"));
        myItems.add(new Items_id("Composite Vest", "Composite_Vest"));
        myItems.add(new Items_id("Electric Jetpack", "Electric_Jetpack"));
        myItems.add(new Items_id("Jetpack", "Jetpack"));
        myItems.add(new Items_id("Lappack", "Lappack"));
        myItems.add(new Items_id("Nightvision Goggles", "Nightvision_Goggles"));
        myItems.add(new Items_id("Solar Helmet", "Solar_Helmet"));
        myItems.add(new Items_id("Static Boots", "Statatic_Boots"));
        myItems.add(new Items_id("Booze Barrel", "Booze_Barrel"));
        myItems.add(new Items_id("Crop-Matron", "Crop_Matron"));
        myItems.add(new Items_id("Crop", "Crop"));
        myItems.add(new Items_id("Coffee Beans", "Coffee_Beans"));
        myItems.add(new Items_id("Coffee Powder", "Coffee_Powder"));
        myItems.add(new Items_id("Grin Powder", "Grin_Powder"));
        myItems.add(new Items_id("Hydration Cell", "Hydration_Cell"));
        myItems.add(new Items_id("Hops", "Hops"));
        myItems.add(new Items_id("Stone Mug", "Stone_Mug"));
        myItems.add(new Items_id("Coffee", "Coffee"));
        myItems.add(new Items_id("Dark Coffee", "Dark_Coffee"));
        myItems.add(new Items_id("Cropnalyzer", "Cropnalyzer"));
        myItems.add(new Items_id("Electric Hoe", "Electric_Hoe"));
        myItems.add(new Items_id("Fertilizer", "FErtilizer"));
        myItems.add(new Items_id("Weed-EX", "Weed_EX"));

    }

    private class MyListAdapter extends ArrayAdapter<Items_id>{

        public MyListAdapter(){
            super(Items.this, R.layout.items_industrialcraft_buttons, myItems);
        }

        EditText search = (EditText) findViewById(R.id.search);

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View itemView = convertView;
            if(itemView == null){
                itemView = getLayoutInflater().inflate(R.layout.items_industrialcraft_buttons, parent, false);
            }

            // Find item to work with

            Items_id currentItem = myItems.get(position);

            search.addTextChangedListener(new TextWatcher() {
                @Override
                public void onTextChanged(CharSequence currentItem, int arg1, int arg2, int arg3) {
                    // When user changed the

                    Items.this.adapter.getFilter().filter(currentItem);
                }

                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                        int arg3) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable arg0) {
                    // TODO Auto-generated method stub
                }
            });

            //Fill the view
            TextView makeText = (TextView)itemView.findViewById(R.id.textId);
            makeText.setText(currentItem.getId());
            return itemView;
        }

    }

    private void registerClickCallback() {
        ListView list = (ListView)findViewById(R.id.list_industrialcraft);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View viewClicked, int position,
                    long id) {
                Items_id clicked = myItems.get(position);

                //Find item
                Items_id currentItem = myItems.get(position);

                String abc = currentItem.getActivity();

                String activitys = abc;

                try{
                    Class classes = Class.forName("com.example.industrialcraft." + activitys);
                    Intent i = new Intent(Items.this, classes);
                    startActivity(i);
                }catch(ClassNotFoundException e){
                    e.printStackTrace();
                }

            }

        });
    }

}

Here is my Items_id Class:
package com.example.industrialcraft;

public class Items_id {

    private String id;
    private String activity;

    public Items_id(String id, String activity){
        super();
        this.id = id;
        this.activity = activity;
    }

    public String getId() {
        return id;
    }

    public String getActivity() {
        return activity;
    }
}

Comment: > Please see this link.. [Here is good example](http://www.androidbegin.com/tutorial/android-search-listview-using-filter/)
Answer:
Please remove

EditText search = (EditText) findViewById(R.id.search);

search.addTextChangedListener(new TextWatcher() {
                @Override
                public void onTextChanged(CharSequence currentItem, int arg1, int arg2, int arg3) {
                    // When user changed the

                    Items.this.adapter.getFilter().filter(currentItem);
                }

                @Override
                public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                        int arg3) {
                    // TODO Auto-generated method stub

                }

                @Override
                public void afterTextChanged(Editable arg0) {
                    // TODO Auto-generated method stub
                }
            });

from MyListAdapter and put it in oncreate method, and in filter use
  your condition whatever you wants.It not solved yet then let me know.
Comment: Will try and I let you know later this day and I don't exactly know how to set condition for filter.
Comment: It still doesnt work. I dont know how to set condition for filter, so I ask you to please explain me or give me some tutorial or link me something that will explain filter or give me a hint. Anyway, Thanks for help!!!
Comment: I already provide you a link (http://www.androidbegin.com/tutorial/android-search-listview-using-filter/), in it everything is well defined and implemented. read it carefully and implement it . if not able to implement, then let me know.
Comment: I made filter and impliment thinks from that link you gave me, but when I try to filter, nothing changes and i dont know why. Code is in anwser.
Comment: I think the problem is within the filter method, more specific somewhere in else statment, but I dont know what it is..
Comment: have you done all work, which i  told you.please post your updated MyListAdapter code here. then i will provide you solution.
Comment: add line arrayList = myItems; in MyListAdapter constractor and also override getsize() method of MyListAdapter add(int getSize() {return arrayList .size();}).
Comment: Look I figured it out and is working now. But your source is wrong, at the filter function tere must be NO else statment after if statment!!!Or you can just not write .clear() function in else statment!!!! But anyhow, thanks for help and that source you gave me was really usefull!!! Thanks again
Answer: Here is the code:
Items class:
    package com.example.industrialcraft;

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

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.example.R;

public class Items extends Activity {

    private List<Items_id> myItems = new ArrayList<Items_id>();
    private List<Items_id> arrayList = new ArrayList<Items_id>();
    ArrayAdapter<Items_id> adapter;
    String activity[];
    String id[];

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.items_industrialcraft);

        populateItems();
        adapter = new MyListAdapter();
        ListView list = (ListView) findViewById(R.id.list_industrialcraft);
        list.setAdapter(adapter);

        final MyListAdapter fil = new MyListAdapter();
        String abcd = "";
        fil.filter(abcd);
        final EditText search = (EditText) findViewById(R.id.search);

        search.addTextChangedListener(new TextWatcher() {
            @Override
            public void onTextChanged(CharSequence a, int position, int arg2, int arg3) {
                String text = search.getText().toString();
                fil.filter(text);

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
                    int arg3) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable arg0) {

            }
        });

        registerClickCallback();

    }

    private void populateItems() {

        activity = new String[] {"Bronze_Helmet", "Bronze_Chestplate", "Bronze_Leggings"};

        id = new String[] {"Bronze Helmet", "Bronze Chestplate", "Bronze Leggings"};

        for (int i = 0; i < activity.length; i++)
        {
            Items_id wp = new Items_id(id[i], activity[i]);
            myItems.add(wp);
        }

    }

    private class MyListAdapter extends ArrayAdapter<Items_id>{

        public MyListAdapter(){
            super(Items.this, R.layout.items_industrialcraft_buttons, myItems);
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View itemView = convertView;
            if(itemView == null){
                itemView = getLayoutInflater().inflate(R.layout.items_industrialcraft_buttons, parent, false);
            }

            // Find item to work with

            Items_id currentItem = arrayList.get(position);

            //Fill the view
            TextView makeText = (TextView)itemView.findViewById(R.id.textId);
            makeText.setText(currentItem.getId());
            return itemView;
        }

        public void filter(String charText){
            arrayList.clear();
            if (charText.length() == 0) {
                arrayList.addAll(myItems);
            }
            else
            {
                for (Items_id id : arrayList)
                {
                    if (id.getId().contains(charText))
                    {
                        arrayList.add(id);
                    }
                }
            }notifyDataSetChanged();
        }

    }

    private void registerClickCallback() {
        ListView list = (ListView)findViewById(R.id.list_industrialcraft);
        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View viewClicked, int position,
                    long id) {
                Items_id clicked = arrayList.get(position);

                //Find item
                Items_id currentItem = arrayList.get(position);

                String abc = currentItem.getActivity();

                String activitys = abc;

                try{
                    Class classes = Class.forName("com.example.industrialcraft." + activitys);
                    Intent i = new Intent(Items.this, classes);
                    startActivity(i);
                }catch(ClassNotFoundException e){
                    e.printStackTrace();
                }

            }

        });
    }

}

Items_id class:
    package com.example.industrialcraft;

public class Items_id {

    private String id;
    private String activity;

    public Items_id(String id, String activity){
        super();
        this.id = id;
        this.activity = activity;
    }

    public String getId() {
        return id;
    }

    public String getActivity() {
        return activity;
    }
}

How do I make a filter for ListView?


Can anyone tell me what's wrong with this script?

Question: The script is working just fine but IE is giving me the error "Done but with errors on page" and I can't figure out why.
<code>(function($){
     $.fn.extend({
         tabify: function() {
            function getHref(el){
                hash = $(el).find('a').attr('href');
                if(hash)
                    return hash.substring(0,hash.length-4);
                else
                    return false;
                }
            function setActive(el){
                $(el).addClass('active');
                if(getHref(el))
                    $(getHref(el)).show();
                else
                    return false;
                $(el).siblings('li').each(function(){
                    $(this).removeClass('active');
                    $(getHref(this)).hide();
                });
            }
            return this.each(function() {
                var self = this;

                $(this).find('li>a').each(function(){
                    $(this).attr('href',$(this).attr('href') + '-tab');
                });

                function handleHash(){
                    if(location.hash)
                        setActive($(self).find('a[href=' + location.hash + ']').parent());
                }
                if(location.hash)
                    handleHash();
                setInterval(handleHash,100);
                $(this).find('li').each(function(){
                    if($(this).hasClass('active'))
                        $(getHref(this)).show();
                    else
                        $(getHref(this)).hide();
                });
            });
        }
    });
})(jQuery);
</code>
Comment: Have you tried using a debugger? Or at least opening the Javascript error console to see what the "errors on page" are? (In Firefox, for example, this is Ctrl-Shift-J.)
Comment: Click on it and figure out what the errors are?
Comment: You could go to [JS Lint](http://jslint.com/) and paste the above code there to see what errors are thrown up (quite a few).
Comment: Use the error console (or the yellow exclamation mark in IE) to find what errors *what* errors you actually get
Comment: have you tried clicking on it to see what the actual error was?
Answer: Installing Firebug plugin on Firefox can help you to better understand what is not working well and many other things.
Comment: Should be a comment imo. And if it doesn't work in IE then Firebug might not help much...
Comment: I know, but unfortunately before this vote up I couldn't comment... a bit strange StackOverflow rule, isn't it?
Anyway Firebug can help showing if there's something not regular in the code, maybe even when Firefox processes it well.


Sharing an Apache configuration between testing vs. production

Question: I have a personal web site with a slightly nontrivial Apache configuration. I test changes on my personal machine before uploading them to the server. The path to the files on disk and the root URL of the site are of course different between the test and production conditions, and they occur many places in the configuration (especially <Directory> blocks for special locations which have scripts or no directory listing or ...).
What is the best way to share the common elements of the configuration, to make sure that my production environment matches my test environment as closely as possible?
Answer: My own answer: What I've thought of is to use SetEnv to store the paths for the current machine in environment variables, then Include a common configuration file with ${} everywhere there's something machine specific. But I have never used these facilities before, and I don't know if there's some caveat.
Comment: Turns out that this feature, which I thought I read about somewhere, doesn't actually exist. Never mind!
Answer: Now this is no direct answer to your question, because it involves a change of setup, but to avoid exactly this problem, I will virtualize both my test system and my production server. I hope that this will give me less hassle with configuration as i will run identical images and add easy scalability or redundancy in the future.
Maybe you have the opportunity to run virtualized....
You should also have a look at those two threads about versioning and duplicating server configurations and moving installed linuxes between platforms
Answer: It could be possible to just set up some scaffolding using sym/hardlinks, change mountpoints etc so that the test environment paths match production. Depending on your particular setup it could be quite easy, or it might be both ugly and complicated..
To access the test environment, use it's IP, or you could add an extra ServerAlias with a name that points to your test environment, or you might just configure the same name for both machines and use your local /etc/hosts to switch which one you want to access.
Comment: The machines are very different platforms; making them similar would be messy for both. I want a way to vary the Apache config, not everything else. And using `/etc/hosts` in particular would be too broad since I want to be able to access my own live site from my personal machine.
Comment: Ok, then using some form of variable substitution is most likely a good idea. I can not really help much with that though, but good luck to you! If that fails for some reason, you could always use a sed script or similar to automate search-replace edits.. :)
Answer: I ended up using a configuration template file and a small Python program using the string.Template facility to generate two different configurations. I have included it below.
This substitutes the configuration values into generic.tmpl.conf (which is the site internal configuration), then makes the result available as ${conf} for use in test.tmpl.conf and production.tmpl.conf, which have the VirtualHost block containing ${conf}, log files, and other such host-specific information.
#!/usr/bin/python

import string
from optparse import OptionParser

# ---

parser = OptionParser()
parser.add_option("--clean", dest="clean", action="store_true", default=False,
                  help="Clean files instead of creating them.")
(options, args) = parser.parse_args()
if len(args) != 0:
  parser.error("No non-option arguments expected.")

# ---

def readconf(name):
  return string.Template(open(name).read())

def writeconf(out, outer, inner, fields):
  outerfields = fields.copy()
  outerfields["conf"] = inner.substitute(fields).replace("\n", "\n\t")
  out.write(outer.substitute(outerfields))
  out.close()

# ---

if options.clean:
  os.remove("production.conf")
  os.remove("test.conf")
else:
  commonconf = readconf("generic.tmpl.conf")
  liveconf = readconf("production.tmpl.conf")
  testconf = readconf("test.tmpl.conf")

  writeconf(open("production.conf", "w"), liveconf, commonconf, {
    # ... configuration values redacted ...
  })

  writeconf(open("test.conf", "w"), testconf, commonconf, {
    # ... configuration values redacted ...
  })

Answer: Try using <Location> instead of <Directory> where possible, so that changing the DocumentRoot will cover most of your changes.  That's probably the easiest way to take care of it.
The Include directive can also be your friend -- you can stick it inside a <Directory> or <Location> block to include the parts of the configuration that won't change between machines.
This is a little more of a hack, but you could also use DirectoryMatch to match both your testing and production directories in one section.
Comment: Using `` seems a good idea independently, but it won't actually help here, because the testing setup is `http://localhost/test-site/foo` as opposed to `http://live-site.example.com/foo`.
Comment: In that case, maybe something like  would work.

A better option might be to set up test-site.localhost as a domain alias, so you can have /foo be the same throughout.  I don't envy a setup that has different paths in testing vs. live.


How to show text on a SVG path

Question: So I have points on my SVG map and now I would like to show text next to them. This is a jsfiddle with 2 points and showing their ID text. But as you can see there is no text somehow.
var featureCollection = topojson.feature(topology, topology.objects.testtest);

lines.append("g")
  .attr("id", "lines")
  .selectAll("path")
  .data(featureCollection.features)
  .enter().append("path")
  .attr("d", path)
  .append("text")
  .attr("class", "nodetext")
  .attr("x", 22)
  .attr("y", 4)
  .text(function (d) {
      return d.properties.id;
  });

And I checked it with some other text beside example I already have here.  It's working in the same way.
So does it not work with pathes? Could that be?
Answer: A 'text' element can't be a child of a 'path' element, it should be a sibling. Group them if they are related and need to be positioned accordingly.
Comment: Could you give me an example about how to change the svg code? Or just how the strcture should be? I'm not completely sure how to solve it.
Answer: As @liamness says, your text can't be a child of path but needs to be a sibling.   Your problem goes a little further, though, since you are using a path and you can't group and position the element conventionally.  There is where path.centroid comes in handy.  It allows you to find the center of you path and position your text there:
var e = lines.append("g")
    .attr("id", "lines")
    .selectAll("path")
    .data(featureCollection.features)
    .enter(); // save enter selection

e.append("path") // add path as child of lines g
    .attr("d", path);

e.append("text") // add text as child of lines g, sibling of path
    .attr("class", "nodetext")
    .attr('x', function(d,i){
        return path.centroid(d)[0]; // horizontal center of path
    })
    .attr('y', function(d,i){
       return path.centroid(d)[1] + 13; // vertical center of path
    })
    .attr('text-anchor','middle')
    .text(function (d) {
        return d.properties.id;
    });

Updated fiddle.
Comment: Wow this works instantly, perfectly and is really straigthforward. Awesome. Thank you so much, exactly what I was looking for.

How to show text on a SVG path


ruby pry whereami command not working

Question: I'm working with pry 0.10.1 java and pry-nav 0.2.4 on jruby 1.7.12 (1.9.3p392). In the middle of an rspec step after invoking binding.pry, I type the pry command:
whereami

All I get is
ArgumentError: Symbol or String expected, but NilClass given.
from /Users/yc98js1/.rbenv/versions/jruby-1.7.18/lib/ruby/gems/shared/gems/coderay-1.1.0/lib/coderay/helpers/plugin.rb:215:in `validate_id'

whereamI going wrong? [pun intended]
Comment: Does `@` work? (alias of whereami)
Comment: Always found that JRuby and pry don't play nice together. Worth debugging in MRI and running your specs with JRuby?
Answer: Seems like the error was thrown by the coderay gem. Could be a collision of this gem with another.
It might be unrelated but its hiding the error. try uninstalling coderay first and running the code again.

ruby pry whereami command not working


How do I add a taxonomy vocabulary to more than one menus with the taxonomy menu module?

Question: I'd like to have two different menus based on the same taxonomy vocabulary, but the taxonomy menu module only lets me choose one menu to add the terms to.
Can I somehow add the same terms to more than one menu?
Answer: Try this: https://www.drupal.org/project/taxonomy_menu_block
Otherwise, you can use views to create blocks with links from a taxonomy vocabulary.
Comment: Thanks! I settled with the method using views, that was perfect for what I wanted to do! A related taxonomy term block for taxonomy pages.


Number of terms in an Arithmetic progression

Question: 1 and 20 are first and last terms of the arithmetic progression. If all the terms of this arithmetic progression are integers, then find the different number of terms that this arithmetic progression can have ?
Comment: Let $s$ be the step size and $k$ be the number of terms. Then $1+s(k-1)=20$. Simplify.
Comment: Sounds like homework. Is it? At any rate, here's a hint. An arithmetic sequence always has the form a, a + n, a + 2n, ... . You know that a = 1 and 20 = a + nk. Go from there.
Comment: Hi, my doubt is that will you consider : 1 and 20 as a arithmetic progression.
Comment: @ArpitBajpai Yes, with step size 19.
Answer: Here's an obvious generalization which may be interesting to you, and which exposes the reasoning for the question above: $1$ and $(1+p)$ are the first and last terms of an arithmetic progression, where $p$ is prime. If all the terms of this arithmetic progression are integers, how many different number of terms can this arithmetic progression have?
See if you can generalize Henning's comment regarding your original question which was that the number of terms $k$ with step size $s$ must satisfy $1+s(k-1)=20$ in order to answer this question as well.
Comment: That is 2 and p + 1.
Comment: but my confusion is that what should be minimum number of terms in an arithmetic progression.
Comment: @ArpitBajpai You are correct, 2 and p+1 is the answer. 2 terms still qualify as an arithmetic progression.
Comment: @Eugene The comments provided by others sufficiently addressed the OP's question, so to prevent this question from remaining unanswered I will leave this as an answer and make it community wiki, which is hopefully satisfactory.
Comment: @MichaelBoratko Oh. Yup you're absolutely right about that.


text_field_tag placeholder ignoring dynamic text after space in rails

Question: I am using I18n for internationalization. for displaying place holder content in locale language in placeholder of text_field_tag im using following code.
<%= text_field_tag('email', "", class: 'form-control', placeholder: t('shared.enter_email')%>

And config/locales/en.yml content is as follows:
en:
  shared:
    enter_email: Enter Email

on running application, the content in the placeholder contains only Enter and its ignoring name because there is a space in-between.
i tried different syntax, all are producing same result. Is there a way to get this done?
Comment: yml should be like this probably `enter_email: 'Enter Email'`
Comment: did you restart your server after that?
Comment: inspect input tag. what `placeholder` attribute contains?
Answer: I was able to solve this issue by using interpolation like this.
<%= text_field_tag('email', "", class: 'form-control', placeholder: "#{t('shared.enter_email')}" %>


Drupal recommended-project missing Drush

Question: I am looking to transform from drupal-project to recommended-project and seeing  some difference in the folder structure.
drupal-project contains a drush folder outside'web' folder and  'composer.json' contains line "drush/drush": "^9.0.0".
However, recommended-project does not have this setup although I could still install drush using composer require drush/drush. Still drush isn't installed outside 'web' folder.
Can I please know why the setup has changed and a way to have drush folder outside 'web'?
Comment: I'm voting to close this question as too broad. You can maybe learn more about the whys reading through https://www.drupal.org/project/drupal/issues/2982680 and https://github.com/drupal-composer/drupal-project/issues/538. And the drush folder outside web you are referring to probably is the one to hold custom Drush config or modules, innit?
Comment: You need to provide more details like your composer.json. The behavior your suggesting works out-of-the-box using the [composer project template](https://www.drupal.org/docs/develop/using-composer/starting-a-site-using-drupal-composer-project-templates) and using `composer require drush/drush` ends up with drush inside vendor outside of web/.
Answer: It is important to understand the distinction between the Drupal core project templates and the drupal-composer project template.

The Recommended and Legacy project templates are maintained by Drupal core. As a result, it only includes those components validated by the core maintainers to be very stable and needed by most Drupal users. The bar for this is very high, and the complexity of the component plays into the decision. For example, Drush is very stable and used by most Drupal users, but it is a fairly large and complex project, and therefore has not been added to a core project template. Use the Recommended project if you'd like your web root inside a "web" directory, or the Legacy project if you would like your web root at the project root.
The drupal-composer/drupal-project template is maintained by the community. It contains more components that are likely to be useful to a wide range of users. If a bug or configuration problem is found with this project, then it must be reported and fixed through the community repository on GitHub.

The latest version of drupal-composer/drupal-project uses the same core scaffold components as the drupal/recommended-project Composer template provided by Drupal core. It is safe to start with the drupal-composer/drupal/project template for your site.
If you add Drush to your site, either by starting with drupal-composer/drupal-project, or by adding it manually to the drupal/recommended-project, then the Drush binary will always be installed inside the vendor directory. This will be inside the web root for the Legacy project, or outside the webroot for the Recommended project, and for drupal-composer/drupal-project.
If you decide to start with the Recommended project and add Drush, you should also look at the composer.json for drupal-composer/drupal-project and see if there is any configuration in the "extra" section that you might want to copy over for your site.


Why does "my blog" menu link disappear when I use a view with the path blog/%?

Question: When I create a view with the path blog/%, the menu link "My blog" disappear from the main menu but still exists in the database. The view works exactly as expected when I go to /blogs and click the nav link at the bottom of the article.
Already tried without success (logged in as administrator)
1) Change view access to:

none
permission: view published content
permission: blog entry:
create new content role: authenticated users

2) Add/Remove the view filter: status published
3) Create a new menu link using Menu Token module but this link disappears too (but still exists in the db).
4) Enable/disable Menu Token and Menu item visibility modules, just to check if there is a conflict somewhere but it doesn't change anything.
Versions:

Drupal 7.31
Blog 7.31
Views 7.x-3.8.
Menu Token 7.x-1.0-beta5
Menu item visibility 7.x-1.0-beta1
Answer: The path that the blog module uses is blog/%user .
If you go to blog/1 you will see all posts made by the user with uid equals 1.
So, when you create a views:view that defines the path blog/%, it overrides the default path previously defined by blog and uses the views path.
Comment: Thanks, but I still don't understand why the menu link disappears: the path is overriden, not the menu link. Views module do not allow to create menu links with arguments.
Comment: The "my blog" menu link is the default menu link that comes with the blog module or its a custom menu link that you created?
The way that drupal handles menu links connects each link to a path. If you see the [link]https://api.drupal.org/api/drupal/includes!menu.inc/function/menu_link_save/7[/link], two variables are required, the path and the title.
So, if you override the path, the menu router will not display that menu link (since the path it was suposed to point to is not acessible anymore).
Comment: I tried with a custom menu link but it disappears from the menu when the view path contains an argument. Now I have deleted it, and try to make the default link (system) work.
Comment: Thanks for the doc, I understand that 2 arguments are required but these are already stored in the db. I have checked "override title" in the contextual filter "author UID", but it does not work. What am I supposed to do? I guess I should start again with a new content type and disable the blog module.
Comment: what do you want? a page that uses views to show the posts AND a page that shows only the posts from a determined user?


How can I find minimum execution time in PowerShell?

Question: I have been using Measure-Command in PowerShell to time the execution of a Python script:
Measure-Command{C:\Python27\python.exe script.py}

This displays the execution time in a number of forms, including TotalSeconds.
In order to minimize the effect of overhead, I would like to run the script 10 times and find the minimal TotalSeconds value across the 10 runs. Is there a simple way to do this in PowerShell?
Answer: Use Measure-Object command, like in this SO answer:
C:\PS> 1..10 | % { Measure-Command { C:\Python27\python.exe script.py } } | Measure-Object -Minimum

Count    : 3
Average  :
Sum      :
Maximum  :
Minimum  : 00:00:00.0095165
Property :

Comment: It looks like the `Measure-Object` command needs to be `Measure-Object -Minimum TotalSeconds`, but otherwise this works well. Thanks.


Is there any way to get availableOutputs like availableInputs in AVAudioSession

Question: I need to list available outputs (like BleutoothLE, HeadPhones, BuiltInReceiver) but i can just access currentRoute's output.
Can anyone access all available outputs, please share your comments ?
Thanks in advance.
Answer: You have two options as far as I know:

Add a MPVolumeView to your view and, set showsVolumeSlider to 0 and set showsRouteButton to 1.  This will put a system provided icon where the user can pick from available outputs.
AVAudioSession has a very limited overrideOutputAudioPort method that can route audio to the built in speaker.
[[AVAudioSession sharedInstance] overrideOutputAudioPort:AVAudioSessionPortOverrideSpeaker error:nil];

Comment: Thanks Dave for your interest but I have already looked at MPVolumeView .it gives only a button to show available output on UI but i need to access the list of available outputs in code and change audio route using them.
Comment: I believe there is no such access.  You can only retrieve a port description for the output of the current route via '[[[[AVAudioSession sharedInstance] currentRoute] outputs] firstObject]', not all available routes.  The outputs array always has one object.
Answer: I have no idea why there wasn't a simple availableOutputs property.
But you can get a list of all available outputs by using the multi-route audio category and inspecting your current route's outputs:
let sesh = AVAudioSession()
try! sesh.setCategory(AVAudioSessionCategoryMultiRoute)
try! sesh.setActive(true)

print("available outputs: \(sesh.currentRoute.outputs)\n")

Outputs (and inputs) come and go, causing route changes, so subscribe to the route change notification:
NSNotificationCenter.defaultCenter().addObserver(
    self,
    selector: "routeChanged:",
    name: AVAudioSessionRouteChangeNotification,
    object:nil
)

NB: multi-route category has a lot of rules about when inputs/outputs that are intuitively available, are actually available (e.g. speaker isn't "available" when you have a USB soundcard plugged in, but wired headphones will be).
What are you trying to do? I've used multi-route to playback 4 channel audio, but I'm not sure if you actually can mix and match between the outputs.
Answer: Get list of all the outputs using AVAudioSession's currentRoute:
AVAudioSession *session = [AVAudioSession sharedInstance];
NSLog(@"Outputs: %@", [[session currentRoute] outputs]);

Comment: this only returns the current output route, not all available ones.


How to find the total spendings in a restaurant when it is given as a system of equations using exponents?

Question: The problem is as follows:
Jenny goes to dinner to a well known restaurant in town. The number of times she goes to the restaurant is $\frac{a}{2}$ times and for each time she went, she spent $b^{2}$ hundreds of dollars. Find the money Jenny spent assuming the following system of equations was observed by Jenny.
$$\begin{cases}
3^a-2^{b^{2}}=77 \\
3^{\frac{a}{2}}-2^{\frac{b^2}{2}}=7 \\
\end{cases}$$
The alternatives given in my book are as follows:
$\begin{array}{ll}
1.&\textrm{600 dollars}\\
2.&\textrm{500 dollars}\\
3.&\textrm{400 dollars}\\
4.&\textrm{300 dollars}\\
\end{array}$
In this given situation the only thing which I can understand is as this:
$\textrm{Money spent}=\frac{a}{2}\cdot b^2\cdot 10^2$
But the thing is how to find $a$ and $b$, which sort of simplication or algebraic manipulation can be done to solve this system of equation.
Can someone help me?.
Answer: Guide:
We have
$$3^a-2^{b^2}=77$$
and
$$3^{\frac{a}2}-2^{\frac{b^2}2}=7$$
Dividing the equations, we get
$$3^{\frac{a}2}+2^{\frac{b^2}2}=11$$
Now, solve a linear system equation to solve for $3^\frac{a}2$ and $2^\frac{b^2}2$.
Comment: I think **the problem here is how to divide those two equations** can you include these?. I'm stuck at **how you did that**?. Please, I'm stuck.
Comment: We use the identity $x^2-y^2 = (x-y)(x+y)$. Dividing $x^2-y^2$ with $x-y$ gives us $x+y$. Try to identify the $x$ and $y$ here.
Answer: Let $x = 3^a$ and $y = 2^{b^2}$
Therefore, $x   = 77+y$   (as $x-y = 77$)
and, $\sqrt{x} = \sqrt{y} + 7$  (as $\sqrt{x} - \sqrt{y} = 7$)
Squaring the second and subtractiing from the first we have,
$0 =28-14\sqrt{y}$
Therefore, $y = 4$ and $x=81$
So $a =4$ and $b^2 =2$
The answer is 400


problem with alternating group with order 3

Question: I was doing some computation with $A_3$, the alternating group on 3 letters. I know it has to be abelian, even cyclic, but when I carried out the actual computation... I couldn't make sense out of it. I think I misunderstood the entire concept of cyclic permutation, so please help me out...
So, in $A_3$, there are: $(1,2),(2,3),(1,3)$. All of these have to permute, but... (ACCORDING TO MY MOST LIKELY WRONG CALCULATION,)
$(1,2)(2,3) = (1,3,2)$, but $(2,3)(1,2)=(1,2,3)$. What??
Likewise, $(1,2)(1,3)=(1,2,3)$, but $(1,3)(1,2)=(1,3,2)$.
What am I doing wrong??? By the way, I use array notation for computing the permutation. So when I do $(1,2)(1,3)$, I write first $2,1,3$, and apply to it $(1,3)$ to get $2,3,1$, and so final permutation becomes $(1,2,3)$. Am I doing something wrong? If so, please correct me once and for all...
Thanks.
Comment: The permutations in $A_3$ are $(1,2,3),\ (1,3,2)$ and $id$. The other three you listed are not even permutations. They are odd.
Comment: Ah, now I feel even dumber. Are the above calculations correct, by the way?
Answer: $S_3$ is non-abelian.
$A_3$ is the subgroup of $S_3$ that has an even number of transpositions.  (1,2) and (2,3) are not in $A_3$ but (1,2)(2,3) is.
(1,2)(2,3) = (1,3,2) and (2,3)(1,2) = (1,2,3) because $S_3$ is non-abelian.
(1,2,3)^2 = (1,3,2) and (1,2,3)^3 = e.  $A_3$ is cyclic.
Hope this helps.


How to get the autocomplete feature for a taxonomy term profile field visible on the registration form?

Question: I have Profile2 and Profile2 Registration Path modules enabled, I set up two different profiles, and for one of them I created a field which is a taxonomy term with the Autocomplete term widget (tagging).
When adding a user within the administration interface, I have the autocomplete widget working, but for anonymous users trying to create a profile the widget is not even attached to the field... I know it is not attached because a field with the widget has a "autocomplete" class and an icon for ajax status in background, but the field on the registration form has no class..
How to add this widget ? Is it a permission issue ? or adding the class to the field through hook_form_FORM_ID_alter() could be enough ? (I don't have the field in the $form array though...
Comment: Turns out it is a permission issue : adding the permission for anonymous users to `View published content` solves my problem as I do not have any reason to not let them see the website content..

I guess for websites where content is for registered users only, this permission would not be granted and the widget would not be used on the taxonomy term field.. Maybe the `Content Access` module could help those use-cases
Comment: In the future, instead of leaving a comment, you should answer your own question and then mark that answer as accepted.  *Drupal Answers* encourages you to answer your own questions when you find the answer; this helps future users who may have the same question that you did.
Comment: I couldn't answer my own question yesterday, I had to wait 8hours before I could do, so instead of leaving people in the doubt, I did answer my own question by leaving a comment :)
Answer: Turns out it is a permission issue : adding the permission for anonymous users to View published content solves my problem as I do not have any reason to not let them see the website content
I guess for websites where content is for registered users only, this permission would not be granted and the widget would not be used on the taxonomy term field.. Maybe the Content Access module could help those use-cases


Disable the "smoke" in SmokePing for multihost

Question: I'm running SmokePing to monitor the latency to several machines.
I have been playing around with the multihost feature, allowing me to draw stats of multiple machines in one graph.
However, on the details page, smoke is being drawn as well, resulting in this:

Is  there a way to disable this? As it makes the graph pretty much unreadable.
Smoke is enabled for the stats per server, so it's duplicated data.
Answer: Well the whole 'smoke' part is pretty integral to the tool.  If you don't have any spread at all on the RTT, it's just a regular ping time graph, right?
The only idea I can think of to improve your graphs is to experiment with setting max_rtt to a very low number to cut off outliers.  You could also try setting pings to the minimum of 3, maybe that would give you less variation and nicer graphs.
For that matter, what about just setting up regular mrtg and using a simple ping monitor without all the fancy features of smokeping?  Or, set up munin and use one of the several ping monitors available for that monitoring tool.
Comment: I would like to have to smoke for every other graph, just the "multihost" graph (a sum of all selected servers, in a single graph) shouldn't include the smoke.


Regex C#. Match specific substring and return that substring only

Question: I've been pulling my hair out over this, and I think I am quite close to actually getting it to work but I just can't seem to.
I've been attempting to pull out a specific substring from a string using Regex. This substring must match a certain set of strings/digits. Then after this, it should be returned to another function which will pull out the number only.
Here's some examples of strings that are present
"(DEV #198) I am a dev testing 23 different things."
"(dev #9540) I am a dev testing different other things."
"(FQ #1140) I am a dev testing different things."
"(fq #910) I am a dev testing different other things."

In the end I would like to have 198, 9540, 1140 or 910 as the final variable depending on the input.
Here is my Regex so far. I think it's close, but I need some help. (note the double backslashes for C#).
^(?=.*?\\b(dev|DEV|fq|FQ)\\b)(?=.*?\\b[0-9]{3,4}\\b).*$

Here is the fragment of code I'm using also.
string caseNumber = cpTicket.Desc;
string regexPattern = "^(?=.*?\\b(dev|DEV|fq|FQ)\\b)(?=.*?\\b[0-9]{3,4}\\b).*$";
caseNumber = Regex.Match(caseNumber, regexPattern).ToString();

That's as far as I have got with this. If you can help, I will be so grateful :D
Answer: Try the following expression:
(?<=(?:dev|fq) #)\d+

(?<=): This is a look behind to make sure the digits are preceded with what is inside the look behind.
(?:dev|fq): This matches either dev or fq.
#: Matches a space which is followed by a hash #.
\d+: Matches one or more digits.

Turn case insensitivity mode on so dev and fq could match in all cases.
You can turn case insensitivity from within the regular expression itself like this:
(?i)(?<=(?:dev|fq) #)\d+

In C#:
var input = "(DEV #198) I am a dev testing 23 different things.";
var matches = Regex.Matches(input, @"(?i)(?<=(?:dev|fq) #)\d+");

Notice how you can use the @ before the string to create what is called a verbatim string  so you don't have to double escape everything.
Comment: Ah awesome, this worked great! Thankyou so much, I see that I was quite far off in my own implementation!
Comment: Instead of using `(?i)`, you can use `(?i:dev|fq)`
Comment: @PierlucSS Thank you for your feedback, I didn't know you could nest the flag like that inside the non-matching group, I wish I could give you a vote up for this as you deserve it.
Answer: I think you pattern can simply be:
"\(.*?\#(\d*)\)"

This will match the group in brackets and return the number.
 var m = Regex.Match(input, @"\(.*?\#(\d*)\)");
 if (m.Groups.Count > 0)
 {
     string matchedNumber = m.Groups[1].Value;
 }

Comment: Ah yeah this works, and it returns the both the DEV # and the number by itself. Both answers were great but I can only mark one as the correct one :( Otherwise I would mark both of you.


C# By Pressing button do in background

Question: Can someone explain me how can i do async tasks from this code?
Currently code does work and do the job but i have tried to make it async? So app will not get frozen while its executing but no success.
public WebpageLocalScanner()
    {

        InitializeComponent();
        InitializeListView();

    }

internal string GetType(string ip, int port)
    {
        try
        {
            if (port == 1234 || port == 4321)
            {
                string urlAddress = string.Format("http://{0}", ip);
                string text = this.GetHttpData(ip, 80, urlAddress, 5120).ToUpper();
                if (text.Contains(""))
                {
                    return "Webpage is here";
                }
            }
        }
        catch (Exception)
        {
        }
        return string.Empty;
    }

public void AddItem() {

            listView1.Items.Clear();

            int froms192 = Convert.ToInt32(tB1.Text);
            int froms168 = Convert.ToInt32(tB2.Text);
            int froms1a = Convert.ToInt32(tB3.Text);
            int froms1b = Convert.ToInt32(tB4.Text);
            int fromports = Convert.ToInt32(tBp1.Text);
            int toports = Convert.ToInt32(tBp2.Text);

            string FromIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;
            int FromPort = fromports;
            int ToPort = toports;

            int tos192 = Convert.ToInt32(tB5.Text);
            int tos168 = Convert.ToInt32(tB6.Text);
            int tos1a = Convert.ToInt32(tB7.Text);
            int tos1b = Convert.ToInt32(tB8.Text);

            string ToIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;

            if (froms1a < tos1a || froms1b < tos1b)
            {

                for (int i = froms1b; i <= tos1b; i++)
                {

                    for (int u = froms1a; u <= tos1a; u++)
                    {
                        for (int p = fromports; p <= toports; p++)
                        {
                        string GenIP = froms192 + "." + froms168 + "." + u + "." + i;

                        string result = GetType(GenIP, p);
                        if (result != null) {
                            string[] row = { Convert.ToString(GenIP), Convert.ToString(fromports), Convert.ToString(result), Convert.ToString(tos1a), Convert.ToString(tos1a) };
                            var listViewItem = new ListViewItem(row);
                            listView1.Items.Add(listViewItem);
                        };

                        }
                    }
                }
            }

    }

private void InitializeListView()
    {
        // Set the view to show details.
        listView1.View = View.Details;
        // Allow the user to edit item text.
        listView1.LabelEdit = true;
        // Allow the user to rearrange columns.
        listView1.AllowColumnReorder = true;
        // Display check boxes.
        // listView1.CheckBoxes = true;
        // Select the item and subitems when selection is made.
        listView1.FullRowSelect = true;
        // Display grid lines.
        listView1.GridLines = true;
        // Sort the items in the list in ascending order.
        listView1.Sorting = SortOrder.Ascending;
        // Attach Subitems to the ListView
        listView1.Columns.Add("IP", 100, HorizontalAlignment.Left);
        listView1.Columns.Add("PORT", 50, HorizontalAlignment.Left);
        listView1.Columns.Add("SERVER", 100, HorizontalAlignment.Left);
        listView1.Columns.Add("TYPE", 100, HorizontalAlignment.Left);
        listView1.Columns.Add("COMMENT", 100, HorizontalAlignment.Left);
    }

private void button1_Click(object sender, EventArgs e)
    {
        AddItem();
    }

What im really struggle is understand how can i convert each function to return and can be used in background if its called.
Whatever i try its getting missing something.
Can you able to make it more clear for me?
What this does is simply scan local network to find current ip of webserver on other pc.
But 255 ips to do it takes a while and app just hungs and have to wait till its finished?
ANSWER CODE APPLIED:
public async void AddItem()
    {

        //listView1.Items.Clear();

        int froms192 = Convert.ToInt32(tB1.Text);
        int froms168 = Convert.ToInt32(tB2.Text);
        int froms1a = Convert.ToInt32(tB3.Text);
        int froms1b = Convert.ToInt32(tB4.Text);
        int fromports = Convert.ToInt32(tBp1.Text);
        int toports = Convert.ToInt32(tBp2.Text);

        string FromIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;
        int FromPort = fromports;
        int ToPort = toports;

        int tos192 = Convert.ToInt32(tB5.Text);
        int tos168 = Convert.ToInt32(tB6.Text);
        int tos1a = Convert.ToInt32(tB7.Text);
        int tos1b = Convert.ToInt32(tB8.Text);

        string ToIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;

        if (froms1a < tos1a || froms1b < tos1b)
        {
            //var listViewItems = new List<ListViewItem>();
            await Task.Run(() =>
            {
                for (int i = froms1b; i <= tos1b; i++)
                {
                    List<string[]> rows = new List<string[]>();
                    for (int u = froms1a; u <= tos1a; u++)
                    {
                        for (int p = fromports; p <= toports; p++)
                        {
                            string GenIP = froms192 + "." + froms168 + "." + u + "." + i;

                            string result = GetProxyType(GenIP, p);
                            if (result != "")
                            {
                                string[] row = { Convert.ToString(GenIP), Convert.ToString(fromports), Convert.ToString(result), Convert.ToString(tos1a), Convert.ToString(tos1a) };
                                var listViewItem = new ListViewItem(row);

                                if (listView1.InvokeRequired)
                                {
                                    listView1.Invoke(new MethodInvoker(delegate
                                    {

                                        listView1.Items.Add(listViewItem);

                                        //row.Checked = true;

                                    }));
                                }
                                else
                                {
                                    listView1.Items.Add(listViewItem);
                                    listViewItem.Checked = true;
                                }
                                //string[] row = { Convert.ToString(GenIP), Convert.ToString(fromports), Convert.ToString(result), Convert.ToString(tos1a), Convert.ToString(tos1a) };
                                //listViewItems.Add(row);
                                //listView1.Items.AddRange(rows.Select(a => new ListViewItem(a)).ToArray());

                            };
                        }
                    }
                }

            });

        }

    }

    private async void button1_Click(object sender, EventArgs e)
    {

        AddItem();

    }

Comment: Step 1: remove `catch (Exception) { }` from all code you write ever. Step 2: read [Asyncronous programming](https://learn.microsoft.com/en-us/dotnet/csharp/async).
Answer: You use the async keyword on any method that will need to run asynchronously. You use await on the code that you want to run in the background. Await yields control back to the UI until that code finishes. You only use async on methods that have an await, and you only use await on code that returns a Task. If you have code that you need to run in the background and it doesn't return a Task, you can wrap it in a Task.Run.
I think this will work, but I haven't tested it.
public WebpageLocalScanner()
{

    InitializeComponent();
    InitializeListView();

}

internal string GetType(string ip, int port)
{
    try
    {
        if (port == 1234 || port == 4321)
        {
            string urlAddress = string.Format("http://{0}", ip);
            string text = this.GetHttpData(ip, 80, urlAddress, 5120).ToUpper();
            if (text.Contains(""))
            {
                return "Webpage is here";
            }
        }
    }
    catch (Exception)
    {
    }
    return string.Empty;
}

public async void AddItem() {

        listView1.Items.Clear();

        int froms192 = Convert.ToInt32(tB1.Text);
        int froms168 = Convert.ToInt32(tB2.Text);
        int froms1a = Convert.ToInt32(tB3.Text);
        int froms1b = Convert.ToInt32(tB4.Text);
        int fromports = Convert.ToInt32(tBp1.Text);
        int toports = Convert.ToInt32(tBp2.Text);

        string FromIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;
        int FromPort = fromports;
        int ToPort = toports;

        int tos192 = Convert.ToInt32(tB5.Text);
        int tos168 = Convert.ToInt32(tB6.Text);
        int tos1a = Convert.ToInt32(tB7.Text);
        int tos1b = Convert.ToInt32(tB8.Text);

        string ToIP = froms192 + "." + froms168 + "." + froms1a + "." + froms1b;

        if (froms1a < tos1a || froms1b < tos1b)
        {
            var rows = new List<string[]>();
            await Task.Run(() => {
                for (int i = froms1b; i <= tos1b; i++)
                {
                    for (int u = froms1a; u <= tos1a; u++)
                    {
                        for (int p = fromports; p <= toports; p++)
                        {
                            string GenIP = froms192 + "." + froms168 + "." + u + "." + i;

                            string result = GetType(GenIP, p);
                            if (result != null) {
                                string[] row = { Convert.ToString(GenIP), Convert.ToString(fromports), Convert.ToString(result), Convert.ToString(tos1a), Convert.ToString(tos1a) };
                                rows.add(row);

                            };
                        }
                    }
                }
            });
            listView1.Items.AddRange(rows.Select(a => new ListViewItem(a)).ToArray());
        }

}

private void InitializeListView()
{
    // Set the view to show details.
    listView1.View = View.Details;
    // Allow the user to edit item text.
    listView1.LabelEdit = true;
    // Allow the user to rearrange columns.
    listView1.AllowColumnReorder = true;
    // Display check boxes.
    // listView1.CheckBoxes = true;
    // Select the item and subitems when selection is made.
    listView1.FullRowSelect = true;
    // Display grid lines.
    listView1.GridLines = true;
    // Sort the items in the list in ascending order.
    listView1.Sorting = SortOrder.Ascending;
    // Attach Subitems to the ListView
    listView1.Columns.Add("IP", 100, HorizontalAlignment.Left);
    listView1.Columns.Add("PORT", 50, HorizontalAlignment.Left);
    listView1.Columns.Add("SERVER", 100, HorizontalAlignment.Left);
    listView1.Columns.Add("TYPE", 100, HorizontalAlignment.Left);
    listView1.Columns.Add("COMMENT", 100, HorizontalAlignment.Left);
}

private async void button1_Click(object sender, EventArgs e)
{
    AddItem();
}

Comment: Yes! Thank you, i  have applied some of the idea of your code, finally have been able to fix rest of the errors. And now IT run on the background! - Will update my Question for answer! Thanks again.

C# By Pressing button do in background


Global sensitivity Morris method - choice of delta and normalisation of the elementary effects

Question: I have few questions regarding the Morris method (as decribed e.g. in Campolongo, Cariboni, Saltelli, Environmental Modelling & Software 22, 2007 or Wenthworth et al. J. Uncertainty Quantification 2016) a global sensitivity method. I describe it below in some details as it is not very widely known.
Method definition
It uses the notation of the elemenatry effects defined as follows
$$d_i(q) = \frac{f(q_1,\dots,q_{i-1},q_i+\Delta,q_{i+1},\dots,q_p)-f(q)}{\Delta} = \frac{f(q+e_i)-f(q)}{\Delta}$$
where $\Delta$ is the step size chosen from the set $\Delta \in \{ \frac1{l-1}, \dots, 1-\frac1{l-1} \}$. Note that it assumes parameters mapped to $[0, 1]^p$.
Constructed in this way, $d_i$ quantifies the approximate, large scale, local sensitivity of the model response relative to the ith parameter. The following settings are recommended: $l$ should be even and $\Delta = \frac{l}{2(l-1)}$ which should garantee equal probability sampling from the distribution.
$$d_i^k(q) = \frac{f(q^k+\Delta e_i)-f(q^k)}{\Delta}$$ is the elementary effect associated with $i$th parameter and kth sample. With $r$ sample points per parameter, the Morris indices for the parameter $q_i$ are
$$\mu_i^* = \frac1{r}\sum_{k=1}^{r} |d_i^k|, $$
$$\sigma_i^2 = \frac1{r-1} \sum_{k=1}^{r}(d_i^r - \mu)^2, \mbox{where } \mu = \frac1{r}\sum_{k=1}^{r} d_i^k.$$ The mean quantifies the individual effect of the input on output, whereas the variance incorporates variability due to parameter interactions. Ranking of the parameters is done using $\sqrt{\mu_i^{*2} + \sigma_i^2}$.
Screening algorithm (Wentworth et al. 2016)

Create a $(p+1)p$ matrix $A$ with ones in the lower triangle such that
$$A = \begin{bmatrix}
    0       & 0 & \dots & 0 \\
    1       & 0 & \dots & 0 \\
    \dots &  & \ddots &  \\
    1 & 1 & \dots & 1
\end{bmatrix}$$
Choose the step size $\Delta$ as above equal $\frac{l}{2(l-1)}$.
Select starting vector $q^* \in \mathbb{R}^{1\times p}$.
Construct a $p\times p$ diagonal matrix $D^*$, whose entries are randomly chosed from $\{ -1,1\}$.
Calculate the sampling matrix
$$ A_s = J_{p+1,1}q^* + \frac\Delta2 [(2A - J_{p+1,p})D^* + J_{p+1,p}]P^*,$$
where $J_{i,j}$ is a $i\times j$ matrix with all ones and $P^*$ is a permutation of the identity matrix.
For parameters defined not in unit hypercube, i.e. $q\in[l_i,u_i]$ for $i=1,\dots,p$, take $l=[l_1,l_2,\dots,l_p]$ and $u=[u_1,u_2,\dots,u_p]$. The sampling matrix is then scaled to match the range of parameters
$$ C=J_{p+1,1}l + A_s(D(u-l)), \;\;\;\;\;\; (*)$$
where $D(u−l)$ is a diagonal matrix with entries $u−l$.
Compute the elementary effects for $i=1,\dots,p.$ Let $C_k$ denote the $k$th row of $C$. Then
$$ d_i = \frac{f(C_m) - f(C_n)}{\Delta}, \;\;\;\;\;\; (**)$$
where $m$ and $n$ denote the indices such that $m$th row and $n$th row differ in the $i$th entry.
Repeat steps 1-7 for $r$ samples. The Morris statistics, $\mu_i^*$ and $\sigma_i^2$, are calculated as described in the Method section by taking the average of the local elementary effect.

Note 1 from the author: denominator of (**) in step 7 is $\Delta$ for all $q_i, i = 1,\dots, p$. The elementary effects must be computed using the scaled step size, even though model responses are computed at the parameter values, which are mapped using (*).
Note 2: Wentworth et al. and others suggest $l=20$ and $r=50$.
Discussion/Questions
I have trouble to see why $\Delta$ is choosen to be $\frac{l}{2(l-1)}$, which for $p=20$ is equal $10/19$. When selecting $q^*$ as in point 3 of the algorithm, the $q_i$ of interest has to be selected from the set $\{0,1/(l-1),2/(l-1),...,1-\Delta\}$ (according to original Morris 1991 paper, otherwise it might be that after adding delta its value is larger then 1.). I.e. $q_i$ will assume values from 0 to 9/19.
Question 1: Why not simply generate sequence between 0 and 1 with elements equidistantly spaced with step $\frac{1}{(l-1)}$? It would be analog to the above scenario.
Question 2: Would it make better sense to calculate, instead of an elemenatry effect, a local normalized sensitivity index similar to how it is done in the Matlab SimBiology toolbox, see the 'full' normalization case (of course with $\Delta$ instead of differentials $\partial x$ or $\partial k$ and without the time dependency):
https://uk.mathworks.com/help/simbio/ref/normalization.html
It would have the advantage that it is dimensionless compared to the elementary effects.
Answer: I'm "answering" this question because I stumbled upon it while looking for the same question.
The first question: why is $$\Delta = \frac{l}{2(l-1)}$$ (your $l$, usually $p$)? The idea is that $\Delta$ is the actual jump step when your inputs are in $[0, 1]$. However, it is easier to think of index-jumping in the array of possible inputs, where the jump is $l/2$, which is identical to the above definition of $\Delta$. When you jump half the array forward or backward (and the array has an even number of steps $l$) there are always exactly two pairs of indices that can be jumped to or from.
So in your example, if you number the indices starting with 0: $\{0, 1, 2, \dots , 19\}$. From 0 you always jump to 10, from 1 to 11, ... and the same is true for jumps back (from 10 to 0, from 11 to 1, ...). This ensures that (given a randomly chosen start point) each element of the input array is chosen with the same probability, therefore giving you uniform coverage of the input space.
There is a nice graphical explanation of this in Saltelli et al. (2008, p. 117ff).
I cannot answer question 2.
Saltelli et al (2008, p. 120) argue no, because in a model of $y = x_1 + x_2$ where $x_1 \in [0, 1]$ and $x_2 \in [0, 10]$ the second factor seems more important. However, if $\Delta$ is normalized (different for each $x_i$), both factors would be equally important. This points towards not scaling and seems sensible to me.
Monari and Strachan (2017) argue for scaling:

The sensitivity indexes employed in the Morris method can be dependent on the variation ranges applied. In partic ular, leaving the variations applied to each parameter with its own units can produce misleading results since the calculated elementary affects will have in turn different units, making it impossible to compare them. To avoid this issue model input samples have been scaled and centred so that
  each of them has mean equal to zero and standard deviation equal to one.

So do Sin and Gernaey (2009):

This refinement consists of scaling the elementary effects to obtain a non-dimensional measure. This is needed for two particular reasons: (1) to prevent any misleading conclusions about the importance of the factors in complicated models and (2) to reliably compare the results of the analysis on different model outputs. This necessity arises especially when a model contains outputs and factors with large differences in their values/units, for example one or more orders of magnitude.

This also sounds logical to me. So which is better, scaling or not scaling?
Note that scaling the input factors $q_i$ or not makes no difference, since they only appear as arguments to the output function $f$ and therefore have no influence on the actual elementary effects. No scaling means $\Delta = \frac{l}{2(l-1)}$, scaling means having $\Delta_i$ and using them depending on which $q_i$ is currently changed.
I have no idea.
Scaling $f$ (like Sin and Gernaey 2009) is an additional issue and in my opinion can only increase comparability if one is looking at multiple outputs $f$.

Saltelli, Andrea, Marco Ratto, Terry Andres, Francesca Campolongo, Jessica Cariboni, Debora Gatelli, Michaela Saisana, and Stefano Tarantola (2008); Global sensitivity analysis: The primer, John Wiley & Sons, doi:10.1002/9780470725184
Monari, F. and Strachan, P. (2017); Characterization of an airflow network model by sensitivity analysis: parameter screening, fixing, prioritizing and mapping; Journal of Building Performance Simulation 10, p. 17 - 36, doi: 10.1080/19401493.2015.1110621
Sin, Gürkan and Krist V. Gernaey (2009); Improving the Morris method for sensitivity analysis by scaling the elementary effects, Computer Aided Chemical Engineering 26, p. 925 - 930, doi: 10.1016/S1570-7946(09)70154-3


Two different editor in one content typ

Question: is there a way in drupal 8 to use two different editors (CKeditor with two different buttonpanels or two differently allowed html tags) in one content type?
I have created a content type of a text field (body) and with the module paragraph other text fields are created. the user should use the possibilities in the body field of pictures and tables but in the text fields of paragraph the user should not be allowed to do so.
I have now created two different editors but the user can always switch between the editors. How can I determine that only one editor can be used in the body field and only the other one in the remaining text fields?
many thanks for your help!
s-webz
Comment: Use Better Formats module to limit format options regardless of the current user permission.
Comment: this is not a option becouse it is a production sites :-( but big thx
Comment: I don't know what that means. I use it all the time.
Answer: You probably need the module https://www.drupal.org/project/allowed_formats.

Limit which text formats are available for each field instance.
Comment: Nice! The module does exactly what I was looking for! big thank you.

Two different editor in one content typ


How to tell a field is nvarchar in CakePHP

Question: I want to make sure that the strings I save to the database are properly formatted in UTF-8. I have converted some of the fields into nvarchar. To save the strings properly I need to prefix all strings with N. e.g. N'my string'.
However not all fields are necessarily nvarchar. In the DboSqlsrv class that I am using that extends DboSource, there is just the one string parameter that you can either specify as 'varchar' or 'nvarchar'.
Does anybody know if there is a 'cake' way to interrogate the database and check if a field is varchar or nvarchar?
Answer: this? http://book.cakephp.org/view/1066/_schema
Comment: thanks. That's pointed me in the right direction. I'm guessing for strings there is only the string and text types. I can use nvarchar for one and varchar for the other.


For Apache, what is the usage of var/www/usage?

Question: I am new to administrating Apache and I am trying to understand what the directory /var/www/usage is used for?
Answer: It seems to be the default output directory for the Webalizer log analysis application.
See this excerpt from Webalizer's changelog:

Sat Aug 02 2003 Joe Orton

support large (>2gb) log files on 32-bit platforms
move default output directory to /var/www/usage


How to install the latest version of OpenSSL on Ubuntu?

Question: I see that the latest security patches are not yet available from apt-get install openssl on Ubuntu 14.04. What steps do I need to take in order to install the latest OpenSSL without conflicting with my previous installation through apt-get?
Comment: When I run `openssl version -a` I see `OpenSSL 1.0.1f 6 Jan 2014` which makes me think I don't have the latest version.
Comment: What security patches do you mean? Are you aware that Ubuntu backports patches into older version? http://changelogs.ubuntu.com/changelogs/pool/main/o/openssl/openssl_1.0.1f-1ubuntu2.11/changelog
Comment: I'm referring to [this article](http://www.zdnet.com/article/high-severity-flaw-in-openssl-to-be-patched/) and this recommendation: "Upgrade your OpenSSL package to one of the following versions: 1.0.2a, 1.0.1m, 1.0.0r and 0.9.8zf"
Answer: You can check this page
https://launchpad.net/ubuntu/trusty/+source/openssl
It will show you the exact security updates that have been backported, even though the overall version date appears old.  If you have installed the latest openssl via apt-get upgrade, you are current (on security updates) as of 2015-03-19, which happens to be 2 days after the security flaw was posted on your link above.  You can drill down into the openssl page on ubuntu to see if this fix was included.
Comment: where at that link can you see which security updates have been backported?


Every finite Set as non-abelian Group

Question: For what values of n, we can find a non abelian group.
The facts I have proved till now:
1. For n prime there exist only one group upto isomorphism which is cyclic hence abelian
2. For n = 4, there exist only two groups(upto isomorphism) and these are abelian
Comment: Your title wants rings but your question and tags are about groups.
Comment: @MarianoSuárez-Alvarez thanks actually I was thinking about cases and for non-abelian rings, I found there is a paper by D.B. Erickson(But sadly I have no access to it) and for groups I have no references
Answer: We can continue your list as follows:
3.) For every prime $p$ there exists a non-abelian group of order $p^3$, see here.
4.) For every even $n>2$ there exists a non-abelian group of order $n$, a dihedral group.
5.) For every odd $n$ the situation is as follows: see here.

Every finite Set as non-abelian Group


FloatingActionButton ,como aparecer em todas as telas?

Question: Como faço com que esse FloatingActionButton (Botão do email) apareça em todas as minhas telas , sem precisar ter que ficar colocando uma em cada tela?
Comment: Se são `activities` diferentes, tu precisa colocar ele em todas elas.
Comment: se voce criou ele a partir do menu normal de criar app do android studio, esse floatactinobutton é parte de uma activity que usa fragments, dai basta que voce implement varios fragments usando sempre a activity main e trabalha nesses fragments para serem exibido nela, fica mais facil de lidar, assim
Answer: O FloatingActionButton esta inserido na Activity criada. Para ter esse efeito que você deseja o aconselhável você trabalhar trocando o miolo da tela através de Fragments. Com isso o botão sempre será visível para todas as telas pois estará presente na activity enquanto os fragments são trocados. No caso que você precise criar outra Activity é necessário inserir um novo FloatingActionButton.
Exemplo de como trabalhar com fragments:
https://github.com/codepath/android_guides/wiki/Fragment-Navigation-Drawer


What is the "total count" metric in Android Studio's Memory Profiler?

Question: I'm unable to find a description of this metric anywhere in the Android developer documentation. Here is a link to what I've most recently looked at: https://developer.android.com/studio/profile/memory-profiler
Here's what I think it is: the number of objects in the heap that have not been deallocated.
Please, if possible, provide a credible resource that supports your reasoning (e.g. a Google I/0 talk on Youtube with a minute-mark or some Android documentation).
EDIT: Here is a screenshot that includes the metric.
Comment: Could you supplement the question with a screenshot?
Comment: Screenshot added as requested.
Answer: Total Count column
Total Count is defined as the total object count (see Android Studio source), specifically:
  new AttributeColumn<>(
    "Total Count",
    () -> new SimpleColumnRenderer<ClassifierSet>(
      value -> Integer.toString(value.getAdapter().getTotalObjectCount()),
      value -> null,
      SwingConstants.RIGHT),

This getTotalObjectCount() is defined as:
  public int getTotalObjectCount() {
    return mySnapshotObjectCount + myDeltaAllocations - myDeltaDeallocations;
  }

Incrementing methods
The mySnapshotObjectCount value is incremented inside addSnapshotInstanceObject, which has the helpful comment:

Add an instance to the baseline snapshot and update the accounting of
  the "total" values.

The myDeltaAllocations and myDeltaDeallocations values are incremented inside addDeltaInstanceInformation:
if (isAllocation) {
  myDeltaAllocations++;
}
else {
  myDeltaDeallocations++;
}

This is called inside partition, which contains the helpful comment:

Partitions InstanceObjects in snapshotInstances and myDeltaInstances according to the current ClassifierSet strategy. This will consume the instances from the input.

This snapshotInstance is the same one used to increment mySnapshotInstanceObjectCount, thus showing that all 3 values are very closely linked, are created when a partition (snapshot) is made, and all factor into the Total Count.

Final formula
So, the final answer is:
Total Count = Snapshot objects + New allocations - New deallocations

Snapshot objects = number of object instances allocated before the snapshot.
New allocations = number of allocations during snapshot.
New deallocations = number of deallocations during snapshot.

This definition of the equation matches what Axifive stated in another answer, and the linked video.
Comment: Fantastic work! Could you also provide explanations backed up by source code for `Snapshot objects`, `New allocations`, and `New deallocations` in your answer? I trust that you've done your research but I would like to leave my bountied faith with a full, pedantically-written proof when it comes to a source-code backed answer like yours, and I don't trust myself to fully comprehend the source code on my own.
Comment: @GrantPark Sure. I've added info on how all 3 are incremented, as well as the connection between them. If I go further I fear I'll just be explaining the code line by line, but let me know any other areas that need improving! Thanks for the advice.
Comment: So seeing where these methods are called as well as the relevant comments are helpful, but I would like to know how these items are being calculated e.g. does the `snapshot objects` count incorporate the deallocation count of the object before the snapshot? That said, I sincerely appreciate your time in digging through the profiler source code -- it makes for a strong answer considering that there is no proper documentation.
Comment: As far as I can tell, it's just the number of objects (so allocations / deallocations aren't included), but not confident enough on that to include in the answer. I'll have a further look when I get back from work!
Answer:
Here's what I think it is: the number of objects in the heap that have
  not been deallocated.

You are right with your thinking but I cannot serve you with a public thread for that.
Answer: Yes this is the total number of instance, that has allocated before the selected period + memory allocation for the selected period (or as you says: number of objects(instances) in the heap that haven't been deallocated for the selected period)
You can see this here
On the Instance View, it can be seen that three int arrays were allocated at 1m, but not deallocated (for the selected period).


Or-operator in matching sub patterns

Question: The Rust documentation says not much about the |-operator for pattern matching. It only gives one example:
let x = 1;

match x {
    1 | 2 => println!("one or two"),
    3 => println!("three"),
    _ => println!("anything"),
}

Contrary to the answer of this question, I noticed that the following compiles:
struct S(E, usize);

#[derive(Copy, Clone)]
enum E {
    P(u8), Q(u8)
}

fn main() {
    let x = S(E::P(1), 10);
    if let S(E::P(..) | E::Q(..), _) = x {

    }

    let y = E::P(2);
    match (y, y) {
        (E::Q(..), E::P(..) | E::Q(..)) => {

        }
        _ => {}
    }
}

In that particular question, integers were matched, not values of enum type. Integers implement the std::ops::BitOr trait, so there would be a conflict there for sub patterns.
My questions are:

Is this a feature? Why does it compile? Why does it seem to work?
What are the limitations of this feature? (e.g. type must not implement BitOr or similar)
What is the feature called? What is the AST node used to implement the feature called? Even the name of the type of the AST node in the compiler implementation would be a better name to use in discussion than calling it the "|-operator", which is very vague.
Comment: I've added an answer to the linked Q&A to address the discrepancy with the current behavior.
Comment: "Integers implement the std::ops::BitOr trait, so there would be a conflict there for sub patterns." There's no conflict. Patterns are not expressions and a match arm is comprised by a pattern, so `|` is always pattern alternation. See e.g., https://play.rust-lang.org/?version=stable&mode=debug&edition=2021&gist=1b8e31eb086e8c91195f40052107d954
Answer:
Is this a feature? Why does it compile? Why does it seem to work?

Before Rust 1.53, |s were only allowed at the top-level of a match arm, but since then they were expanded to be allowed in nested patterns. So what you see is working as intended; just the linked Q&A was out-dated.

What are the limitations of this feature? (e.g. type must not implement BitOr or similar)

On the contrary, this does not use the BitOr operator and thus will work on any type that can be matched to multiple values. Remember pattern matching employs structural equality, not value equality. And because of that, the pattern 1 | 2 will match either 1 or 2, while if it used BitOr then it'd only match 3.
Feature-wise, this is fairly unlimited:

Or-patterns are patterns that match on one of two or more sub-patterns (e.g. A | B | C). They can nest arbitrarily. Syntactically, or-patterns are allowed in any of the places where other patterns are allowed, with the exceptions of let-bindings and function and closure arguments.  - Rust Reference

What is the feature called? What is the AST node used to implement the feature called? Even the name of the type of the AST node in the compiler implementation would be a better name to use in discussion than calling it the "|-operator", which is very vague.

The original RFC 2535 was simply called "or-patterns" and that is reflected in the reference documentation. Not sure about the name of the AST node, but the Pattern grammar in the Rust Reference simply has the | chain as directly part of the Pattern production and other types of patterns are deferred to PatternNoTopAlt or PatternWithoutRange.
Comment: Small nitpick: `1 | 2` is `3`, not `0`.
Comment: @Jmb woops! Was thinking `&`

Or-operator in matching sub patterns


The purpose of scaling the normal variance in NIG-distribution

Question: The Normal-Inverse-Gamma distribution is often written as
$N(\phi | \mu, \sigma^2 \Sigma) IG(\sigma^2 | \alpha, \beta),$
and used as a conjugate prior for a linear model given observations
$y_t \sim N(y_t | x_t \phi, \sigma^2).$
However, the model would still be conjugate even if the prior would be written as
$N(\phi | \mu, \Sigma) IG(\sigma^2 | \alpha, \beta),$
which begs the question of why is the variance of the Normal part of the prior scaled by $\sigma^2$ in the first place, as this makes some derivations longer and more problematic. Most importantly, is there some clear benefit regarding the quality of the inferences?
Answer: The prior below is not conjugate
$$ N(\phi|\mu,\Sigma)IG(\sigma^2|\alpha,\beta) $$
since the posterior does not have the form
$$ N(\phi|\mu',\Sigma')IG(\sigma^2|\alpha',\beta'). $$
So the answer to the question "why is the variance of the Normal part of the prior scaled by $\sigma^2$?" is the prior
$$ N(\phi|\mu,\sigma^2\Sigma)IG(\sigma^2|\alpha,\beta) $$
is used because it is conjugate, i.e. the posterior can be put in the form
$$ N(\phi|\mu',\sigma^2\Sigma')IG(\sigma^2|\alpha',\beta'). $$
The benefit of using this prior is that it is conjugate.
Comment: At present, this is more of a comment than an answer. Can you expand it? Why wouldn't it be conjugate?
Comment: I guess that if you want to keep the variance of the posterior Normal part clearly as a product of observation and model variances, it makes sense to use the first formulation. However, if you mostly care about the posterior inferences do you think that there is any essential difference?


Erro de Login num Sistema Android (MakeToast)

Question: Estou a criar um sistema de Login com json no android mas quando eu vou apresentar uma mensagem pelo maketoast ele da um erro:

Process: imm.pt.videoclube, PID: 11853
                                                                     java.lang.RuntimeException: Can't create handler inside thread that
  has not called Looper.prepare()
                                                                         at android.os.Handler.(Handler.java:200)
                                                                         at android.os.Handler.(Handler.java:114)
                                                                         at android.app.Dialog.(Dialog.java:152)
                                                                         at android.app.Dialog.(Dialog.java:202)
                                                                         at
  android.support.v7.app.AppCompatDialog.(AppCompatDialog.java:46)
                                                                         at android.support.v7.app.AlertDialog.(AlertDialog.java:97)
                                                                         at
  android.support.v7.app.AlertDialog$Builder.create(AlertDialog.java:932)
                                                                         at imm.pt.videoclube.VideoClube.showMessage(VideoClube.java:66)
                                                                         at imm.pt.videoclube.VideoClube.VerifyAnswer(VideoClube.java:49)
                                                                         at imm.pt.videoclube.VideoClube.access$000(VideoClube.java:17)
                                                                         at imm.pt.videoclube.VideoClube$1.run(VideoClube.java:43)

Codigo:
package imm.pt.videoclube;

import android.app.Application;
import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import org.json.JSONException;
import org.json.JSONObject;

public class VideoClube extends AppCompatActivity {
    Button btn;
    EditText usr,psw;

    public void entrar(View view){
        usr = (EditText) findViewById(R.id.usr);
        psw = (EditText) findViewById(R.id.psw);
        String json = generateJSON();
        callServer("veruser", json);

    }

    private String generateJSON(){
        JSONObject jo = new JSONObject();
        try{
            jo.put("user", usr.getText().toString());
            jo.put("pass", psw.getText().toString());
        }
        catch (JSONException e){e.printStackTrace();}
        return(jo.toString());
    }
    private void callServer(final String method, final String data){
        new Thread(){
            public void run(){
                String answer = HttpConnection.getSetDataWeb("http://192.168.1.71/video/app/process.php", method, data);
                VerifyAnswer(answer);
            }
        }.start();
    }
    private void VerifyAnswer(String answer){
        if(answer.equals("N")){
            showMessage("Dados Invalidos!");
        }else{
            showMessage("Bem-vindo!");
            Intent inicial = new Intent(VideoClube.this, VideoClubeStart.class);
            startActivity(inicial);
        }
    }
    private void showMessage(String msg) {
        Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_clube);

    }
}

Answer: Quando você está dentro de uma Thread diferente da UI Thread, você precisa invocar os elementos que irão trabalhar com a UI na UI Thread.
Nestes casos utilizamos o método runOnUiThread.
No seu caso, basta chamar o método VerifyAnswer dentro do runOnUiThread:
runOnUiThread(new Runnable() {
   @Override
   public void run() {
       VerifyAnswer(answer);
   }
});

Um exemplo completo utilizando o seu método callServer, ficaria assim:
private void callServer(final String method, final String data){
    new Thread(){
        public void run(){
            String answer = HttpConnection.getSetDataWeb("http://192.168.1.71/video/app/process.php", method, data);

            runOnUiThread(new Runnable() {
              @Override
              public void run() {
                 VerifyAnswer(answer);
              }
            });
        }
    }.start();
}

Comment: Obrigado pela ajuda!


What is the simple Linux utility that is like cat but works via TCP (to be used for port knocking)?

Question: For port knocking over at my old job, one of the SAs use to perform something like the following:
 echo 'blah' > tcpcat -a 192.168.3.1 -p 2222 && ssh firstname.lastname@example.com

I cannot remember the command that I am referring to as tcpcat. Does anyone know?
Answer: ncat may be the tool you're looking for.
Comment: Looks like that is it! Thanks sir. Have to wait 12 minutes to award you the answer.
Answer: It may be called netcat, Lowercase nc is what the command actually is.


Como manipular um Objecto Json antes de retornar na API

Question: Olá
estou com este método no meu controller:
@GetMapping(value="/{id}/perfil", produces = MediaType.APPLICATION_JSON_VALUE)
public String carregarPerfilUsuario(@PathVariable("id") Long id, HttpServletResponse response) throws IOException {

    obj.put("usuario", ur.findWhereId(id));
    obj.put("postagem", pr.findAllWhereUserId(id));

    return gson.toJson(obj);

}

estou usando gson para transformar um objeto em json e JsonOBJECT para criar um obj que será retornado no final:
private static final Gson gson = new Gson();
private static final JSONObject obj = new JSONObject();

porem não sei porque ao converter meus dados ele insere atributos indesejados na minha api:

Map e MyArrayList, eu queria que não vinhe-se esses atributos quando eu convertesse, como eu consigo?
O resultado que busco, é semelhante a imagem, apenas gostaria que não tivesse estes atributos que comentei em negrito na pergunta.
Comment: Veja se utilizar o JsonObject do próprio GSON, em vez do JSONObject, resolve seu problema.
Comment: Está usando a classe certa (`JsonObject`)? Tentei reproduzir aqui mas não encontrei o método `put` nessa classe :(
Answer: Olá,
Os métodos que você está utilizando sugerem que você tem um Map (método put) e um ArrayList (método findAll), daí seu map e seu myArrayList.
O correto a se fazer é ter um POJO que represente o objeto a ser retornado pela sua API, e populá-lo com os dados de usuário e postagem.
Por exemplo:
public class PostagemDTO {

   private Usuario usuario;
   private List<Postagem> postagens;

   // getters e setters

}

Assim sua API retornará o resultado desejado.
Espero que ajude!
Comment: Oi Tomaz! Bem-vindo ao StackOverflow em Português. Concordo com o seu ponto de vista em relação a construir uma classe para servir de retorno para o método, ao invés de String, mas essa não foi a pergunta dele.
Ele questiona o funcionamento do GSON e suas classes.
Novamente, concordo contigo sobre a implementação de um modo geral. Inclusive, você pode usar isso como complemento a uma resposta que responda exatamente o perguntado! :)
Comment: Olá, acho que não fui claro então... O resultado que ele está buscando não precisa das classes internas do GSON, basta criar e popular o POJO conforme eu mostrei, e usar o método .toJson Mas claro que o Spring faz isso sozinho se ele retornar o POJO direto no controle sim. Valeu!


Postfix: dynamically rewrite server name depended on senders domain

Question: Im setting up postfix SMTP relay, that will be placed right after Exchange server.
Details:
1) postfix server name mail.server.com
2) we have several domains: a-domain.com, b-domain.com and etc..
I need to rewrite somehow emails headers. So recipient will not receive email like:
Received: from mail.server.com ([XX.XX.XX.X])
But will receive it from mail.a-domain.com ([XX.XX.XX.X]) if sender is firstname.lastname@example.com
OR
from mail.b-domain.com ([XX.XX.XX.X]) if sender is email@example.com
is this possible anyhow?
Answer: Postfix does not support directly this feature, but you can fiddle with transport maps in order to achieve your goal.
You can add many transports in master.cf, each for every domain, with a -o directive that adds a remap rule
In the transport file you set up the transport rule to use the transports specified in master.cf accordinf to the domain name
This blog post contains some examples and some links.
Comment: Thank you. Seems this is what i need exactly. I'll just create bunch of email gateways (for each domain) and strip the headers
Comment: finally I found this link http://tekman.livejournal.com/83609.html `sender_dependent_relayhost_maps = hash:/etc/postfix/sender_dependent_relayhost` works for me (as on my testing)


How to submit data from new page to older page

Question: I got a Button on HTML form (let's call it Form_A) which when clicked, opens a new window (let's call it Form_B).
When user fill in some information in Form_B form and hit submit (or just a button), I need to send some processed information back to 'Form_A' and close 'Form_B.'
How can I accomplish it?
Comment: by calling a function on `window.opener` and pass the data as an argument
Comment: Why do you need to open a new window? You can have a `div` with `display:none` css and on clicking the button, you can make it visible (api.jquery.com/show). Then on clicking another button related to the div or submitting the form( keep the div in  form B ) you can get the info from here to form B. use  api.jquery.com/submit to submit form without opening another window.
Comment: @IstiaqueAhmed I can't explain the whole business requirement over here and I guess, neither would you be interested... Let's just say, I need it, and I found the solution as well... Check my comments below
Comment: @adeneo thanks, you answer directed me to right direction
Answer: This is best illustrated with an example.  In the code of Form_A:

 <button onclick="window.open('form_b.html'); return false">Open Form B</button>

function receive_data (value)
{
    $("#target").text(value);
}

In the code of Form_B:
<input type="button" onclick="window.opener.receive_data('hello'); window.close();">

Comment: Works fine on IE, but gives security exception on Chrome. Do you think, it can be because I am running it locally. Finally, these two files will be hosted across different sub-domain of a website.
Comment: Dunn know why it was giving error locally, when I deployed it (after fixing the sub-domain issue), it was working fine for all browsers. Appending code in my Question. Thanks for snippet.
Comment: Chrome applies stricter security standards to javascript running from local files than ones downloaded from a web server.  It's perverse, but true.
Comment: SOLUTION:
===========
a.html
=======

 Open Form B

b.html
=======

This helped - http://stackoverflow.com/questions/5183684/cross-domain-javascript-code-with-sibling-sub-domains
Answer: You can do it using localStorage, like:

<input type="submit" onclick="processInfo();" />

and in your javascript code:
function processInfo(){
    //process your information then
    //let's day you have 2 variables as a result of your process
    var info1 = "My Information 1";
    var info2 = "My Information 2";
    localStorage.setItem("info1", info1);
    localStorage.setItem("info2", info2);
}

then in your code on the next page get your variables whenever you wanted like:
    function getInfo1(){
        return localStorage.getItem("info1");
    }

    function getInfo2(){
        return localStorage.getItem("info2");
    }

and the other solution for ancient browsers is using window.opener, you can use it in your close function like this:

<input type="button" onclick="closeWindow();" />

javascript code:
function closeWindow(){
    //process your information then
    //let's day you have 2 variables as a result of your process
    var info1 = "My Information 1";
    var info2 = "My Information 2";

    window.opener._info1 = info1;
    window.opener._info2 = info2;

    window.close();
}

then you can get them in the main page like:
    function getInfo1(){
        return window._info1;
    }

    function getInfo2(){
        return window._info2;
    }

BTW, we usually use _ when we want to simulate private variable, whereas they are not really private.
Comment: Thanks, but I can't use local storage in my scenario... ancient browsers
Comment: @user3133397: I changed my answer, now check it out.
Comment: thanks for your efforts but i had already started working on it when your answer arrived. Now, I got a fix which is addressing my whole problem. Thanks anyways.


Intuition for definition of Gromov norm?

Question: Let $X$ be a topological space. A $k$-chain in the singular chain complex of $X$ is a linear combination $c = \sum_1^k a_i\sigma_i$, where $\sigma_i$ are continuous maps from the standard $k$-simplex $\Delta^k$ to $X$. Thus we can natually define the norm of the cycle to be$$\|c\| = \sum_1^k |a_i|.$$
For $\alpha \in H_k(X, \mathbb{R})$, the Gromov norm of $\alpha$ is defined to be$$\|\alpha\| = \inf\{\|c\| : c \text{ is a singular cycle which represents }\alpha\}.$$What is the intuition behind the definition of the Gromov norm?
Comment: It measures how complicated the cycle is needed to represent the homology class.
Comment: You could do worse than study this for the fundamental classes of surfaces. I'd never encountered it, but I would guess the Gromov norm grows for fundamental classes of higher genus surfaces.
Comment: You probably get bounds in terms of the euler characteristic and such
Comment: For closed oriented surfaces $S$ of genus $p\ge 2$, $||S||=c(2p-2)$, where $c$ is some universal constant, I forgot which one. Did you try the book by Benedetti and Petronio? They discuss Gromov norm in great detail.
Comment: The original lecture notes of William Thurston, "The Geometry and Topology of 3-manifolds", contains the original description of the Gromov norm, and it remains very accessible. http://library.msri.org/books/gt3m/
Answer: Part of the intuition is that if you fix the dimension $n$ and consider the set of all closed hyperbolic $n$-manifolds $X$, the Gromov norm is proportional to the volume of $X$. The proportionality constant turns out to be equal to the maximal volume of an ideal simplex in $\mathbb{H}^n$ (or the supremal volume of a finite simplex). This tells us, intuitively, that the way to acheive the infimum in the definition of $||c||$ is to choose a chain whose singular simplices lift to the universal cover $\mathbb{H}^n$ so as to be close to ideal simplices (when lifted to the universal cover).