text:
Q: Mustache/handlebars templating: figure out context data structure from template html In mustache/handlerbars or any templating system in js,
are there any tools to gather all the variables that a template refers to?
for example, given input
templateHTML:

  {#item}}

{{title}}

    {{text}}
  {{/item}}

would return
{
  divclass: "",
  item: {
    title: "",
    text: ""
  }
}

when used like MyTemplateTool.getTemplateData(templateHTML)
I tried googling around and checking out handlebars docs but could not find anything suitable

A: I believe it's just .. See the related docs on paths. Example:
{{#srcs}}

{{/srcs}}

A: I had the same in mind and I thought it was worth while writing something so here you go:
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class MustacheSchemaBuilder
{
    static String javaIdentifierRegExp = "[a-zA-Z_$0-9]+";
    static String tab = "    ";
    static Format format = Format.java;

    enum Format {
        json,
        java,
        ;
    }

    enum TagType {
        variable("\\{\\{\\s*" + javaIdentifierRegExp + "\\s*\\}\\}"),
        escapedVariable("\\{\\{\\{\\s*" + javaIdentifierRegExp + "\\s*\\}\\}\\}"),
        sectionStart("\\{\\{#\\s*" + javaIdentifierRegExp + "\\s*\\}\\}"),
        invertedSectionStart("\\{\\{\\^\\s*" + javaIdentifierRegExp + "\\s*\\}\\}"),
        sectionEnd("\\{\\{/\\s*" + javaIdentifierRegExp + "\\s*\\}\\}"),
        //partial("\\{\\{>\\s*" + javaIdentifierRegExp + "\\s*\\}\\}"),
        // no support for set delimiters or partials
        ;

        Pattern pat;
        private TagType(String aRegExp) {
            pat = Pattern.compile(aRegExp);
        }

        public Pattern getPattern() { return pat; };
    }

    class Tag{
        public TagType type;
        public String identifier;
        Tag(TagType aType, String aIdentifier) { type = aType; identifier = aIdentifier;}

        public String toString() { return type.name() + " : " + identifier; }

        @Override
        public boolean equals(Object aOther) {
            if(!(aOther instanceof Tag)) return false;
            Tag ot = (Tag) aOther;
            return ot.type.equals(this.type) && ot.identifier.equals(this.identifier);
        }

        @Override
        public int hashCode() {return identifier.hashCode();}
    }

    class Node {
        public Section parent;
        public Tag tag;
        Node(Section aParent, Tag aTag){parent = aParent; tag = aTag; if(parent != null) parent.children.put(tag, this);}

        @Override
        public int hashCode() {return tag.hashCode();}

        public int depth() {
            int depth = 0;
            Node currentNode = this;
            while(currentNode.parent != null) {
                depth++;
                currentNode = currentNode.parent;
            }
            return depth;
        }

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            for(int i = 0; i < this.depth(); i++) sb.append(tab);
            switch(format) {
            case java:
                sb.append("public Object ").append(tag.identifier).append(";\n");
                break;
            case json:
            default:
                sb.append(tag.identifier).append(": {},\n");
            }
            return sb.toString();
        }
    }

    class Section extends Node{
        public Map<Tag, Node> children = new LinkedHashMap();
        Section(Section aParent, Tag aTag) { super(aParent, aTag); };

        @Override
        public String toString() {
            StringBuilder sb = new StringBuilder();
            for(int i = 0; i < this.depth(); i++) sb.append(tab);
            switch(format) {
            case java:
                sb.append("public Object ").append(tag.identifier).append(" = new Object() {\n");
                for(Node child : this.children.values()) sb.append(child);
                for(int i = 0; i < this.depth(); i++) sb.append(tab);
                sb.append("};\n");
                break;
            case json:
            default:
                sb.append(tag.identifier).append(": {\n");
                for(Node child : this.children.values()) sb.append(child);
                for(int i = 0; i < this.depth(); i++) sb.append(tab);
                sb.append("},\n");
            }
            return sb.toString();
        }
    }

    class MustacheSchemaBuildException extends Exception {
        private static final long serialVersionUID = 1L;
        MustacheSchemaBuildException(String aMessage) {super(aMessage);}
    }

    Section rootSection;

    public MustacheSchemaBuilder(String aContents) throws Exception
    {
        TreeMap<Integer, Tag> tagMap = new TreeMap();
        for(TagType type : TagType.values()) {
            populateMap(tagMap, type, aContents);
        }
        System.out.println(tagMap);

        rootSection = new Section(null, new Tag(TagType.sectionStart, "$root$"));
        Section currentSection = rootSection;

        for(Tag tag : tagMap.values()) {
            if(currentSection.tag.type == TagType.invertedSectionStart) {
                if(tag.type == TagType.sectionEnd) {
                    if(!tag.identifier.equals(currentSection.tag.identifier))
                        throw new MustacheSchemaBuildException("The end tag: " + tag.identifier + " doesn't match the expected start tag: " + currentSection.tag.identifier + "\n\n" + rootSection);
                    currentSection = currentSection.parent;
                }
                continue;
            }
            switch(tag.type)
            {
            case variable:
                if(!currentSection.children.containsKey(tag))
                    new Node(currentSection, tag);
                break;
            case sectionStart:
                Tag invertedSectionStartTag = new Tag(TagType.invertedSectionStart, tag.identifier);
                if(!(currentSection.children.containsKey(tag) || currentSection.children.containsKey(invertedSectionStartTag)))
                    new Section(currentSection, tag);
                currentSection = (Section)currentSection.children.get(tag);
                break;
            case invertedSectionStart:
                Tag sectionStartTag = new Tag(TagType.sectionStart, tag.identifier);
                if(!(currentSection.children.containsKey(tag) || currentSection.children.containsKey(sectionStartTag)))
                    new Section(currentSection, tag);
                currentSection = (Section)currentSection.children.get(sectionStartTag);
                break;
            case sectionEnd:
                if(!tag.identifier.equals(currentSection.tag.identifier))
                    throw new MustacheSchemaBuildException("The end tag: " + tag.identifier + " doesn't match the expected start tag: " + currentSection.tag.identifier + "\n\n" + rootSection);
                currentSection = currentSection.parent;
                break;
            default:
            }
        }
    }

    public void build() {
        System.out.println(rootSection);
    }

    public static void main(String[] args) throws Exception
    {
        String contents;
        try {
            contents = readFile(args[0], Charset.defaultCharset());

        }catch(Exception e)
        {
            System.out.println("Unable to open file!");
            throw e;
        }

        MustacheSchemaBuilder builder = new MustacheSchemaBuilder(contents);

        builder.build();
    }

    void populateMap(Map<Integer, Tag> map, TagType aType, String aContents) {
        Matcher m = aType.getPattern().matcher(aContents);
        while(m.find()) {
            int start = m.start() + 3;
            if(aType == TagType.variable) start = m.start() + 2;
            map.put(m.start(), new Tag(aType, aContents.substring(start, m.end() - 2).trim()));
        }
    }

    static String readFile(String path, Charset encoding) throws IOException
    {
      byte[] encoded = Files.readAllBytes(Paths.get(path));
      return new String(encoded, encoding);
    }
}

Give the template file path at the command line - you need java 7 or higher to open the file, or you can just rewrite the readFile - method. You can produce a json or java 'schema' by changing the format at the top of the class. The 'schema' gets written to stdout, you can copy it from there and paste it into where you need it. Hope this helps. Ah! This doesn't support partials or set delimiters, but if you get round to writing support ping it to me as I might want it :)


text:
Q: click and hold to scroll, touchstart, touchmove, touchend I have a scrollable div. I want people to be able to scroll the list through 'hold', and also select a button for click.
The problem is that when a button is held in order to scroll the div, it is triggering the click function.
I want that do not trigger when scrolling. I need some way to differentiate click of the hold function.
So I'm using:
$('.panel').bind("touchstart mousedown", function (e) {
console.log(e.type);
$(this).addClass('resize');

}).bind("touchmove mousemove", function (e) {
$(this).removeClass('resize');

}).bind("touchend mouseup", function (e) {
$(this).removeClass('resize');
$('.panel').addClass('flip');
});

I thought the following solution.
When '.panel' is mousedown for more than 500 ms, the button activates, pressed:
$(this).addClass('resize');

When '.panel' is mouseup, the button returns to its normal state and then all the buttons make the movement of output:
$(this).removeClass('resize');
 $('.panel').addClass('flip');

BUT if the user mousemove, the mousedown and mouseup actions are canceled.
just do not know how to put this into practice
is something similar to that:
http://m.microsoft.com/windowsphone/en-us/demo/default.aspx
Please Suggest.

redpajama_set_name: RedPajamaStackExchange


text:
Q: log into wordpress with webinject I am trying to create a script log into the admin section of wordpress and then check for updates, I already did this for drupal using the example mentioned here:
<case
    id="1"
    description1="short description"
    description2="long description"
    method="post"
    url="http://myserver/test/login.jsp"
    postbody="username=corey&password=welcome"
    verifypositive="verify this string exists"
    verifynegative="verify this string does not exist"
    logrequest="yes"
    logresponse="yes"
    sleep="3"
/>

and also a comment here http://drupal.org/node/147413#comment-1269222
I am however stuck with the  postbody part, it wont log in the admin page.
Any thoughts?

A: I can  tell you about the testcases we created for atlassian suite, maybe the example will help you, this case is the one we created for CONFLUENCE
TESTDATA FILE
confluence_Basic_AD_Login_testdata.xml  (it first login to webapp and then checks login by checking the dashboard)
 <testcases repeat="1">

 <case
         id="1"
         description="Get Confluence Login Page"
         method="post"
         url="https://confluence.company.com/login.action"
         postbody="os_username=conflumin&os_password=conflumin123"
         errormessage="Unable to connect to the login page of Confluence"
         verifypositive="Username"
         logrequest="yes"
         logresponse="yes"
 />

 <case
         id="2"
         description="Authentication by AD to Confluence"
         url="https://confluence.company.com/dashboard.action"
         verifypositive="Dashboard"
         errormessage="Unable to authenticate user in Confluence"
         logrequest="yes"
         logresponse="yes"

 />

 </testcases>

CONFIG FILE
file:  confluence_Basic_AD_Login_config.xml
   <testcasefile>confluence_Basic_AD_Login_testdata.xml</testcasefile>
   <useragent>WebInject Application Tester</useragent>
   <timeout>10</timeout>
   <globaltimeout>30</globaltimeout>
   <reporttype>nagios</reporttype>

That's all, and the check works with NagiosXI.
Hope it helps you.
karina


text:
Q: Using Shared Preferences in a RecyclerView item Button OnClick I have a ImageView in my product_list_item.xml as below:
 <ImageView
        android:id="@+id/imgbtn_favorite"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/txt_pdt_desc"
        android:layout_alignParentRight="true"
        android:layout_marginRight="3dp"
        android:background="@null"
        android:clickable="true"
        android:focusable="true"
        android:onClick="starOnClick"
        android:contentDescription="@string/favorites" />

App Output: RecyclerView with Favourites  ImageView
I have my OnItemClick and OnItemLongClick in my ProductListFragment class as below:
@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    Product product = (Product) parent.getItemAtPosition(position);
    Toast.makeText(activity, product.toString(), Toast.LENGTH_LONG).show();
}

@Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
        int position, long arg3) {
    ImageView button = (ImageView) view.findViewById(R.id.imgbtn_favorite);

    String tag = button.getTag().toString();
    if (tag.equalsIgnoreCase("grey")) {
        sharedPreference.addFavorite(activity, products.get(position));
        Toast.makeText(activity,
                activity.getResources().getString(R.string.add_favr),
                Toast.LENGTH_SHORT).show();

        button.setTag("red");
        button.setImageResource(R.drawable.heart_red);
    } else {
        sharedPreference.removeFavorite(activity, products.get(position));
        button.setTag("grey");
        button.setImageResource(R.drawable.heart_grey);
        Toast.makeText(activity,
                activity.getResources().getString(R.string.remove_favr),
                Toast.LENGTH_SHORT).show();
    }

    return true;
}

EDIT
My ProductListAdapter class
public class ProductListAdapter extends ArrayAdapter<Product> {

private Context context;
List<Product> products;
SharedPreference sharedPreference;

public ProductListAdapter(Context context, List<Product> products) {
    super(context, R.layout.product_list_item, products);
    this.context = context;
    this.products = products;
    sharedPreference = new SharedPreference();
}

private class ViewHolder {
    TextView productNameTxt;
    TextView productDescTxt;
    TextView productPriceTxt;
    ImageView favoriteImg;
}

@Override
public int getCount() {
    return products.size();
}

@Override
public Product getItem(int position) {
    return products.get(position);
}

@Override
public long getItemId(int position) {
    return 0;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.product_list_item, null);
        holder = new ViewHolder();
        holder.productNameTxt = (TextView) convertView
                .findViewById(R.id.txt_pdt_name);
        holder.productDescTxt = (TextView) convertView
                .findViewById(R.id.txt_pdt_desc);
        holder.productPriceTxt = (TextView) convertView
                .findViewById(R.id.txt_pdt_price);
        holder.favoriteImg = (ImageView) convertView
                .findViewById(R.id.imgbtn_favorite);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }
    Product product = (Product) getItem(position);
    holder.productNameTxt.setText(product.getName());
    holder.productDescTxt.setText(product.getDescription());
    holder.productPriceTxt.setText(product.getPrice() + "");

    /*If a product exists in shared preferences then set heart_red drawable
     * and set a tag*/
    if (checkFavoriteItem(product)) {
        holder.favoriteImg.setImageResource(R.drawable.heart_red);
        holder.favoriteImg.setTag("red");
    } else {
        holder.favoriteImg.setImageResource(R.drawable.heart_grey);
        holder.favoriteImg.setTag("grey");
    }

    return convertView;
}

/*Checks whether a particular product exists in SharedPreferences*/
public boolean checkFavoriteItem(Product checkProduct) {
    boolean check = false;
    List<Product> favorites = sharedPreference.getFavorites(context);
    if (favorites != null) {
        for (Product product : favorites) {
            if (product.equals(checkProduct)) {
                check = true;
                break;
            }
        }
    }
    return check;
}

@Override
public void add(Product product) {
    super.add(product);
    products.add(product);
    notifyDataSetChanged();
}

@Override
public void remove(Product product) {
    super.remove(product);
    products.remove(product);
    notifyDataSetChanged();
}
}

EDIT-2
My SharedPreferencesclass have the following:
   public void addFavorite(Context context, Product product) {
    List<Product> favorites = getFavorites(context);
    if (favorites == null)
        favorites = new ArrayList<Product>();
    favorites.add(product);
    saveFavorites(context, favorites);
}

public void removeFavorite(Context context, Product product) {
    ArrayList<Product> favorites = getFavorites(context);
    if (favorites != null) {
        favorites.remove(product);
        saveFavorites(context, favorites);
    }

My complete ProductListFragment class is as below:
public class ProductListFragment extends Fragment implements
    OnItemClickListener, OnItemLongClickListener {

public static final String ARG_ITEM_ID = "product_list";

Activity activity;
ListView productListView;
List<Product> products;
ProductListAdapter productListAdapter;

SharedPreference sharedPreference;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    activity = getActivity();
    sharedPreference = new SharedPreference();
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_product_list, container,
            false);
    findViewsById(view);

    setProducts();

    productListAdapter = new ProductListAdapter(activity, products);
    productListView.setAdapter(productListAdapter);
    productListView.setOnItemClickListener(this);
    productListView.setOnItemLongClickListener(this);
    return view;
}

private void setProducts() {

    Product product1 = new Product(1, "Dell XPS", "Dell XPS Laptop", 60000);
    Product product2 = new Product(2, "HP Pavilion G6-2014TX",
            "HP Pavilion G6-2014TX Laptop", 50000);
    Product product3 = new Product(3, "ProBook HP 4540",
            "ProBook HP 4540 Laptop", 45000);
    Product product4 = new Product(4, "HP Envy 4-1025TX",
            "HP Envy 4-1025TX Laptop", 46000);
    Product product5 = new Product(5, "Dell Inspiron",
            "Dell Inspiron Laptop", 48000);
    Product product6 = new Product(6, "Dell Vostro", "Dell Vostro Laptop",
            50000);
    Product product7 = new Product(7, "IdeaPad Z Series",
            "Lenovo IdeaPad Z Series Laptop", 40000);
    Product product8 = new Product(8, "ThinkPad X Series",
            "Lenovo ThinkPad X Series Laptop", 38000);
    Product product9 = new Product(9, "VAIO S Series",
            "Sony VAIO S Series Laptop", 39000);
    Product product10 = new Product(10, "Series 5",
            "Samsung Series 5 Laptop", 50000);

    products = new ArrayList<Product>();
    products.add(product1);
    products.add(product2);
    products.add(product3);
    products.add(product4);
    products.add(product5);
    products.add(product6);
    products.add(product7);
    products.add(product8);
    products.add(product9);
    products.add(product10);
}

private void findViewsById(View view) {
    productListView = (ListView) view.findViewById(R.id.list_product);
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
        long id) {
    Product product = (Product) parent.getItemAtPosition(position);
    Toast.makeText(activity, product.toString(), Toast.LENGTH_LONG).show();
}

@Override
public boolean onItemLongClick(AdapterView<?> arg0, View view,
        int position, long arg3) {
    ImageView button = (ImageView) view.findViewById(R.id.imgbtn_favorite);

    String tag = button.getTag().toString();
    if (tag.equalsIgnoreCase("grey")) {
        sharedPreference.addFavorite(activity, products.get(position));
        Toast.makeText(activity,
                activity.getResources().getString(R.string.add_favr),
                Toast.LENGTH_SHORT).show();

        button.setTag("red");
        button.setImageResource(R.drawable.heart_red);
    } else {
        //sharedPreference.removeFavorite(activity, products.get(position));
        button.setTag("grey");
        button.setImageResource(R.drawable.heart_grey);
        Toast.makeText(activity,
                activity.getResources().getString(R.string.remove_favr),
                Toast.LENGTH_SHORT).show();
    }

    return true;
}

Currently the items are marked as Favourites when the user LongClicks (OnItemLongClick) an Item in the RecyclerView..
i implemented the starOnClick in my MainActivity class as below:
public void starOnClick (View view){
    // Toast.makeText(getApplicationContext(),"Star Clicked",Toast.LENGTH_SHORT).show();
}

but i get errors, since i dont know how to get position of the item and saved sharedpreferences in here....
how can i implement the onClick on my ImageView imgbtnFavouriteto mark the items as Favourites

A: You need to implement the click at the adapter not in MainActivity :
holder.favoriteImg.setOnClickListener(this)

and implement the onClick(View v) where you add the product to the shared preference and change the image too.

A: Firstly, I consider it a sub-optimal solution to use SharedPreferences to store this "isFavorite" information. This is a disk operation which will take a performance hit in a highly optimized RecyclerView element. Instead add a property to your Product class which maintains information whether the product is a "Favorite". In my examlpe I will use getIsFavorite() and setIsFavorite(boolean).
You need to handle the onClick in your Adapter class by setting the setOnClickListener(). Note that you could also just add a onClick for the Item instead of the ImageView ... that will give the user a bigger target to tap.
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder = null;
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context
                .getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.product_list_item, null);
        holder = new ViewHolder();
        holder.productNameTxt = (TextView) convertView
                .findViewById(R.id.txt_pdt_name);
        holder.productDescTxt = (TextView) convertView
                .findViewById(R.id.txt_pdt_desc);
        holder.productPriceTxt = (TextView) convertView
                .findViewById(R.id.txt_pdt_price);
        holder.favoriteImg = (ImageView) convertView
                .findViewById(R.id.imgbtn_favorite);

        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.favoriteImg.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Product prod = products.get(position);
            //toggle the value
            boolean isFavorite = !prod.getIsFavorite();
            prod.setIsFavorite(isFavorite);

            if (isFavorite) {
                holder.favoriteImg.setImageResource(R.drawable.heart_red);
                holder.favoriteImg.setTag("red");
            } else {
                holder.favoriteImg.setImageResource(R.drawable.heart_grey);
                holder.favoriteImg.setTag("grey");
            }
        }
    });

    Product product = (Product) getItem(position);
    holder.productNameTxt.setText(product.getName());
    holder.productDescTxt.setText(product.getDescription());
    holder.productPriceTxt.setText(product.getPrice() + "");

    boolean isItemFavorite = product.getIsFavorite();

    if (isItemFavorite) {
        holder.favoriteImg.setImageResource(R.drawable.heart_red);
        holder.favoriteImg.setTag("red");
    } else {
        holder.favoriteImg.setImageResource(R.drawable.heart_grey);
        holder.favoriteImg.setTag("grey");
    }

    return convertView;
}

Now you can get rid of the checkFavoriteItem() method because you are no longer using SharedPreferences.
So now you do not need these attributes in the ImageView

    android:clickable="true"
    android:focusable="true"
    android:onClick="starOnClick"

Remove them so it can look like this:
<ImageView
        android:id="@+id/imgbtn_favorite"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignBottom="@+id/txt_pdt_desc"
        android:layout_alignParentRight="true"
        android:layout_marginRight="3dp"
        android:background="@null"
        android:contentDescription="@string/favorites" />

Edit:
To add the isFavorite property to your Product class simply add a new class variable:
private boolean isFavorite = false;

Then add the setter:
public void setIsFavorite(boolean favorite) { this.isFavorite = favorite; }

and the getter:
public boolean getIsFavorite(){ return this.isFavorite; }


text:
Q: CSS layout for fixed header and 100% content height? I'm trying to get a fixed height header and a content area the fills the screen.  The content div contains a telerik mvc grid.  I've tried a few suggested on stackoverflow but the control that is the content area always seems to size incorrectly because it doesn't take into account the header fixed height, so it will scroll the extra 40px if the header is 40px. Any suggestions?

   <telerik mvc grid control>

Css
html,body
{
     margin:0;
     padding:0;
     height:100%;
}

#header {
    position:absolute;
    height: 40px;
    left:0;
    top:0;
    width:100%;
    background:green;
  }

  #content {
    position: absolute;
    top:40px;
    left:0;
    width:100%;
    height:100%;
    background:#eee;
  }

UPDATE:
Had to manually re-size the grid on load and window re-size.
   Add
 .ClientEvents(events => events.OnLoad("resizeGrid"))

A: DEMO
HTML

HEADER

CONTENT

CSS
html, body {
    height:100%;
    margin:0;
    padding:0;
}
#wrapper {
    width:400px; /*set to desired width*/
    height:100%;
    margin:auto;
    position:relative;
}
#header {
    height:40px; /* set to desired height*/
}
#content {
    position:absolute;
    bottom:0;
    top:40px; /*must match the height of #header*/
    width:100%;
    overflow:auto;
}

A: You could place the #header element inside of the #content element, the content element will take 100% height.
Here's an example, HTML:

        Header.

    Content Area.

CSS:
body,html {
    height:100%;
    margin:0;
    padding:0;
}

#header {
    background:#666;
    height:30px;
}

#content {
    height:100%;
    background:#999;
    width:100%;
}

Demo:
http://jsfiddle.net/Rz2tN/

A: With box-sizing you can do like
http://jsfiddle.net/Wener/Vat4C/1/
No matter the header is in wrapper or out of wrapper, it will work.
Only add :
#wrapper
{
    box-sizing: border-box;
    padding-top: 40px;
    margin-top: -40px;
}
#header
{
    /* add this if header out of wrapper */
    position: relative;
    z-index: 9;
}
#content
{
    /* remove
    position:absolute;
    bottom:0px;
    top: 40px;*/

    /* add */
    height: 100%;
}

This is more flexible, the content's position is no absolute, but it need the box-sizing property.
About the box-sizing, I defined less function as fallow:
.box-sizing(@type: content-box) {
    -webkit-box-sizing: @type; /* <=iOS4, <= Android  2.3 */
    -moz-box-sizing: @type; /* Firefox 1+ */
    box-sizing: @type; /* Chrome, IE8+, Opera, Safari 5.1*/
}

.border-box()
{
    .box-sizing(border-box);
}

A: Set the outer  to be 100% height, inside make your fixed with header, and auto height for the content should suffice.
to fix the scrolling, take a look at the overflow porperty. visible will prevent scrolling.

A: Put a 25px top-margin on the content div and make sure the content div does not include the header.
If the content div must include the header, create a new div for your grid using the same properties stated above.

A: For Vertical Scroll we can use the following and for horizontal scroll just use a div

@(Html.Telerik().Grid(listCustomerStatus)
                .Name("grvSalesAdjustment")
                .DataKeys(keys => keys.Add(k => k.CustCode))
                .Columns(column =>
                {

                })
               .Selectable()
               .Pageable(page => page.PageSize(100))
               .Scrollable(scroll => scroll.Height(300))
)

add the following CSS
.DataGridXScroll
{
    width: 1000px;
    overflow-x: scroll;
    text-align:left;
}

This is work in Firefox and other browser. For IE just use the following CSS
.t-grid
{
   position: static;
   overflow:hidden;
}

.t-grid-content
{
   overflow-x: hidden;
   position:static;
   width:100%;
}

.t-grid-header-wrap
{
   position:static;
}

.t-grid-content
{
   overflow-x: hidden;
}

.t-grid-footer-wrap
{
  position:static;
}

This is a very Simple solution and I think every one enjoy it.


text:
Q: Phonegap -how to use plugins when building locally I am using the latest version of Phonegap and I am trying to include some plugins in my application. I have installed the plugins via cli and they appear in my plugins folder. However, even after referencing them in the config.xml I cannot get them to work. I have successfully used plugins via the phonegap online compiler but I do not know how to use them locally. Please help!
FIXED -------------------------------------------------------------------------------------------------
It turns out that I had everything correct in my project except for the cordova.js reference. I was physically referencing a copy that I had place in my js folder instead of only referencing it and allowing phonegap to generate the copy. The problem was in the fact that I then referenced js/cordova.js instead of cordova.js. Thanks for all of the suggestions below!

A: @Matt Butler, What do you mean you cannot get them to work? Can you get an APK? Will the install? Does the javascript work? Can you build Hello World?


text:
Q: scrapy pagination selenium python I'm trying to scrape links off of a table using pagination. I can get Selenium to iterate through the pages and I can get the links off of the first page, however if I try to combine the two, when I get to the last page and there is no longer a next page button, the process stops, and I get nothing.
I am unsure how to gracefully tell the thing to simply return the data to csv. I am using a while true: loop so it's rather puzzling to me.
Another question has to do with targeting the links I am trying to parse using xpath. The links are held in two different tr-classes. One set is under //tr[@class ="resultsY"] and the other under //tr[@class ="resultsW"], is there an OR statement of some sort I can use to target all of the links in one go?
One solution I found:
'//tr[@class ="resultsY"] | //tr[@class ="resultsW"]' gives me an error every time.
Here's the html table:

-
-
----        <----a link i'm after
-
-

-
-
----        <----a link i'm after
-
-

And here is my scrapy:
import time
from scrapy.item import Item, Field
from selenium import webdriver
from scrapy.spider import BaseSpider
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import Select
from selenium.common.exceptions import NoSuchElementException
from scrapy.selector import HtmlXPathSelector

class ElyseAvenueItem(Item):
    link = Field()
    link2 = Field()

class ElyseAvenueSpider(BaseSpider):
    name = "s1"
    allowed_domains = ["nces.ed.gov"]
    start_urls = [
    'https://nces.ed.gov/collegenavigator/']

    def __init__(self):
        self.driver = webdriver.Firefox()

    def parse(self, response):
        self.driver.get(response.url)
        select = Select(self.driver.find_element_by_id("ctl00_cphCollegeNavBody_ucSearchMain_ucMapMain_lstState"))
        select.deselect_by_visible_text("No Preference")
        select.select_by_visible_text("Alabama")
        self.driver.find_element_by_id("ctl00_cphCollegeNavBody_ucSearchMain_btnSearch").click()

#here is the while loop. it gets to the end of the table and says...no more "next page" and gives me the middle finger

        '''while True:
            el1 = self.driver.find_element_by_partial_link_text("Next Page")
            if el1:
                el1.click()
            else:
                #return(items)
                self.driver.close()'''
        hxs = HtmlXPathSelector(response)

        '''
#here i tried: titles = self.driver.find_elements_by_xpath('//tr[@class ="resultsW"] | //tr[@class ="resultsY"]') and i got an error saying that

        titles = self.driver.find_elements_by_xpath('//tr[@class ="resultsW"]')
        items = []
        for titles in titles:
            item = ElyseAvenueItem()

#here i'd like to be able to target all of the hrefs...not sure how

            link = titles.find_element_by_xpath('//tr[@class ="resultsW"]/td[2]/a')
            item ["link"] = link.get_attribute('href')
            items.append(item)
        yield(items)

A: Breaking this post into three posts would increase your chances of getting good answers.
For the first question, it would be helpful to know more precisely what "the process stops and i get nothing" means. I don't see you trying write the "links" to a file. I don't understand why you do what you do in your else clause.
For the second question, using regular expression might do the trick. See this.
For the third question, since the element title is the list
titles = self.driver.find_elements_by_xpath('//tr[@class ="resultsW"]') ,
you could just do
hrefs=[]
for titles in titles:
    href = titles.find_element_by_xpath('a').get_attribute('href')
    hrefs.append(href)

As an aside, if all that you trying to do is to get the links off a page, consider mechanize, lxml.html and|or BeautifulSoup.


text:
Q: Usage of ''both"
*

*Both the control laws demand high magnitude of acceleration at the end.

*Both the control laws demand high magnitudes of acceleration at the end.

*At the end phase, acceleration demand of both the guidance laws shoots up.

*At the end phase, acceleration demands of both the guidance laws shoot up.

Which one is grammatically correct?

A: I had not seen "both" after "of"  so I would say that the last two are wrong.
The majority of the time, I had seen the word "Both" in order to omit the noun.
For example: John and Heather? Both are coming to the wedding.
However, the word "Both" can be used as an adjective. As result of it, (S1) and (S2) are right but you have to change the order like this:
"The both control laws demand high magnitude of acceleration at the end."


text:
Q: jQuery UI dialog: how to add overlay with `modal: false` option? Is it possible to add overlay to dialog with modal: false? Maybe with the help of external class...
Really need it!
Thanks!

A: You can try adding a div as the first element of body and displaying it when you open the dialog box. Here is sample CSS for that div. This will create a div covering the entire page with black color an opacity 70%. You will have to adjust the z-index according to the z-index of the dialog and use the open event of jquery UI dialog to make this div visible.
.overlaydiv{ background-color: #000000; display: none; height: 100%; -moz-opacity: 0.7; opacity:.70; filter: alpha(opacity=70); left: 0%; position: fixed; top: 0%; width: 100%; z-index:1001; }

Make sure to add a div right after the opening  tag, else it would not cover the entire page.

...


text:
Q: Having error during use ispconfig auto installer in debian 11 [WARN] Query CREATE DATABASE phpmyadmin; failed. (/lib/os/class.ISPConfigDebianOS.inc.php:339)[WARN] Query CREATE USER 'pma'@'localhost' IDENTIFIED BY 'uUFMzprRqDAZm1B'; failed. (/lib/os/class.ISPConfigDebianOS.inc.php:339)
[INFO] HTTPoxy config.
[INFO] Installing acme.sh (Let's Encrypt).
[INFO] acme.sh (Let's Encrypt) installed.
[INFO] Installing packages quota, quotatool, haveged, geoip-database, libclass-dbi-mysql-perl, libtimedate-perl, build-essential, autoconf, automake, libtool, flex, bison, debhelper, binutils
[INFO] Installed packages quota, quotatool, haveged, geoip-database, libclass-dbi-mysql-perl,
libtimedate-perl, build-essential, autoconf, automake, libtool, flex, bison, debhelper, binutils
[INFO] Adding quota to fstab.
[ERROR] Exception occured: ISPConfigOSException -> Command mount -o remount / 2>&1 && quotaoff -avug 2>&1 && quotacheck -avugm 2>&1 && quotaon -avug 2>&1 failed. (/ispconfig.ai.php:15)

Having this problem whem I'm using ispconfig autoinstaller command below
curl https://get.ispconfig.org | sh -s -- --debug --no-mailman
Also tried without debug.

A: you need to use su -  that solved the issue for me.


text:
Q: Import Excel Sheet into SQL Server 2012 I am presently doing migration of SQL Server 2005 to SQL Server 2012. Mostly all the functionality remains the same. However, in few store I was using Jet provider 4.0 to import Excel data into the SQL Server table. I know it is not being supported for 64 bits & Ace provider is an alternate for that. However, my query works only for sysadmin (SA) access, which will not be provided in the production.
Does anybody have the solution for the same ?
Below is the query I tried for the same.
USE Master

sp_configure 'Show Advanced Options', 1;
RECONFIGURE;
GO

sp_configure 'Ad Hoc Distributed Queries', 1;
RECONFIGURE;
GO

EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'AllowInProcess', 1
GO

EXEC sp_MSset_oledb_prop N'Microsoft.ACE.OLEDB.12.0', N'DynamicParameters', 1
GO

SELECT * FROM OPENDATASOURCE('Microsoft.ACE.OLEDB.12.0',
  'Data Source=C:\Cutomer_Transaction.xls;Extended Properties=Excel 12.0')...[Sheet1$]
GO

This query works fine for sa login. But fails for other users with below  message:

Ad Hoc access to oledb Provider 'Microsoft.Ace.Oledb.12.0' has been denied. You must access this provider through linked server.


text:
Q: Reflection through bisector of angle $\angle A$ Let ABC be a triangle. Let B' and C' denote respectively the reflection of B and C in the internal angle bisector of $\angle A$, Show that the triangle ABC and AB'C' have the same in centre?
What should be the approach in this question? I don't even know how to initiate.

A: Hint: Since it is a reflection, the angle bisector at $B$ reflects to the angle bisector at $B',$ and similarly for the bisectors at $C$ and at $C'.$ In either triangle, the center of the incircle is at the intersection of the three bisectors. So each triangle's incenter lies on the bisector at $A$, and maybe the above about the other two bisectors in each triangle will lead to something to prove it.

A: In-center I is the point of concurrence. Since one bisector is fixed and other two bisectors are swapped by reflection about the first fixed line , position of I does not change.


text:
Q: Is it possible to disable swipe keyboard in windows phone 8.1 RT TextBox Is it possible to disable swipe keyboard in TextBox just like PasswordBox does.

A: Found a workaround.
Add a textbox (and delete the text in it)

Add a passwordbox on The textbox

Set the passwordboxes opacity to 0%

Make a passwordchanged trigger on The passwordbox (double click on passwordbox does the same) and write a code on that sets the text of The textbox to The passwordboxes password (add names to The passwordbox and textbox before this)

You must be done!
I hope I helped you.

A: Not necessarily the best solution, but playing with the InputScope might get you what you want. For example, this won't allow the shape-writing keyboard:
<TextBox InputScope="NameOrPhoneNumber"/>

The list of possible InputScope values can be found here.
[Edit: Updated for XAML]

A: I Think it's impossible to disable swipe keyboard in textBox but you can disable it from phone settings (Settings -> Keyboard -> tap your keyboard language -> uncheck "Type as I swipe through letters").


text:
Q: Why my code is behaving like this? This is my first question here so i apologize if its not a useful question.
I have this project of a simulator where the user calls the program via command line with some parameters. Like, MYPROG [options] filename.
I need to make sure the filename is valid, where it is (directory) and get the name for further use.
Here is part of the code:
char* ExtrairNome(char* alvo){
    char* teste = alvo;
    char* nome = NULL;
    int barras = 0;

    while(strcmp(teste, "") != 0){ //look for "/"
        if (teste[0] == '/') barras++;
        teste++;
    }

    teste = alvo;
    if (barras > 0){
        while(barras > 0){ //remove everything leaving the "filename.ias"
            if (teste[0] == '/') barras--;
            teste++;
        }
    }

    int i = 0;
    char aux[strlen(teste) - 4];
    while (strcmp(teste, ".ias")){ //remove the ".ias"
        aux[i] = teste[0];
        teste++;
        i++;
    }
    printf("random %d\n", barras); //this line fixes the bug!!
    aux[i] = '\0';
    nome = aux;
    return nome;
}

This function receives the string with the full filename and should return only the name, without extention or path. But it only works when i printf some variable before returning. If i remove that line the function returns nothing.
I think it has something to do with scope but i don't know for sure. How can i fix this?

A: nome is a pointer, so you can return the address of the solution.
Problem is aux, which is in the stack, and once you return, it doesn't exist anymore, so behaviour is unknown. You have two choices, declaring "aux" in a higher scope and pass it to your function, and passing a pointer to the buffer solution or allocate in the function(using malloc) and then free(when its not necessary).
i mean:
char name[100];
ExtrairNome(alvo, name);//pass a pointer to the function

void ExtrairNome(char * alvo, char * aux)
{
     ...;//everything is the same
     //except you don't create aux here, you use the one you created in your main function
}

or
char * ExtrairNome(char * alvo, char * aux)
{
     ...;//everything is the same
     char * aux = (char*)malloc((strlen(teste)-4 )* sizeof(char));
     ...;//everything the same
}
//remember to free() when you are done using it

A: You are returning a pointer to a local automatic (stack) variable - aux. That does not exist after the function returns. This is undefined behavior. The fact that it 'works' when you print a variable is one possibility for undefined behavior.


text:
Q: Why does a dynamic TabControl seem to be unable to switch between the tabs? I'm using a dynamic TabControl in a page:
    <TabControl x:Name="DynamicTabControl"
                ItemsSource="{Binding TabsCollection, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:TabView}}}"
                SelectionChanged="tabDynamic_SelectionChanged">
        <TabControl.ItemTemplate>
            <DataTemplate x:Name="TabHeader" DataType="TabItem">
                <DockPanel Width="30">
                    <TextBlock Text="{Binding RelativeSource={RelativeSource AncestorType=TabItem }, Path=Header}" />
                </DockPanel>
            </DataTemplate>
        </TabControl.ItemTemplate>
        <TabControl.ContentTemplate>
            <DataTemplate >
                <local:TabItem/>
            </DataTemplate>
        </TabControl.ContentTemplate>
    </TabControl>

        public ObservableCollection<TabItem> TabsCollection {get;set;}
        private TabItem _tabAdd;

        #region Initialization
        public TabView()
        {
            InitializeComponent();
            TabsCollection = new ObservableCollection<TabItem>();
            TabsCollection.Add(new TabItem { Header = "Tab 1"});

            // add a tabItem with + in header
            _tabAdd = new TabItem
            {
                Header = "+"
            };

            TabsCollection.Add(_tabAdd);

            DynamicTabControl.DataContext = TabsCollection;
            DynamicTabControl.SelectedIndex=0;
        }
        #endregion

        private TabItem AddSubsequentTabItem()
        {
            int count = TabsCollection.Count;
            TabItem tab = new TabItem();

            tab.Header = string.Format("Tab {0}", count);
            tab.Name = string.Format("tab{0}", count);

            TabsCollection.Insert(count - 1, tab);
            return tab;
        }

        private void tabDynamic_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            TabItem tab = DynamicTabControl.SelectedItem as TabItem;
            if (tab == null) return;

            if (tab.Equals(_tabAdd))
            {
                // clear tab control binding
                DynamicTabControl.DataContext = null;

                TabItem newTab = this.AddSubsequentTabItem();

                // bind tab control
                DynamicTabControl.DataContext = TabsCollection;

                // select newly added tab item
                DynamicTabControl.SelectedItem = newTab;
            }
            else
                Dispatcher.BeginInvoke((Action)(() => DynamicTabControl.SelectedIndex = DynamicTabControl.SelectedIndex));
        }

But, I'm unable to get the tab control to switch between my TabItems.
I'm using an amalgamation of the dynamic tab control from https://www.codeproject.com/Articles/493538/Add-Remove-Tabs-Dynamically-in-WPF , with modifications to create the GUI objects from within xaml.
My title pretty much says it all: Why is my TabControl not switching tabs? Even besides fixing the problem, I'd like to know if subscribing a method to the "selectionChanged" event unsubscribes the native tab switching.
Here is the barebones example project of the problem


text:
Q: Unable to create number of sections in tableView based on no of items in dictionary hello I have a dictionary like this
  {
        0 =     {
            ProductRequest =         {
                description = "";
                "destination_country" = "";
            };
            User =         {
                "first_name" = irfan;
                "last_name" = sheikhg;
            };
        };
        1 =     {
            ProductRequest =         {
                description = dummy;
                "destination_country" = dummy;
                "user_id" = 9;
            };
            User =         {
                "first_name" = john;
                "last_name" = Doe;
            };
        };
        code = 200;
    }

If I return the sections like this, my program crashes
return dict.count - 1

If I do this
return dict.count

Program doesn't crash but it returns one empty section extra. By looking at my array you will know that 3rd element I am sending success code in array, thats why I am doing dict.count - 1
Complete Class Code
  class RequestTableViewController: UITableViewController {
  var dict = NSDictionary()

  override func viewDidLoad() {
    super.viewDidLoad()
    getRequestsFromServer()
  }

  override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    return dict.count - 1
  }

  override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return 1
  }

  override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath) as! RequestTableViewCell
    if(indexPath.section == 0) {
      cell.requestTitleTextView.text = (((self.dict["\(indexPath.row)"] as?NSDictionary)!["ProductRequest"] as?NSDictionary)!["request_title"] as?NSString)! as String

      let firstName = (((self.dict["\(indexPath.row)"] as?NSDictionary)!["User"] as?NSDictionary)!["first_name"] as?NSString)! as String
      let  lastName = (((self.dict["\(indexPath.row)"] as?NSDictionary)!["User"] as?NSDictionary)!["last_name"] as?NSString)! as String

      cell.userNameLabel.text = firstName.uppercaseString + " " +  lastName.uppercaseString
    }
    return cell
  }

  func getRequestsFromServer() {
    let url:String = Variables.GETALLREQUESTS_URI
    let params = ["data":"get"]
    ServerRequest.postToServer(url, params: params) { result, error in

      if let result = result {
        let code =  result["code"] as? Int
        print(result)
        if(code == 200) {
          self.dict = result
          dispatch_async(dispatch_get_main_queue(), {
            // DO SOMETHING ON THE MAINTHREAD
            self.tableView.reloadData()
          })

        } else if(code==500 ) {
          dispatch_async(dispatch_get_main_queue(), {
            AlertView().showAlert(Message.INTERNETISNOTCONNECTED)
            /*let alert = UIAlertView()
            alert.message = Message.INTERNETISNOTCONNECTED
            alert.addButtonWithTitle("Ok")
            alert.show()*/
          })
        }
      }
    }
  }
}

Update:
When It crashes. nothing is printing out on console. here is the image

A: I think @Wain is onto something :)
If your dict is initially empty then you're returning -1 as the number of sections - that probably won't work. You will need to check for that in your numberOfSections method :
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    guard dict.count > 0 else { return 0 }

    return dict.count - 1
}

Though a better way to deal with this might be to be smarter about how you calculate the number of sections; just subtracting 1 from the count is going to run into trouble if the server ever returns any other keys apart from 'code' . . .


text:
Q: Can you make sure only one object related to another object has a certain field set? I have a model called Video, and it has related objects on another model called Label. Example here:
class Video(models.Model):
    pass

class Label(models.Model):
    video = models.ForeignKey(Video, related_name="labels")
    current = models.NullBooleanField()

I need to be able to find the current label on a video by doing something like my_video.labels.filter(current=True), and this query should only ever return one label, so only one label on the video should have that field set to True.
Is there a way of ensuring this on the model/db?
Thanks
EDIT: The answer given below has achieved exactly this. Adding some django tests below for anyone else reading as some proof:
class TestLabelIntegrity(TestCase):
    def test_a_video_can_have_only_one_current_label(self):
        video = Video.objects.create()
        label_1 = Label.objects.create(
            video=video,
            current=True
        )
        with self.assertRaises(IntegrityError):
            label_2 = Label.objects.create(
                video=video,
                current=True
            )

    def test_two_different_videos_can_each_have_current_layers(self):
        """ No assertions needed, just need to make sure no integrity errors are raised"""
        video_1 = Video.objects.create()
        label_1 = Label.objects.create(
            video=video_1,
            current=True
        )
        video_2 = Video.objects.create()
        label_2 = Label.objects.create(
            video=video_2,
            current=True
        )

A: I believe you can solve this using UniqueConstraint.
Using this, you can restrict that a Video only have a single label that current == True
You can define the UniqueConstraint in the models Meta.
You'll get a database integrity error on save() if the condition fails.
See the documentation for this here:
https://docs.djangoproject.com/en/4.0/ref/models/constraints/
class Label(models.Model):
    ...
    class Meta:
        constraints = [
            models.UniqueConstraint(
                fields=["current", "video"],
                condition=Q(current=True),
                name="unique_current_label",
            ),
        ]


text:
Q: appending onto multiple elements in d3js i wanted to know is there way to distinguish between which element of the parent array we are appending onto and append selectively?
eg:

cell = parent.selectAll("g")
      .data(nodes)
      .enter()
   .append("svg:g")
   .filter(function(d,j){ var a = parent.selectAll("text");
  for(i=0;i<3;i++)
  if(a[i][0].innerHTML == d.parent.name)
  return true;
  return false;
   })
      .attr("class", "cell")
      .attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; })
      .on("click", function(d) { return zoom(node == d.parent ? root : d.parent); });

parent is cell of the previous iteration which consists of 3 cells
i want to writ a filter logic such that i can choose which object of nodes array goes to which cell
i can't hard code it as it will be dynamic>
thanks for you help.


text:
Q: Homology is a functor into Groups or R-Modules From what I understood, taking the homology was a functor from the category of chain complexes to abelian groups. I am reading through Davis' lectures on algebraic topology and it states that homology is a functor from chain complexes to graded $R$-modules.

Is this a more general kind of homology, or is this because we can view any abelian group as a $\mathbb Z$ module?

A: Here's a brief outline of how all this goes.
When you first learn homology you are really learning homology with $\mathbb Z$-coefficients.
At a more advanced level, given an abelian group $A$, you can learn homology with coefficients in $A$. Commonly studied examples are $A = \mathbb Z / 2 \mathbb Z$, $\mathbb Q$, $\mathbb R$, or $\mathbb C$. The idea is that when defining the chain groups $C_n$, each simplex is assigned a coefficient from the abelian group $A$ instead of a coefficient from $\mathbb Z$, thus making each chain group into a free abelian group.
Now "abelian groups" and "$\mathbb Z$-modules" are more-or-less the same kind of mathematical objects. So when you learn homology with coefficients in an abelian group $A$, you are really learning homology with coefficients in $\mathbb Z$-modules. Each chain group with coefficients in $A$ is still an abelian group, i.e. it is a $\mathbb Z$-module (in fact, a free $\mathbb Z$-module, if $A$ itself is free). Each boundary map is an abelian group homomorphism, i.e. it is a $\mathbb Z$-module homomorphism. The kernels (cycle groups), boundary groups (image groups), and homology groups (quotients of cycle groups modulo image groups) are all abelian groups, i.e. all $\mathbb Z$-modules.
And then, given a commutative ring $R$ with unit, you can study homology with coefficients in an $R$-module $M$: when defining the chain groups $C_n$, each simplex is assigned a coefficient from $M$. The chain groups themselves are then $R$-modules (in fact, free $R$-module, if $M$ itself is free), the boundary maps are $R$-module homomorphisms, and the chain groups, boundary groups, and homology groups are all $R$-modules.


text:
Q: Prove the intersection of transitive relations is transitive. Prove the intersection of transitive relations is transitive.
Let $\left\{\mathcal\ R_{i}:i\ \in\ \mathcal I\right\}$ be the set of transitive relations on $A$ indexed by $\mathcal I$,it should be shown that:
$$ (\forall i  :i\in \mathcal I \implies\mathcal R_i \text{ is transitive}) \implies \bigcap_{i \in \mathcal I}\mathcal R_i \;\text{ is transitive}$$
This can be proved by induction on the number of elements in $\mathcal I$.
Let $\left|\mathcal I\right|=0$,then:
$$ (\forall i :i\in \varnothing \implies\mathcal R_i \text{ is transitive}) \implies \bigcap_{i \in \mathcal I}\mathcal R_i =A \times A $$
Which by the definition of Cartesian product implies  $A \times A $ is transitive.
Assume the theorem is true for $\left|\mathcal I\right|=n$ and consider $\left|\mathcal I\right|=n+1$:
Assume $ (\forall i :i\in \mathcal I \implies\mathcal R_i \text{ is transitive})  $
$$\bigcap_{i \in \mathcal I}\mathcal R_i =\bigcap_{i \in \mathcal I \setminus \left\{n+1\right\} }\mathcal R_i \; \cap \mathcal R_{n+1}$$
By the induction hypothesis and the assumption that $\mathcal R_{n+1}$ is transitive it implies that:
$$\bigcap_{i \in \mathcal I \setminus \left\{n+1\right\} }\mathcal R_i \; \cap \mathcal R_{n+1}$$
Is transitive.

Is what have I done true?Also can the index set be an infinite one? And is it necessary for the transitive relations to be over the same set?if yes then why?

A: Unfortunately, your proof doesn't work. Your inductive proof only shows that if any intersection of $n$ transitive relations is transitive, then any intersection of $n+1$ transitive relations can be represented as an intersection of $2$ transitive relations. However, your argument fails to show that an intersection of $2$ transitive relations is transitive, hence the result doesn't follow.
Also, standard induction can't work for infinite families.
The simplest proof would involve going back to the definition of transitivity: if $(x,y), (y,z) \in R$ then $(x,z) \in \mathcal R$.
Assume that $(x,y),(y,z) \in \bigcap_{i \in \mathcal I} \mathcal R_i$. By the definition of intersection, this means that, for each $i \in \mathcal I$, $(x,y),(y,z) \in \mathcal R_i$. Since each $\mathcal R_i$ is transitive, that means that $(x,z) \in \mathcal R_i$ for each $i \in \mathcal I$. Again, by the definition of intersection,this means that $(x,z) \in \bigcap_{i \in \mathcal I} \mathcal R_i$.
So $(x,y),(y,z) \in \bigcap_{i \in \mathcal I} \mathcal R_i$ implies $(x,z) \in \bigcap_{i \in \mathcal I}$. Therefore $\bigcap_\mathcal{i \in \mathcal I} \mathcal R_i$ is transitive.
Note that this proof can be generalized way further. Let $\{S_i : i \in I\}\subseteq 2^X$. Let $A \subseteq 2^X$. Let $\phi: A \rightarrow 2^X$. The argument above shows that if any family $S_i$ satisfies the condition:
For any $S \subseteq S_i: S \in A$, $\phi(S) \subseteq S_i$.
Then $\bigcap_{i \in I} S_i$ satisfies it as well.


text:
Q: Postfix: allow inbound relaying from only authenticated MTAs I want to authenticate our customers' MTAs (Exchange for the most part, pointing to us as its smart host) to our relay server (Postfix 2.11.3, CentOS 6.6) and accept mail from only those authenticated MTAs.
I've looked into SASL, but as far as I can tell, its use case is for authenticating inbound MUAs or outbound MTAs.
How does one authenticate inbound MTAs using Postfix?
Thanks,
Nathan
EDIT:
From my main.cf:
smtpd_sasl_type = dovecot
smtpd_sasl_path = private/auth
smtpd_sasl_auth_enable = yes
smtpd_sasl_security_options = noanonymous
smtp_sasl_password_maps = hash:/etc/postfix/sasl_passwd
smtpd_relay_restrictions = permit_sasl_authenticated, reject_unauth_destination

Other useful info:
postconf -a
cyrus
dovecot
vim /etc/dovecot/conf.d/10-auth.conf
auth_mechanisms = plain login
master.cf is virginal

A: SASL is the way to go.  Postfix doesn't particularly care of it's an MUA or MTA connecting to it.  If you use smtpd_sasl_auth_enable (along with smtpd_relay_restrictions = permit_sasl_authenticated and a proper SASL configuration), only authenticated connections will be able to use your server as a smarthost relay.  Exchange supports this sort of thing, and it should be what you want.

A: I'm glad you could get it working with Dovecot - I couldn't! Fortunately, I wasn't married to Dovecot. I found this: http://initrd.org/wiki/SMTP_Relay which I followed and succeeded. Just having cert issues, but I'll take that up separately. Thanks again, Doug


text:
Q: ASP.NET anchor tag with runat="server" acting weird I have a strange problem with the page I'm designing.  I have a link like this:

And when I view source on the resulting page I get this:

My goal was to programmatically insert a link if it was applicable to the page in question, and leave a href="#" if it wasn't (basically a blank anchor tag).  However now it will take them to an actual link, which of course doesn't exist.
How can I make it stop doing this?

A: How are you inserting the link? I've just tried the following:

If you do nothing in the code behind the link is rendered as:

and if in the Page_Load you define the href:
protected void Page_Load(object sender, EventArgs e)
{
    asel1.HRef = "../Cards";
}

it will render as:

which other the id mangling is the expected behavior.

A: I know this is an old question, but I too ran into the exact same problem.  In my case the anchor tag was also inside an ASCX file (user control).  I found that if I removed:
runat="server"

then the problem was fixed.

A: I would have replaced the href as following:

A: You are inserting the link dynamically in asp c#, right?
you have to look there for the href and id.
in asp, Control.ClientID value is generated by concatenating the ID value of the control and the UniqueID value of its parent control. That explains how your id is changing.
According to this Each part of the generated ID property is separated by the ClientIDSeparator property value. The value always returns an underscore (_).
That is why you have id="ctl00_ContentMainSection_CardsControl1_asel1"


text:
Q: i want to access the transaction from web panel and directly through developer menu( I want to access my transaction from web panel(send  variables to the transaction ) and I want to access this from the developer menu screen (without variables)

A: How are you?.
Thats is very simple Try with some like this
WebPanel
put in it ONLY a GRID with a several attributes from such TRANSACTION, change the property main=true and Choice option RUN WITH THIS ONLY.
Form more details, you can write to my gmail: @gxsoft
Kind regards,
gab


text:
Q: How to decode json object for database in cakephp 3.0 I am trying to do a new database entry off of a http post request in cakephp 3. In cakephp 3 they are now using entities to manipulate the data. I have a rest api that uses json. I want to take that json data and put it in my database, here is what I am doing -
    public function add() {
    $user = $this->Users->newEntity();
    $user = $this->Users->patchEntity($user, $this->request->data);
    $array = $user->toArray();
    $this->Users->save($user);}

My json data that is being sent in http post -
{"userID":60,"firstname":"Sherbert60","lastname":"Dafflemore60","profilepic":"nada"}
The error I receive -
Error: Call to a member function errors() on array
File /var/app/current/vendor/cakephp/cakephp/src/ORM/Table.php
Line: 1356
Does anyone know what I am doing wrong? Thanks
EDIT -
Read in the docs that cakephp will automatically handle it if it is json, so I changed my code to -
    $user = $this->Users->newEntity($this->request->data);
    if ($this->Users->save($user)) {
        $message = 'Saved';
    } else {
        $message = 'Error';
    }

Now I get a 200 response with no entry into database. I can query the database with no problems.


text:
Q: Find position on a path I am building a 2D game, I got a path of $N$ coordinates where $N$ is a small integer. I calculated the path total length to be $L$, and I decided that I would like to complete the path within some fixed time, so during each frame, I am calculating where my location on the path should be.
Assuming that my location is $fL$ where $f$ is a number between $0$ to $1$, how can I calculate the coordinates of my location?

A: The standard technique here is surprisingly boring. In pseudocode, you write something like this:
preprocessing:
input: pts, an array of N points indicating a piecewise
            linear path.

distances[0] = 0.0;
for i = 1 to N-1
   distances[i] = distances[i-1] + dist(pts[i], pts[i-1]);

L = lengths[N-1]; // total length of the path.

main program:
input:
input: pts, an array of N points indicating a piecewise
            linear path.
       f, a fraction between 0 and 1.
       L, the total length of the path
       distances, an array of distances along the path.

output: q, a point along the path that's f of the way from
       pts[0] to pts[N-1].

target = f * L; // the distance we want to go.
i = 0;
while (lengths[i] < target) i = i + 1;

// Now lengths[i-1] < target <= lengths[i]
u = pts[i-1];
v = pts[i];
h = lengths[i] - lengths[i-1]; // distance between the pts
r = target - lengths[i-1]; // distance still to be covered.
t = r/h; // fraction of the distance from u to v we have to go.
q = (1-t) * u + t * v;

The idea is that if you have 3 points, at distances 0, 3, and 5.5, for a total length of 5.5, and you want to go 70% of the way (f = 0.7), then you compute $0.7 \cdot 5.5 = 3.85$. So you want to get to the point that's at distance 3.85 from the start. You walk the first edge, and use up distance $3,$ and now need to got $0.85$ more. The length of the second edge of your path is $5.5 - 3 = 2.5$, so you need to go $0.85$ of the total distance of $2.5$. That's a fraction $t = 0.85/2.5 = 0.34$ of the distance. To get that, you call the second and third points $u$ and $v$, and compute the point $(1-0.34)u + 0.34 v$, and that's your result.
N.B.

*

*This works in any dimension, not just 2.

*I've made the simplest possible assumption about your path, namely, that it's a sequence of straight line segments. The only simpler assumption --- that you "teleport" from one point to the next, resting at each location in sequence, has the problem that there may be no solution to the problem posed. For instance, if you start at $(0,0)$ and then teleport to $(3, 0)$, what answer should I give for $f = 0.5$? The obvious answer is $(1.5, 0)$, but you were never at that point. In fancier terms, I've assumed a $C^1$ interpolant for your data, because the $C^0$ interpolant doesn't work. If you want a smoother output, you'll need to choose a higher-order interpolant, and spline technology is probably what you're looking for...until you realize what a mess it is. If you go that route, I strongly suggest you consider the Catmull-Rom spline.

*I've tried to answer the question I thought you were asking, but there's a real skill in learning to ask the question you really need answered so that you get what you want, and don't waste others' time. If you look back at your question, you might want to think about "How could I have asked this more usefully?" You might, for instance, have included an example. You might have said "from the input points, I'm assuming a "connect-the-dots" kind of path." Or you might have said "Is there something better than a connect-the-dots path for which this computation is still easy?"


text:
Q: Folder with special characters py2exe In my code, I call a file that is located in a folder called "Física" (please note that the "i" is acute).
I don't have any problem running this in my IDE (Spyder), but after I turn my program into an executable with py2exe I get an error:
"UnicodeEncodeError: 'ascii' codec can't encode character u'\xed'"

The problem is because of these special characters. How can I solve this problem?
I tried to do the following
path = unicode(path).encode('utf-8')

to treat the path with utf-8 encoding. But if I do this my path will be:
F\xc3\xadsica instead of Física

A: I found out what I was doing wrong:
I wanted to read a file from that path, and then write a file to the same path. I was encoding the path in utf-8 when saving it in a variable. However, I was not using the decode when using that variable to write in the path.
I need to use ´encode('utf-8')´ when saving the path to a variable and then use ´decode('utf-8')´ when setting the destination path. Thank you so much and sorry for the poor explanation


text:
Q: UWP URI for making a call I'm working on a UWP app that uses a RichTextBlock to display some text that the user can enter, I want it to Identify phone numbers so that I can tap the number and then the application should take me to the call app or people app and give me the option to call this number. I search for a solution for that and what I found so far is in this link:
https://msdn.microsoft.com/en-us/windows/uwp/launch-resume/launch-default-app
I couldn't find the URI that I can use to make it work, the best thing that I've achieved so far is by using a hyperlink that contains the following:
 if(isPhoneNumber)
       hyper = @"ms-people:savetocontact?PhoneNumber="+hyper+"&Email=&ContactName=";

but now when I tap the number the people app is launched on the contacts list screen.
Any advice would be great, thanks.

A: Try tel:<phone-number> uri scheme. You will get the below page where you can send text message, call or save this number. Eg.:
await Launcher.LaunchUriAsync(new Uri("tel:+36301234567"));


text:
Q: How to keep the same filename in carrierwave when updating a file (in rails) When an image is updated using carrierwave I have it setup to use the model id and original file name
def filename
 "#{model.id}-#{original_filename}" if original_filename.present?
end

Its only like this because its the default way I found when I was setting up carrierwave. Recently I realised if you update an image the link to the image is broken because the filename is updated to use the newer files name. So if a page is linked to the old image it isn't updated with the newer image but instead becomes a broken image link.
I want it to keep the old file name when the image is being updated but cant find how to do this in the documentation and from googling around
Edit
I diddnt add a lot of the 'use case' because I diddnt think the problem was this complicated.
Basically on the site there are items that have images assigned to them. I did see the comment on not using only model.id and @struthersneil cleared up why that comment is there. Considering the images records for an items are created when the item is created they will never be new when the image is being added (because its just updating a record that already exists). Because of this I'd say my best bet is to use just model.id as the filename.
My other option is to keep the old image so the links aren't broken. The main problem for using this is that users create posts on the site and link to these images in the posts (the posts are regularly updated so I cant to a once off cache on the post and images in the post). The images become updated from new information on the items they are associated to. Once this happens the image linked in the post will show outdated information and they will have to manually update to the new image each time. So having the image link stay the same with the image being updated is the best option in this case particular case

A: original_filename in this context is the name of the file that was just received by the uploader. It's the file's original name.
By doing this:
 "#{model.id}-#{original_filename}" if original_filename.present?

You're telling CarrierWave to use the new name of the file every time. It sounds like you want a given model to use the same filename every time. So the obvious option is simply to throw away the original_filename altogether and use the model id by itself.
However, the comment above the filename method in the auto-generated uploader code says this:
  # Avoid using model.id or version_name here, see uploader/store.rb for details.

Which leads us to this...
  # Be careful using record ids as filenames. If the filename is stored in the database
  # the record id will be nil when the filename is set. Don't use record ids unless you
  # understand this limitation.

That is kind of a hitch. Unless you can guarantee that your model always has an id (which won't be true if it's new) then you shouldn't use model.id to name your file.
I would suggest you generate a unique file_identifier string once for each model on initialize (as long as the file_identifier has not already been set), and just use this unique string as your filename, e.g.
class Something < ActiveRecord::Base
  mount_uploader :image, SomeImageUploader

  after_initialize do
    unless self.file_identifier
      self.file_identifier = SecureRandom.hex(32)
    end
  end
end

...and in your uploader class...
def filename
  model.file_identifier if original_filename
end

Now your uploaded image will always overwrite the same file. But notice: you have just lost your image extension. That seems to be fine in my modern version of Firefox (it can guess by the looking at the image header) but it's probably not the most widely compatible solution. You could take the extension of the original_filename and add it on there, but now you're back to your original problem if someone uploads a png and then uploads a jpg (the result would be two different files).
You could perform a conversion to a fixed format of your choice on upload, then the filename + extension would always be the same.
Honestly I think you'd have an easier time if you accept that files get a new name after every upload, and simply leave the old files hanging around for a set period of time to continue supporting users who have the old link. (How old are these links going to get anyway? If it's sitting in a cache, then why cache only the generated HTML without caching the image?) This is especially true if you ever plan to use a CDN service between your application and your users. The usual pattern is to version your files with a new unique filename every time, which the CDN will cache once and forever.


text:
Q: Is it better to add an index and search via the index or add a unique constraint and let an insert fail? I have a table with over 2.5 million records in production that keeps track of if a specific user has already viewed an job:
mysql> DESCRIBE job_views;
+--------------------+--------------+------+-----+---------+----------------+
| Field              | Type         | Null | Key | Default | Extra          |
+--------------------+--------------+------+-----+---------+----------------+
| id                 | int(11)      | NO   | PRI | NULL    | auto_increment |
| job_id             | int(11)      | YES  |     | NULL    |                |
| session_id         | varchar(255) | YES  | MUL | NULL    |                |
| created_at         | datetime     | YES  |     | NULL    |                |
| updated_at         | datetime     | YES  |     | NULL    |                |
+--------------------+--------------+------+-----+---------+----------------+

Before adding a row to the table, I want to ensure that there isn't already a row with the same job_id and session_id. Currently the application queries the table for a row that matches (presently without an index, although an index on the two columns has been added), but I believe a unique constraint makes more sense.
Is there a difference between a SELECT using the index and then an INSERT if a row isn't found versus an INSERT that fails because of a unique constraint? If so, which is preferable (or how can I make that determination)?

A: Use a unique constraint (unique index), this is exactly what they're for.
The difference will be in your code. If you use the unique constraint method, you need to catch the error that the dbms will throw on duplicate entries, but if you check for the value explicitly first, you won't need to catch an error.
However, if you don't use the unique constraint method, you're not really restricting the duplication of the data at the database level, allowing the data to be corrupted easily by another application or even a maintenance script being run by a careless developer or dba.


text:
Q: Mental estimate for tangent of an angle (from $0$ to $90$ degrees) Does anyone know of a way to estimate the tangent of an angle in their head? Accuracy is not critically important, but within $5%$ percent would probably be good, 10% may be acceptable.
I can estimate sines and cosines quite well, but I consider division of/by arbitrary values to be too complex for this task. Multiplication of a few values is generally acceptable, and addition and subtraction are fine.
My angles are in degrees, and I prefer not have to mentally convert to radians, though I can if necessary. Also, all angles I'm concerned with are in the range of [0, 90 degrees].
I am also interested in estimating arc tangent under the same conditions, to within about 5-degrees would be good.
Backstory
I'm working on estimating the path of the sun across the sky. I can estimate the declination pretty easily, but now I want to estimate the amount of daylight on any given day and latitude. I've got it down to the arc cosine of the product of two tangents, but resolving the two tangents is now my sticking point. I also want to calculate the altitude of the sun for any time of day, day of the year, and latitude, which I have down to just an arc tangent.

A: Consider trivial trig identity:
$$\tag 1\tan(a+b) = \frac {\tan a + \tan b}{1-\tan a\tan b} $$
Now substitute:
$$\tan a = N_1/D_1$$
$$\tan b = N_2/D_2$$
So 1 becomes:
$$\tag 2\tan(a+b) =\frac {N_1D_2+N_2D_1}{D_1D_2-N_1N_2}$$
$$\tag 3\tan(a-b) =\frac {N_1D_2-N_2D_1}{D_1D_2+N_1N_2}$$
And use this "magic hash table":
$$\tan 26.57^\circ = 1/2$$
$$\tan 18.43^\circ = 1/3$$
$$\tan 14.04^\circ = 1/4$$
$$\tan 11.31^\circ = 1/5$$
And a following useful identities for small angels in radians
$$\tan a = a,  |a| <0.05 (3.0 ^\circ) $$
And for angles more than $45^\circ$
$$\tan a = 1/\tan(90°−a)$$
You can also recursively repeat this process to get more and more precious approximation then:
$$a_i=a_{i-1}\pm b_{i-1}$$
$$\tag 4  \tan b_i=b_i=x - a_i$$
Where $a_0$ and $b_0$ picked from the table and $x$ is initial angle value
While evaluating $(4)$ you need conversion to radians. It is simply multiplication on $7/400$ So you need to aproximate $x-a_i$ with such fraction what it has $7$ in denominator and/or dividers of $400$ in numerator.
Google for "Fast_Approximation_of_Elementary_Functions.pdf" paper for further information on this trick. Direct link is prohibitted for some strange reason.
P.S. Drawing for using instead of remebering the hash table and for fast picking of $a_0$ $b_0$:

P.P.S. To remember $(2)$ consider product of two complex numbers
$$z=(D1,N1)(D2,N2)$$
so $(2)$  becomes:
$$\frac {\Im z}{\Re z}$$
to get $(3)$ just swap signs

A: Because of the numerical coincidence that $(\pi/180)^2/3$ is nearly $10^{-4}$, the Taylor polynomial $\tan x \approx x+x^3/3$ becomes nearly
$$\tan(y {\rm\ deg}) \approx .017y(1+10^{-4}y^2)$$
which seems to be accurate within 5 percent up to about 38 degrees, and within about 8 percent up to 45 degrees. Beyond 45 degrees I don't know what to do unless you can divide as in $\tan x = 1/\tan(\pi/2-x)$.

A: This may not be the best for in-your-head calculation, but for $x$ in degrees
$$
\tan\left(\frac{\pi x}{180}\right)\approx\frac{x(990-4x)}{(90-x)(630+4x)}\tag{1}
$$
is at most $0.6\%$ off for $0\le x\le90$.
Here is a plot of the relative error:$\displaystyle\left.\frac{x(990-4x)}{(90-x)(630+4x)}\middle/\tan\left(\frac{\pi x}{180}\right)-1\right.$ :
$\hspace{2cm}$
Equation $(1)$ looks a little daunting, but at least $x$ is in degrees, and the relative error is quite small. Really, the only constant that needs to be remembered for $(1)$ is $\frac{990}{4}$; that is,
$$
P(x)=x\left(\frac{990}{4}-x\right)\implies\tan\left(\frac{\pi x}{180}\right)\approx\frac{P(x)}{P(90-x)}\tag{2}
$$

A: For $\theta = \frac{180^{\circ}}{\pi}\arctan x$ you can use:
$$\theta \approx \frac{180x}{3+x} \quad \mathrm{for} \quad 0 \leq x \leq 1$$
$$\theta \approx 90^{\circ}- \frac{180}{3x+1} \quad \mathrm{for} \quad  x > 1$$
where $\theta$ is measured in degrees.

A: If you want to stay within 10%, the following piecewise linear function satisfies $$.9\tan\theta \le y \le 1.1\tan\theta$$ for $0\le\theta\le60$ degrees:
$$y={\theta\over60}\text{ for }0\le\theta\le20$$
$$y={2\theta-15\over75}\text{ for }20\le\theta\le45$$
$$y={\theta-20\over25}\text{ for }45\le\theta\le60$$
It might help to rewrite them as
$$y={5\theta\over300}\text{ for }0\le\theta\le20$$
$$y={8\theta-60\over300}\text{ for }20\le\theta\le45$$
$$y={4\theta-80\over100}\text{ for }45\le\theta\le60$$
so that you really don't have to divide by anything other than $3$.  The line segment approximations lie above $\tan\theta$ from $\theta\approx25$ to $\theta=45$ and below it elsewhere, so you should round down and up accordingly when doing the mental arithmetic.It's obviously possible to extend this for angles greater than $60$ degrees, but whether (or how far) you can do so with formulas that use only "simple" multiplications and divisions is unclear.
A word of explanation:  What I tried to do here was take seriously the OP's request for estimates you can calculate in your head.  The ability to do mental arithmetic, of course, varies from person to person, so I used myself as a gauge.  As for where the formulas came from, my starting point was the observation that the conversion factor between degrees and radians, $180/\pi$, is approximately $60$, so the estimate $\tan\theta\approx\theta/60$ should be OK for a while.  A little trial and error showed it's good up to $\theta=20$ degrees (since $.9\tan20\approx.328$).  It was easy to see that connecting $(0,0)$ to $(20,1/3)$ and $(20,1/3)$ to $(45,1)$ with straight lines would stay within the prescribed bounds.  Finally, noting that $.9\tan60\approx1.55$, I saw that the line connecting $(45,1)$ to $(60,1.6)$ would have a nice slope and stay within the prescribed bounds as well.

A: This is probably way too simplistic, but I think of it literally as "slope". In other words, if you have an angle with a leg on the positive x-axis, the line that is tangent to the angle (thinking of tangent literally like the tangent to a circle) is the other leg of the angle, and the slope $\frac{y}{x}$ of this line, is the value of the trigonometric tangent function.
So if you have ways to estimate slope (there are simple tools for this), you can use that as a tangent estimate as long as you can frame your problem in a context in which "slope" makes sense. Ultimately, though, this is just a guessing / eyeballing / memorization method, but if you do memorize a few reference values ($45^\circ$ an obvious one), I think it is possible without an extreme amount of rote memorization to make very rough estimates. For more accuracy, or at least a cross-reference, could make a similar triangle, estimate a ratio for the legs directly, and perform the single division.

A: We have $\tan(x) = \frac{1}{\cot(x)}$, so split $[0,\frac{\pi}{2}]$ into 4 invervals of length $\frac{\pi}{8}$ and then use
\begin{align}
f_1(x) &= x & f_2(x) &= -0.19+1.5x \\
f_3(x) &= \frac{1}{f_2(\frac{\pi}{2}-x)} & f_4(x) &= \frac{1}{f_1(\frac{\pi}{2}-x)}
\end{align}
Functions $f_1$ and $f_4$ have relative error of $6\%$ while $f_2$ and $f_3$ about $4\%$, see: here, here, here and here.
I know this is in radians and contains division, but it still might help ;-)

A: The function
$$f(x):={{3\over2}x-{1\over100}x^2\over 90-x}$$
produces a relative error which is  less than $6\%$ over the whole range $[0,{\pi\over2}[\ $. See the following figure:


text:
Q: How to fix "No Log4j 2 configuration file found" in Netbeans? I am trying to configure Log4j2 in Netbeans.
I have used following code:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class App
{
    public static void main( String[] args ) {
        Logger logger = LogManager.getRootLogger();
        logger.trace("Configuration File Defined To Be :: "+System.getProperty("log4j.configurationFile"));
    }
}

When i right click and run i am getting following error message:
ERROR StatusLogger No Log4j 2 configuration file found. Using default configuration (logging only errors to the console), or user programmatically provided configurations. Set system property 'log4j2.debug' to show Log4j 2 internal initialization logging. See https://logging.apache.org/log4j/2.x/manual/configuration.html for instructions on how to configure Log4j 2
BUILD SUCCESSFUL (total time: 2 seconds)

currently, My project structure looks like below: (Netbeans project)

As suggested by related questioners, I am trying to make src/main/resources and put configuration file under same and also tried to put it under src(source packages) but unable to fix that error. Kindly help me.

A: Try changing name of configuration file to log4j2.xml
By default, log4j2 searches for file with name log4j2 on application classpath (under src/main/resources/ directory)


text:
Q: php not returning variable for display I have a html/php that queries a database and downloads the results to a csv file.  That part works fine.  But, I want to display the text of the variable $message in the text box of the html page.  If I do not do the fputcsv section, it works.  But I cannot get it to display if the file gets downloaded.  Any help is appreciated.
<?php

include('members.db.inc.php');

$mysqli = new mysqli($dbhost, $dbuser, $dbpass, $dbname);

if(isset($_POST['Info_Verify'])){
$message1="Export Information Verification.";
ExportFile ("Information_Verification");
$message = $message1;
}

if(isset($_POST['Members'])){
$message="Export Member Import List.";
ExportFile ("Member_Import_List");
}
if(isset($_POST['GMail'])){
$message="Export Gmail Import List.";
ExportFile ("GMail_Import_List");
}

function ExportFile($temp) {

//echo $temp;
$error = 0;
$filename = $temp . ".csv";
$sql = sprintf("Select * from " . $temp);
//print $sql . '
';

$result = DBi::$conn->query($sql);
if (!$result) die('Couldn\'t fetch records'. DBi::$conn->connect_error) . '
';

$headers = $result->fetch_fields();

foreach($headers as $header) {
    $head[] = $header->name;
}

$fp = fopen('php://output', 'w');
if ($fp && $result) {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename=' . $filename);
    header('Pragma: no-cache');
    header('Expires: 0');
    fputcsv($fp, array_values($head));
    while ($row = $result->fetch_array(MYSQLI_NUM)) {
        fputcsv($fp, array_values($row));
        }
    fclose($fp);
    exit;
    }
}

?>

<title>Export Information</title>

<form name="Export_Form" action="<?php echo $_SERVER['PHP_SELF']; ?>"     method=post>
<input type="text" name="txt" value="<?php if(isset($message)){ echo $message;}?>" style="width: 688px" >

<input type="submit" name="Info_Verify" value="Information Verification">

        House_Number,Street_Name,Member_Name,Phone_Number_1,Phone_Number_2,Zip_Code,Email1,EMail2,Communication_Code,Hide_Information

<input type="submit" name="Members" value="Members" >
        "Home Address",Name,"Home Phone","Home Phone
        2","E-Mail Address","E-Mail 2 Address",Categories"

<input type="submit" name="GMail" value="GMail Export" >
        Name,"E-mail Address","E-mail 2
        Address",Categories

</form>


text:
Q: how deep can a url be in angular? i'm trying to learn angular's routing basics and I'm fighting with a strange issue.
The problem is that I can't use more than two levels of features to obtain a url like this 'localhost:4200/teams/settings/people'.
People also is a module cause my intent is to configure other child components like 'home','details',...
I don't know if is it possible but I'have configured the last module just like 'teams' and 'settings' but when I navigate to 'localhost:4200/teams/settings/people' the app goes to root position.
I'm thinking about a limit on child features, It is possible?
In angular docs I haven't found any information on this particular case.
app-routing.module.ts:
const routes: Routes = [
  {path:'teams',component:TeamsComponent},
  {path:'**',redirectTo:'easynow',pathMatch:'full'}
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

app.module.ts:
@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    TeamsModule,
    AppRoutingModule
  ],
  exports:[AppRoutingModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

teams-routing.module.ts:
const routes: Routes = [
  {path:'teams',component:TeamsComponent,children:[
    {path:'settings',component:SettingsComponent}
  ]}
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class TeamsRoutingModule { }

teams.module.ts:
@NgModule({
  declarations: [TeamsComponent],
  imports: [
    CommonModule,
    SettingsModule,
    TeamsRoutingModule
  ],
  exports:[TeamsRoutingModule]
})
export class TeamsModule { }

setings-routing.module.ts
const routes: Routes = [
  {path:'settings',component:SettingsComponent,children:[
    {path:'people',component:PeopleComponent}
  ]}
];

@NgModule({
    imports: [RouterModule.forChild(routes)],
    exports: [RouterModule]
 })
 export class SettingsRoutingModule { }

settings.module.ts:
@NgModule({
  declarations: [SettingsComponent],
  imports: [
    CommonModule,
    PeopleModule,
    SettingsRoutingModule
  ],
  exports:[SettingsRoutingModule]
})
export class SettingsModule { }

peope-routing.module.ts:
const routes: Routes = [
  {path:'people',component:PeopleComponent,children:[

  ]}
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class PeopleRoutingModule { }

people.module.ts:
@NgModule({
  declarations: [PeopleComponent],
  imports: [
    CommonModule,
    PeopleRoutingModule
  ],
  exports:[
    PeopleRoutingModule
  ]
})
export class PeopleModule { }

All components looks like this:

Component Name

<router-outlet></router-outlet>

this is my output (http://localhost:4200/teams/settings):
Sitename
teams works!

settings works!

when I try to navigate (http://localhost:4200/teams/settings/people) I return to the root component.
EDIT 1:
I didn't understand the routing module well.
Now I understand that when there are routing modules engaged that are not lazy, it is necessary to repeat the path regularly as I was suggested or, if it is lazy, only the last part of the path that is hung on the previous routing module.
However the problem was solved.

A: You have to repeat the complete path to the route you want to add in each module (meaning from root on).
To solve your problem you would have to change your settings.routing.module.ts to
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { TeamsComponent } from '../teams.component';
import { SettingsComponent } from './settings.component';
import { PeopleComponent } from './people/people.component';

const routes: Routes = [
   {path:'teams',component:TeamsComponent,children:[
  {path:'settings',component:SettingsComponent,children:[
    {path:'people',component:PeopleComponent}
  ]}
  ]}
];

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})
export class SettingsRoutingModule { }

Here is the working Stackblitz
In order to not repeat the configuration each time somebody has written a neat article


text:
Q: Array storing Any objects is also of AnyObject type let f: () -> Void = { }

let array = ["a", 1, false, f] as [Any]

if array[3] is AnyObject {
  print(array[3])
}

Why is the element evaluating to true for AnyObject even though the array is set to store Any?
Why is function evaluates to true as an AnyObject even though AnyObject by definition can only be classes?
As another example:
let f: () -> Bool = { return true }
let ff = f as AnyObject
(ff as () -> Bool)()

This goes against the definition of AnyObject in the API doc, which states that:

AnyObject can be used as the concrete type for an instance of any
class, class type, or class-only protocol.

or the official Swift Programming Language Guide:

• Any can represent an instance of any type at all, including function
types.
• AnyObject can represent an instance of any class type.

In the above example, it looks like function can be representated as AnyObject.
There is explanation elsewhere in SO (as pointed out by @hamish) that internally because SwiftValue class is used, anything can be bridged to AnyObject. The logic of explanation seems to be flawed/reverse, as we should make implementation conform to the language definition, not the other way around, so either the implementation is incorrect, or the definition of AnyObject and typecheck operator is incorrect?

A: First, the Swift Programming Language Guide is a not a language specification in the way that ISO 9899 defines C. (And even given an ISO standard, not every compiler implements C identically, or even in 100% accordance with the standard.) If you find a disagreement between the compiler and the documentation, it is just as likely to be a documentation bug as a compiler bug.
That said, I believe you've glossed over an important part of the spec you reference:

AnyObject can also be used as the concrete type for an instance of a type that bridges to an Objective-C class. Many value types in Swift bridge to Objective-C counterparts, like String and Int.

() -> Void is equivalent to dispatch_block_t, which bridges to ObjC as a dispatch_object (see dispatch/object.h and os/object.h):
/*
 * By default, dispatch objects are declared as Objective-C types when building
 * with an Objective-C compiler. This allows them to participate in ARC, in RR
 * management by the Blocks runtime and in leaks checking by the static
 * analyzer, and enables them to be added to Cocoa collections.
 * See <os/object.h> for details.
 */
OS_OBJECT_DECL_CLASS(dispatch_object);

So there is no surprise here that () -> Void can be coerced into AnyObject.
In practice, pretty much anything can now bridge into AnyObject (again, from a language specification point of view, anything that can be an NSValue can be an AnyObject, even though that's not exactly how it's implemented).
AnyObject is different than Any, however. Any behaves like a protocol (despite not being a protocol). AnyObject behaves like the superclass of every class (despite actually being a protocol).
let b = true                         // true
let bany = true as Any               // true
let banyobj = true as AnyObject      // 1 <=== (because it's NSNumber)

MemoryLayout.size(ofValue: b)        // 1 (size of a bool)
MemoryLayout.size(ofValue: bany)     // 32 (size of a protocol box)
MemoryLayout.size(ofValue: banyobj)  // 8 (size of a reference pointer)

type(of: b)                          // Bool.Type
type(of: bany)                       // Bool.Type
type(of: banyobj)                    // __NSCFBoolean.Type

(Try the same thing for {} to see how closures are handled.)
It is reasonable to open a defect against the AnyObject docs to include a more explicit explanation that any type can be converted into a reference type using as AnyObject, but this is just an omission, not a contradiction of what's already there. (And if it were a contradiction, or you find it confusing, then again, the correct answer is to open a defect to improve the docs to match Swift, not Swift to match the docs.)