Q:

Android - RecyclerView spacing between items in a Grid

In my Android app I'm using a RecyclerView to display items in a grid by using a GridLayoutManager.
In a GridView, in order to specify the spacing between elements, I would set the horizontalSpacing and verticalSpacing properties.
So, how can I do the same on a RecyclerView?

A:

I haven't tested it with a GridLayout but for a LinearLayout, I simply set a margin to each listitem's root layout. I guess if you want the same space between all items (let's say 8dp), you would have to do this:

Set layout_padding 4 dp to the RecyclerView.
Set layout_margin 4 dp to each listitem.

This way you would have a constant 8 dp around every item.

The code below is a horizontal RecyclerView that displays images with a correct spacing of 8 dp:
<!-- fragment_layout.xml -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="4dp">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layoutManager="android.support.v7.widget.LinearLayoutManager"
        tools:listitem="@layout/list_item" />

</LinearLayout>

<!-- list_item.xml -->
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_margin="4dp">

    <ImageView
        android:layout_width="@dimen/thumbnail_size"
        android:layout_height="@dimen/thumbnail_size"
        android:contentDescription="@string/image_content_desc" />

</LinearLayout>

EDIT: I realised that the item view need to have a parent ViewGroup, so I updated the snippet.

A:

you have to use a ItemDecorator for that:
like this:
public class EqualSpaceItemDecoration extends RecyclerView.ItemDecoration {

    private final int mSpaceHeight;

    public EqualSpaceItemDecoration(int mSpaceHeight) {
        this.mSpaceHeight = mSpaceHeight;
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent,
                               RecyclerView.State state) {
        outRect.bottom = mSpaceHeight;
        outRect.top = mSpaceHeight;
        outRect.left = mSpaceHeight;
        outRect.right = mSpaceHeight;
    }
}


Q:

use subscript operator on a second rank pointer

I'm confused with a problem about the pointer and array in C.
Let's see a piece of code first:
//case 1
int **a;
a = (int **)malloc(sizeof(int*)*m);
for(i = 0; i < m; i++)
    a[i] = (int *)malloc(sizeof(int)*n);

//case 2
int b[m][n];

then, we known that, the layout of b in memory is as follow:
b[0][0] b[0][1] ... ... b[m-1][n-1]

and, the layout of a in memory is as follow:
a
 \
 _\|
 a[0]  a[1] ... a[m-1]
  |    |
  |    |
  |   \|/
  |   a[1][0] a[1][a] ... a[1][n-1]
 \|/
a[0][1] a[0][2] ... a[0][n-1]

so, my question is: since a[0..m-1][0..n-1] is stored in memory inconsecutively, why we can use subscript operator [] on a? In other words, why a[i][j] can get the correct element, just as b[i][j] do?

A:

That's because a[i][j] equals to *(*(a+i) + j). Even though a is not consecutively stored (possibly), the pointer *(a+i) will exactly point to the right place (where a[i][0] is stored).

A:

The compiler processes each part of an expression individually. The primary difference between a[i][j] and b[i][j] is that, since a is a pointer to pointers to int, the address calculation for a[i] counts a number of pointers, but, since b is an array of arrays of int, the address calculation for b[i] counts a number of arrays. C uses the type of each part of the expression to determine how to evaluate it.
The steps for interpreting a[i][j] are:

a is a pointer to a pointer to an int.
a[i] is defined to be *(a + i).
The sum a+i is i elements beyond where a points. Since a points to pointers to int, we count i pointers to int to determine the new address.
Since the sum is a pointer to a pointer to an int, applying * to it yields a pointer to an int.
a[i][j] is defined to be *(a[i] + j). We have already evaluated the a[i] part.
The sum a[i] + j is j elements beyond where a[i] points. Since a[i] points to int objects, we count j int objects to determine the new address.
Since this sum is a pointer to an int, applying * to it yields an int.

The steps for interpreting b[i][j] are:

b is an array of m arrays of n int.
Since b is an array, it is converted to a pointer to its first element, an array of n int.
b[i] is defined to be *(b + i).
The sum b + i is i elements beyond where b points. Since b has been converted to a pointer to arrays of n int, we count i arrays of n int to determine the new address.
Since the sum is a pointer to an array of n int, applying * to it yields an array of n int.
Since this expression is another array, it is converted to a pointer to its first element, an int.
b[i][j] is defined to be *(b[i] + j). We have already evaluated the b[i] part.
The sum b[i] + j is j elements beyond where b[i] points. Since it points to int, we count j int to determine the new address.
Since this sum is a pointer to an int, applying * to it yields an int.


Q:

Having trouble using date for an interest calculate

I need a little logic help as well as some code help.
I'm writing a program that is suppose to be a simple ATM program. It will do deposits Withdrawals And a balance check.
I also have to have my program record the date of every deposit, and use that date when calculating 5% interest for when the user checks their balance. The part im having problems with is the part where I need to store the deposit amount as well as the date that corresponds to that deposit. I'm supposed to use the GregorianCalender methods. Im just taking a shot in the dark but I think I would use an array for this. But im clueless as to how to implement it. Because I'm new to arrays.
and once I get a date, when checking the balance I need to check how many months its been since the deposit of that amount to calculate interest. Sorry its a pretty elaborate question but I'm a newbie and this is the most complicated thing ive ever written.
 public void printDeposit(){
    Calendar c = new GregorianCalendar();
    BigDecimal depositamt;
    Date date = c.getTime();

    int menuselection;
    System.out.println("Press 1 to deposit, zero to return to the main menu.");
    Scanner sc = new Scanner (System.in);

    menuselection = sc.nextInt();
            if (menuselection==1){
                System.out.println("Please enter the amount: " + date);
                depositamt = sc.nextBigDecimal();
                Transaction tran = new Transaction(depositamt, date);

    }

public class Transaction {

BigDecimal amt;
Date date;

public Transaction(BigDecimal amt, Date date) {
    this.amt = amt;
    this.date = date;

}

A:

You should use ArrayList instread of arrays here, but more to the point, you should aim to use a databasehere, even if it is just an in-memory temporary database.  Also, the printDeposit method is badly named; that would probably correspond to printing a deposit receipt.  You'd want your logic to be something like:
Console console = System.getConsole();
if (console == null) {System.exit(42)}
while(true) (
    String option = console.readLine("What would you like to ask this ATM? %d to Quit, %d to deposit, %d to withdraw:", 0, 1, 2;
    switch (option) {
      case "1": acceptDeposit(); break;
      case "2": acceptWithdrawl(); break;
      case "0": quit(); break;
      default: break;
    }
}

Now, you need to write the acceptDeposit and acceptWithdrawl methods.  In database terms, you'd want a balance table and a transaction table.  In Java terms, you'd want classes like this:
public class Transaction {
    enum Type {DEPOSIT, WITHDRAWL, INTEREST};
    private Long userId;
    private Type type;
    private BigDecimal amount;
    private Date date;  // Switch to Joda-Time or its Java 8 equivalent when you can.
    // getters, setters, etc.
    public getBalanceChange() {
        if (type != WITHDRAWL) {
            return amount;
        } else {
            return amount.negate();
        }
    }
}

Do you see why you want the user id?
Your application would have a list of transactions, and uneless you keep a map that maps user ids to balances, you'd want a balance method:
public BigDecinmal balance(Long userId) {
    BigDecimal balance = new BigDecimal("0.00");
    for (Transaction t: transactionList) {
        if (userId.equals(t.getUserId())) {
            balance = balance.add(t.getBalanceChange());
        }
    }
}

With a database table, you'd do an UPDATE to the database.  Were this app running continually, you'd schedule jobs to compute interest, probably using the Java Quartz library.  For a student application, you'd simulate it by having a method:
private void applyInterest(Date from, Date to){...}

In fact, that's an argument against using GregorianCalendarand getting one for the time of each transaction; in practical use, each session will be part of a single day.  Instead, have a Date currentDate and a Date interestLastApplied variable, and bump currentDateup periodically.


Q:

If the roots of $ax^2+bx+c=0$ are of the form $\frac{m}{m-1}$ and $\frac{m+1}{m}$ then find..

Problem :
If the roots of $ax^2+bx+c=0$ are of the form $\frac{m}{m-1}$ and $\frac{m+1}{m}$ then find the value of $(a+b+c)^2$
My approach :
Let $\alpha, \beta$ are the two roots of the given equation.
then
$\frac{1}{\alpha}+\beta =2$
Also we know that sum of the roots $= \frac{-b}{a}$ and product of the roots $\frac{c}{a}$
but how to find $(a+b+c)^2$ not getting any idea further please help thanks.

A:

Say the roots are $\frac{m}{m-1}$ and $\frac{m+1}{m}$.
Then we have that,
$$\frac{m}{m-1}+\frac{m+1}{m}=-\frac{b}{a}$$
$$\frac{m}{m-1}\cdot \frac{m+1}{m}=\frac{c}{a}$$
So we can conclude that
$$\frac{2m^2-1}{m(m-1)}=-\frac{b}{a}$$
$$\frac{m+1}{m-1}=\frac{c}{a}$$
So we can write that
$$(a+b+c)^2=a^2(1+\frac{b}{a}+\frac{c}{a})^2$$
$$=a^2\left[1-\frac{2m^2-1}{m(m-1)}+\frac{m+1}{m-1}\right]^2$$
$$=a^2\left[\frac{m^2-m-2m^2+1+m^2+m}{m(m-1)}\right]^2$$
$$=\left[\frac{a}{m(m-1)}\right]^2$$
Now, again we can write that $$(x-\frac{m}{m-1})(x-\frac{m+1}{m})=0$$
$$x^2-(\frac{m}{m-1}+\frac{m+1}{m})x-\frac{m+1}{m-1}=0$$
$$m(m-1)x^2-(2m^2-1)x-(m^2+m)=0$$
By comparison with $ax^2+bx+c=0$, we can say that $a=rm(m-1)$.
So we have that $$(a+b+c)^2=r^2$$
See if you can progress any far with this result.


Q:

VI Editor on Ubuntu using VIM Short Cuts?

I installed Ubuntu and I tried to use the terminal's vi editor.   The editor is using a different set of short cut keys that I'm not familiar with.  Someone told me it's probably using the VIM short cut keys.
How do I make it use the normal vi short cut keys?   For example, I want
i - insert
:q - quit
etc...
How do I tell vi to use this set of commands instead of vim?
Another problem:  For example, when I hit "back space", I expect vi to Delete, instead of just move the cursor back.  When I hit the arrow keys, random letters show up.  There are other really quirky things like this that i'm not use to because I've been using the "normal" vi editor.

A:

Update:
From what you said about the backspace and the arrow keys, that sounds like it could be the terminal, not the editor.  So your editor is not getting the right keys.  Are using a particular xterm? are you on the same machine? Are you using screen?

Vi and VIM should have the same shortcuts.  Are you sure you are not using an Emacs editor like nano ( the ubuntu default).  That would have shortcuts like ctrl-x to exit.
What does 'echo $EDITOR' from the shell tell you?

A:

You may be using a different clone or a cut down version of vim.  Ubuntu by default uses vim-tiny if I remember correctly.  You can find out which one is being used by checking the link "/etc/alternatives/vi"**.  If it points to /usr/bin/vim.tiny you have a very minimal vim installed.  If it points to some other file you can use "dpkg -S filename" to figure out where it came from.
To install a different "clone" use apt-get or another package management tool.  I suspect that vim-gnome or vim-full may more to your liking.  If one or both of the above are already installed but you have the link
** Many utilities and programs like mail, vi, java, awk, etc. are linked through /etc/alternitives/.  For example on my system /usr/bin/cc is a link to /etc/alternatives/cc which is a link to /usr/bin/gcc.  This allows a common set of tool names to be used with different packages that provide the same functionality.
I hope this helps


Q:

Biztalk set WCF MessageHeaders in Biztalk message assignment

I'm trying to set the MessageHeader of a message that my Biztalk orchestration is sending to WCF. The Message Contract looks as follows in the WCF project.
 [MessageContract(IsWrapped = true, WrapperName = "PerformTransformationRequestWrapper", WrapperNamespace="http://www.iasreo.com/integration/servicetypes")]
public class PerformTransformationRequest
{
    [MessageHeader(Namespace = "http://www.iasreo.com/integration/servicetypes")]
    public string Version { get; set; }
    /// <summary>
    ///
    /// </summary>
    [MessageHeader(Namespace = "http://www.iasreo.com/integration/servicetypes", MustUnderstand = true)]
    public TransformType TransformType { get; set; }

    /// <summary>
    ///
    /// </summary>
    [MessageBodyMember(Namespace = "http://www.iasreo.com/integration/servicetypes")]
    public System.IO.Stream Payload { get; set; }
}

TransformType.cs
[DataContract(Namespace = "http://www.iasreo.com/integration/servicetypes")]
public enum TransformType
{
    /// <summary>
    /// Transform to Excel
    /// </summary>
    [EnumMember]
    ExcelTransform = 1,

    /// <summary>
    /// Transform to PDF
    /// </summary>
    [EnumMember]
    PDFTransform = 2
}

I'm creating the message to send to Biztalk in a Message Assignment shape and that code looks as follows:
xmlDoc = new System.Xml.XmlDocument();
xmlDoc.LoadXml(@"<ns0:PerformTransformationRequestWrapper xmlns:ns0=""http://www.iasreo.com/integration/servicetypes""><ns0:Payload>GpM7</ns0:Payload></ns0:PerformTransformationRequestWrapper>");

PerformTransformationRequest = xmlDoc;

xpath(PerformTransformationRequest, "/*[local-name()='PerformTransformationRequestWrapper' and namespace-uri()='http://www.iasreo.com/integration/servicetypes']/*[local-name()='Payload']") = System.Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(Input.OuterXml));

How can I set the Version and TransformType that MessageHeaders in the WCF MessageContract?

A:

You can set the promoted WCF.OutboundCustomHeaders property of the outgoing message
OutboundMessage(WCF.OuboundCustomHeaders) = "...";

You need to supply the complete WCF Header string as the parameter.
This http://bencode.net/biztalk-custom-wcf-behaviour might be of use to you.


Q:

How do I make curl ignore the proxy?

How do I make curl ignore the proxy?
Setting $NO_PROXY doesn't seem to work for me.

A:

If your curl is at least version 7.19.4, you could just use the --noproxy flag.
curl --noproxy "*" http://www.stackoverflow.com

From the manual.

A:

I ran into the same problem because I set the http_proxy and https_proxy environment variables. But occasionally, I connect to a different network and need to bypass the proxy temporarily. The easiest way to do this (without changing the environment variables) is:
curl --noproxy '*' stackoverflow.com

From the manual: "The only wildcard is a single * character, which matches all hosts, and effectively disables the proxy."
The * character is quoted so that it is not erroneously expanded by the shell.

A:

I assume curl is reading the proxy address from the environment variable http_proxy and that the variable should keep its value. Then in a shell like bash, export http_proxy=''; before a command (or in a shell script) would temporarily change its value.
(See curl's manual for all the variables it looks at, under the ENVIRONMENT heading.)


Q:

How to prevent image disappear when another image is dropped on it

I want to create page where I can move images between divs. I can move images over other divs and back. The problem is that if I move one image over another, the "another" image disappear. I am looking for some way to prevent this.

    function allowDrop(event)
    {
        event.preventDefault();
    }
    function drag(event)
    {
        event.dataTransfer.setData("text", event.target.id);
    }

    function drop(event)
    {
        event.preventDefault();
        var imgData = event.dataTransfer.getData("text");
        event.target.appendChild(document.getElementById(imgData));
    }

CodePen here
I expect that if I move image over another image, it will not move but stay in div where it is currently located.
Thank you for your time.

A:

You need to clone the original element and create a new node, otherwise it will just moved over.
function allowDrop(event)
{
  event.preventDefault();
}
function drag(event)
{
  event.dataTransfer.setData("text", event.target.id);
}

function drop(event)
{
  event.preventDefault();
  var imgData = event.dataTransfer.getData("text");
  var newNode = document.getElementById(imgData).cloneNode(true);

  clearChildren(event.target);
  event.target.appendChild(newNode);
}

function clearChildren(el) {
  while (el.firstChild) {
    el.removeChild(el.firstChild);
  }
}


Q:

My iOS app suddenly starts force closing immediately

I have developed an iOS app using libGDX. It is compiled and deployed with the help of Xamarin.iOS, and runs using the Mono framework.
When deploying to my test iPad (a physical iPad, not a simulator), it works great for a while. But after a while (this time, about 12 hours and 5-10 launches), it stops working. When I try to launch it now, it force closes immediately.
When I click the app icon on the iPad, the icon expands and fills the screen (like all apps does when I start them on the iPad), but once the screen has gone black, the app just closes and returns to the iOS menu. No error messages.
The app has been deployed with "Release|iPad".
Any ideas of what could be wrong, or how I can get hold of error messages/logs or something that can help me figure it out?

A:

Xcode > Organizer > Device Logs.
BTW, this article will you understand the meaning of log:
https://developer.apple.com/library/ios/technotes/tn2151/_index.html


Q:

Core Data - get/create NSManagedObject performance

I'm creating an iphone/ipad app that basically reads XML documents and creates tableviews from objects created based on the xml. The xml represents a 'level' in a filesystem. Its basically a browser.
Each time i parse the xml documents i update the filesystem which is mirrored in a core-data sqllite database. For each "File" encountered in the xml i attempt to get the NSManagedObject associated with it.
The problem is this function which i use to get/create either a new blank entity or get the existing one from database.
+(File*)getOrCreateFile:(NSString*)remotePath
        context:(NSManagedObjectContext*)context
 {
        struct timeval start,end,res;
        gettimeofday(&start,NULL);
        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"File" inManagedObjectContext:context];
        [fetchRequest setEntity:entity];
        [fetchRequest setFetchLimit:1];
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"remotePath == %@",remotePath];
        [fetchRequest setPredicate:predicate];

        NSError *error;
        NSArray *items = [context executeFetchRequest:fetchRequest error:&error];
        [fetchRequest release];

        File *f;
        if ([items count] == 0)
            f = (File*)[NSEntityDescription insertNewObjectForEntityForName:@"File" inManagedObjectContext:context];
        else
            f = (File*)[items objectAtIndex:0];

        gettimeofday(&end, NULL);
        [JFS timeval_subtract:&res x:&end y:&start];
        count++;
        elapsed += res.tv_usec;
        return f;

}
For eksample, if i'm parsing a document with 200ish files the total time on a iPhone 3G is about 4 seconds. 3 of those seconds are spent in this function getting the objets from core data.
RemotePath is a unique string of variable length and indexed in the sqllite database.
What am i doing wrong here? or.. what could i do better/different to improve performance.

A:

Executing fetches is somewhat expensive in Core Data, though the Core Data engineers have done some amazing work to keep this hit minimal. Thus, you may be able to improve things slightly by running a fetch to return multiple items at once. For example, batch the remotePaths and fetch with a predicate such as
[NSPredicate predicateWithFormat:@"remotePath IN %@", paths];

where paths is a collection of possible paths.
From the results, you can do the searches in-memory to determine if a particular path is present.
Fundamentally, however, doing fetches against strings (even if indexed) is an expensive operation. There may not be much you can do. Consider fetching against non-string attributes, perhaps by hasing the path and saving the hash in the entity as well. You'll get back a (potentially) larger result set which you could then search in memory for string equality.
Finally, do not make any changes without some performance data. Profile, profile, profile.


Q:

C++ Counting number of objects in a tree structure

I am trying to perform the following.

I have two classes A and B, A is a superclass of B.
A can have children, but B  can't.
A1 has children B1 and A2 and A2 has children B2 and B3.
A1->descendants() should return the number of objects "under" A1, that is 4.

However, it keeps on returning 2. Can anyone help? Code:
#include <iostream>
#include <vector>

using namespace std;

class B;

class A{
public:
    string name;
    vector<A*> children;
    int n=0;

   A(string aName){
        this->name=aName;
    }

    void addChild(A* aChild){
     children.push_back(aChild);
   }

   int descendants(){
       if(children.size()==0){
           n=0;
       }else{
           for(int i=0;i<children.size();i++){
               n=n+1;
               if(children[i]->children.size()!=0){
                   children[i]->descendants();
               }
           }
       }
       return n;
   }

 };

class B:public A{
public:
    string name;

   B(string aName) : A(aName) {
       this->name=aName;
   }
};

int main() {

A* A1=new A("A1");
A* A2=new A("A2");
B* B1=new B("B1");
B* B2=new B("B2");
B* B3=new B("B3");

A1->addChild(B1);
A1->addChild(A2);
A2->addChild(B2);
A2->addChild(B3);

cout<<A1->descendants()<<endl;

}

P.S. I have looked through similar questions, but I believe this one differs as I want to return an integer number and not update descendants every time a new child is added.
Thanks!

A:

#include <iostream>
#include <vector>

using namespace std;

class A{
public:
    string name;
    vector<A*> children;

    A(string aName){
        this->name=aName;
    }

    void addChild(A* aChild){
        children.push_back(aChild);
    }

    int descendants(){
        int numDescendants = 0;
        for(int i=0;i<children.size();i++){
            numDescendants++;
            numDescendants += children[i]->descendants();  // IMPORTANT: Add the number of grandchildren to the total, too
        }
        return numDescendants;
   }

 };

class B:public A{
public:
    string name;

    B(string aName) : A(aName) {
        this->name=aName;
    }
};

int main() {
    A* A1=new A("A1");
    A* A2=new A("A2");
    B* B1=new B("B1");
    B* B2=new B("B2");
    B* B3=new B("B3");
    B* B4=new B("B4");
    A1->addChild(B1);
    A1->addChild(A2);
    A2->addChild(B2);
    A2->addChild(B3);
    B3->addChild(B4);
    cout<<A1->descendants()<<endl;
}


Q:

How to set date to default time zone

I would like to set date to default time zone. At this moment my date looks like this: 2013-04-08T22:00:00 +02:00. I need to set my date to +00:00.
I tried to get the offset of my date and I received -120. Is it possible to set time offset? Are there maybe any better solutions?
Anybody an idea?
I'm using EXT JS.

A:

JavaScript's Date object is bound to the time zone of the computer itself.  There is no way to change the zone offset programmatically to an arbitrary value.
There is some work going on to add this functionality to the Moment.js library, but it is still in progress.
If you are just looking to get the time at UTC in ISO format, you can use .toISOString()
If you are speaking about code that is specific to the Ext.Date object from ExtJS, please edit your question and post some sample code so we can get a better idea of what you are talking about.  Thanks.


Q:

how to disable this document.getElementById("failedUpdateMessage").style.visibility = "hidden"; in javascript

after I used that code to hide the element with the id "failedUpdateMessage", I would like to show that hidden element in some page in html, how would I do that using java script? I'd try to replace the "hidden" to "show" but it doesn't work.

A:

You must use :
 document.getElementById("failedUpdateMessage").style.visibility ="visible";

Note : show() works on elements hidden with jQuery methods and display:none in CSS (but not visibility:hidden).


Q:

Checkbox Images in List

It seems like it should be a simple concept. I need a vertical list. This list has an image with a checkbox and pathname of that image underneath it. The user should be able to check the checkboxes of the images they want to appear in their "shopping cart". The images, checkbox label, and list are populated by an XmlList. How can I do this in Flex 3.5 and Actionscript and have a button that when clicked, display a list of the checked items??

A:

You need to write a custom list item-renderer.
Here are same docs http://livedocs.adobe.com/flex/3/html/help.html?content=cellrenderer_2.html


Q:

ASP.NET MVC POST Parameters in the url

url : /jobs/UpdateJobResults/GUIDHERE
When I do a post to the below function the guid id is always blank, can I use the above format to POST the GUID in the url (as the form body has the results dictionary) ?
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult UpdateJobResults(Guid Id, Dictionary<string, object> results)
{

}

A:

ended up being the model binder created was looking in the form for the guid on the post rather than the query string


Q:

If $a,b>1$ then there is an integer $N$ such that $a^N>b$

Let $a,b>1$ be real numbers. I need to prove that there exists an integer $N>0$ such that $a^N>b.$ This seems like trivial by intuition but I can't have a rigorous proof. There's also a hint:  $(1+c)^N \geq 1 + Nc$.

A:

Let $c = a - 1$, then $(1 + c)^N = a^N \ge 1 + Nc$
Let $b$ be any real number bigger than one.
We have $a^N = (1 + c)^N \ge 1 + Nc > Nc = b$
So let's get $N = \frac{b}{a - 1}$


Q:

The confused and problem about the jquery ajax using

At first I want request a whole page:
    $.ajax({
            type: "get",
            url: "Test.aspx",
            dataType: "html",
            success: function (html) {
                 $(html).appendTo($("#contain"));
            },
     });

the whole page element will append to the div#contain,include the css,js script effect ,
but when I request part of the page 's elements,like :
$.ajax({
        type: "get",
        url: "Test.aspx",
        dataType: "html",
        success: function (html) {
             $(html).find("div.test").appendTo($("#contain"));
        },
 });

the resault is that div#conntain only get the element's pure inner html,like some text,without any css or js effect……
so how can I get parts of the page 's element' include css and js effect?or it is just impossible……

A:

first I still don't konw why the situation would happened,but the comment above is right,if I define CSS and JS globally,this could be solved more or less ,the CSS could work ,but the js seems still not……


Q:

Magento Responsive CSS block

i need to make that bar have the same margin as the whole page and be responsive. Im not being able to do so. Im new to css html and stuff, i've tried adding padding, margins, float and was unssucesful, could someone give me a hand?
Webpage

A:

on this class move-block header
element.style {
    margin: 0 14px 0 24px;
    position: relative;
    top: 0;
    width: 1170px;
}

and add this
.col-xs-12 {
    width: 98%;
}


Q:

ARM LL/SC exclusive access by register width or cache line width?

I'm working on the next release of my lock-free data structure library.
I'm using LL/SC on ARM.
To use LL/SC as LL/SC (rather than emulating CAS) there has to be a single STR between the LDREX and STREX.
Now, I've written the code and this works.
What concerns me however is the possibility it may not work.
I've read on PowerPC if you access the same cache line as the LL/SC target, you break the LL/SC.
So I'm thinking if my STR target is on the same cache line as my LL/SC target, then pow, I'm dead.
Now, the LL/SC target and STR targets are always in different malloc()s so the chance of them being directly in the same cache line is probably small (and I can guarantee this by padding the LL/SC target so it begins on a cache line boundary and fills that cache line).
But there coud be false sharing, if the STR target is in just the right (wrong!) place in memory.
Looking at the LDREX/STREX documentation, this descriibes exclusive access in terms of "the physical address". This implies register width granularity, not cache line width granularity.
And that's my question - is LDREX/STREX sensitivity to memory access using register width granularity or cache line width granularity?

A:

ARM uses Exclusive Monitors to implement exclusive access to memory via load-linked/store-conditional. [1] has all the details, of importance here I'd say is the following:

Exclusives Reservation Granule
When an exclusive monitor tags an address, the minimum region that can
  be tagged for exclusive access is called the Exclusives Reservation
  Granule (ERG). The ERG is implementation defined, in the range 8-2048
  bytes, in multiples of two bytes. Portable code must not assume
  anything about ERG size.

So you're kinda out of luck there as I see it. Most real implementations will probably keep a small value anyway, but it's not guaranteed by the basic ARM architecture as far as I can tell, but maybe someone with more experience will find me wrong. :)
Still, kinda all implementations out there of LL/SC are some form of weak-LL/SC, so you can almost never be completely sure that a store between the LL and the SC won't kill the SC always, or most of the time, or maybe never... It's just so much architecture and implementation dependent that I personally stick to using LL/SC to implement CAS in a tight loop and use that as usual and be done with it.
[1] http://infocenter.arm.com/help/index.jsp?topic=/com.arm.doc.dht0008a/CJAGCFAF.html


Q:

Multiple AggregateResult Querys

Hi guys,
I'm currently trying to join two objects in a same query or result.
My question is if it's possible to show or debug the sum of FIELD A FROM LEAD + sum of FIELD B FROM two different Objects.
Here's an example I'm working on:
Btw I really appreciate your time and comments, and if i'm making a mistake pls let me know, thank you.
public static void example() {

   String sQueryOne;
   String sQueryTwo;
   AggregateResult[] objOne;
   AggregateResult[] objTwo;

   //I tried to save the following querys into a sObject List
   List<SObject> bothObjects = new List<SObject>();

   sQueryOne = 'Select Count(Id) records, Sum(FieldA) fieldNA From Lead';
   objOne = Database.query(sQueryOne);
   sQueryTwo = 'Select Count(Id) records, Sum(FieldA) fieldNB From Opportunity';
   objTwo = Database.query(sQueryTwo);

   bothObjects.addAll(objOne);
   bothObjects.addAll(objTwo);

   for(sObject totalRec : bothObjects) {
       //There's a Wrapper(className) I created which contains some variables(totalSum)
       className finalRes = new className();
       finalRes.totalSum = (Integer.valueOf(fieldNA)) + (Integer.valueOf(fieldNB));
       System.debug('The sum is: '+finalRes.totalSum);

For example if I call a System debug with the previous variable finalRes.totalSum it's just showing the first value(fieldNA) duplicated.

The following debug shows the current values of the sObject List which I want to sum for example FIELD0 = from leads, FIELD0 = from Opportunities.

   }
}

A:

You access the columns in AggregateResult by calling get('columnAlias'). If you didn't specify an alias they'll be autonumbered by SF as expr0, expr1... When in doubt you can always go System.debug(results);
Some more info: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/langCon_apex_SOQL_agg_fns.htm
This might give you some ideas:
List<AggregateResult> results = new List<AggregateResult>{
    [SELECT COUNT(Id) records, SUM(NumberOfEmployees) fieldA, SUM(AnnualRevenue) fieldB FROM Account],
    [SELECT COUNT(Id) records, SUM(Amount) fieldA, SUM(TotalOpportunityQuantity) fieldB FROM Opportunity],
    [SELECT COUNT(Id) records, SUM(NumberOfEmployees) fieldA, SUM(AnnualRevenue) fieldB FROM Lead]
    /* hey, not my fault these are only 2 standard numeric fields on Lead.
    It doesn't matter that they're identical to Account fields, what matters is what their SUM(...) aliases are
    */
};

List<Decimal> totals = new List<Decimal>{0,0,0};

for(AggregateResult ar : results){
    totals[0] += (Decimal) ar.get('records');
    totals[1] += (Decimal) ar.get('fieldA');
    totals[2] += (Decimal) ar.get('fieldB');
}

System.debug(totals); // (636, 8875206.0, 9819762558.0) in my dev org

(I'm not saying it's perfect, your wrapper class sounds like better idea or maybe even Map<String, Decimal>. Depends what are you going to do with the results)


Q:

Using Kubernetes Persistent Volume for Data Protection

To resolve a few issues we are running into with docker and running multiple instances of some services, we need to be able to share values between running instances of the same docker image.  The original solution I found was to create a storage account in Azure (where we are running our kubernetes instance that houses the containers) and a Key Vault in Azure, accessing both via the well defined APIs that microsoft has provided for Data Protection (detailed here).
Our architect instead wants to use Kubernetes Persitsent Volumes, but he has not provided information on how to accomplish this (he just wants to save money on the azure subscription by not having an additional storage account or key storage).  I'm very new to kubernetes and have no real idea how to accomplish this, and my searches so far have not come up with much usefulness.
Is there an extension method that should be used for Persistent Volumes?  Would this just act like a shared file location and be accessible with the PersistKeysToFileSystem API for Data Protection?  Any resources that you could point me to would be greatly appreciated.

A:

A PersistentVolume with Kubernetes in Azure will not give you the same exact functionality as Key Vault in Azure.
PesistentVolume:

Store locally on a mounted volume on a server
Volume can be encrypted
Volume moves with the pod.

If the pod starts on a different server, the volume moves.

Accessing volume from other pods is not that easy.
You can control performance by assigning guaranteed IOPs to the volume (from the cloud provider)

Key Vault:

Store keys in a centralized location managed by Azure
Data is encrypted at rest and in transit.
You rely on a remote API rather than a local file system.
There might be a performance hit by going to an external service

I assume this not to be a major problem in Azure.

Kubernetes pods can access the service from anywhere as long as they have network connectivity to the service.
Less maintenance time, since it's already maintained by Azure.


Q:

Prevent UINavigationBar popViewController animation

I have the following problem: I have overridden popViewControllerAnimated:(BOOL)animated of UINavigationController because I would like to have a custom animation. The code is as follows:
- (UIViewController *)popViewControllerAnimated:(BOOL)animated
{
    UIViewController *poppedCtrl = [super popViewControllerAnimated:NO];
    [((customViewController *) self.topViewController) doCustomAnimation];
    return poppedCtrl;
}

Unfortunately the UINavigationBar seems to ignore that I explicitly disable the built in animation and it is still animated.
What do I have to do to also prevent the animation of the navigation bar?

A:

After some reading and also some experimentation I finally found out what needs to be done to achieve the desired behavior.
To prevent the navigation bar from being animated it is not sufficient to override (UIViewController *)popViewControllerAnimated:(BOOL)animated.
It is also necessary to create a custom navigation bar and override (UINavigationItem *)popNavigationItemAnimated:(BOOL)animated:
- (UINavigationItem *)popNavigationItemAnimated:(BOOL)animated {
    return [super popNavigationItemAnimated:NO];
}

Of course this custom navigation bar must also be the one which is used (I just replaced the navigation bar which is used by my navigation controller in the interface builder).


Q:

Texture Memory Usage

I am trying to find out how much texture memory does consumed from my application. There are following types of texture and calculations by me:

RGB textures -> textureWidth * textureHeight * 3 (memory usage)
RGBA textures -> textureWidth * textureHeight * 4 (memory usage)

As a result I am wondering that can graphics driver allocate much more memory than above calculated memory?

A:

A few simple answers:
To the best of my knowledge, it's been around 2 decades since (the majority of) hardware devices supported packed 24bit RGB data. In modern hardware this is usually represented in an "XRGB" (or equivalent) format where there is one padding byte per pixel. It is painful in hardware to efficiently handle pixels that straddle cache lines etc.   Further, since many applications (read "games") use texture compression, having support for fully packed 24bit seems a bit redundant.
Texture dimensions: If a texture's dimensions are not 'nice' for the particular hardware (e.g,. maybe, say, x is not a multiple of 16bytes, or, say, 4x4 or 8x8 blocks), then the driver may pad the physical size of the texture.
Finally, if you have MIP mapping (and you do want this for performance as well as quality reasons), it will expand the texture size by around 33%.

A:

In addition to the answer from Simon F, it's also worth noting that badly written applications can force the driver to allocate memory for multiple copies of the same texture. This can occur if it attempts to modify the texture while it is still referenced by an in-flight rendering operation. This is commonly known as "resource copy-on-write" or "resource ghosting".
Blog here explains in more detail:
https://community.arm.com/developer/tools-software/graphics/b/blog/posts/mali-performance-6-efficiently-updating-dynamic-resources


Q:

cancel JComboBox actionEvent

I'm writing a gui program and have an AbstractAction for a Jbutton that opens a file.  In a JComboBox I have a list of the files that have been opened.  The AbstractAction for the JComboBox will change back to any of the files that have been opened.  When I update the list for a JComboBox though the action fires.
So when I actually open a file the JComboBox action fires, and when I use the JComboBox the action fires once, then a second time when updating.
Is there a way i can stop the event when just updating the JComboBox list?
Thanks in advance

A:

The answer is in the design, particularly in separation of concers: don't think view-with-two-actions, instead think many-views-change-state-of-single-data.
In pseudo-code something like:
// data class
public class MyOpenFilesBean {

    private File currentFile;

    public void setCurrentFile(File current) {
         File old = getCurrentFile();
         this.currentFile = current;
         firePropertyChange("currentFile", old, getCurrentFile());
    }

    public File getCurrentFile() {
        return currentFile;
    }

}

// view wiring (view --> data)

Action open = new AbstractAction(...) {

      public void actionPerformed(...) {
          File choosenFile = // grab it from whereever in the view
          myOpenFileBean.setCurrentFile(choosenFile);
      }

};
myButton.setAction(open);
myComboBox.setAction(open);

// view wiring (data --> view)

PropertyChangeListener l = new PropertyChangeListener() {
     public void propertyChanged(...) {
         if ("currentFile".equals(evt.getPropertyName()) {
               // a method implemented to update f.i. the combo selection
               updateView((File) evt.getNewValue());
         }
     }
};
myOpenFileBean.addPropertyChangeListener(l);


Q:

Where jenkins store build files result?

I am wondering if there is a way to get the files result of a Jenkins build.
I configure Jenkins to create the build, so it successfully pull my gitlab and then compile my project. So it should have my files and the compilation result stored somewhere right?
The only files I could see in the last build for my job directory are :

build.xml
changelog.xml
log

Thanks for your help, really appreciate that !
Thomas

A:

Workspace will keep the latest build, the legacy will be kept inside the jenkins master slave under
$JENKINS_HOME/yourjobname/builds/yourbuildernumer

Br,
Tim


Q:

Libgdx serialization

I'm trying to deserialize my game data on Android. I have the gamadata.dat file in my assets folder, however I keep having a FileNotFoundException.
FileHandle fl = Gdx.files.internal("gamedata.dat");
ObjectInputStream in = new ObjectInputStream(new FileInputStream(fl.file()));

AllData data = (AllData) in.readObject();
in.close();

So why do I have this exception?
Regards

A:

In the JavaDoc it is stated that FileHandle.file() does not work with internal FileHandles.
Try this instead:
FileHandle fl = Gdx.files.internal("gamedata.dat");
ObjectInputStream in = new ObjectInputStream(fl.read());

AllData data = (AllData) in.readObject();
in.close();


Q:

Having problem resizing form, input text and font height

i´m having some problem trying to resize the height of the forms, input text´s and fonts.
I´m writing a forms that will show up inside a background image, and i´m trying to fit the form size inside that image. But he is not changing his height.
I dont know how i can do it, i already tried a lot of google and stack overflow stuff but nothing worked.

    body {
        margin: 0;
        padding: 0;
        overflow: hidden;
        height: 100%;
        width: 100%;
    }

    .inner {
        float: left;
        width: 600px;
        height: 410px;
    }

    .jright {
        background: url("../img/visa_erased.png");
    }

    form {
        float: right;
        width: 40%;
        padding-top: 80px;
    }

    .input-field {
        box-sizing: border-box;
        color: #000000 !important;
    }

    #register {
        height: auto;
        width: 30%;
        padding: 1;
        background: #392c34 !important;
    }

    .dropdown-content {
        top: 0 !important;
    }

    .select-wrapper li {
        background: #b5a795 !important;
    }

    .select-wrapper li span {
        color: #ffffff !important;
    }

    .select-wrapper .disabled {
        background: #897d6e !important;
    }

    .select-wrapper .selected {
        background: #d6c7b3 !important;
    }

    .datepicker-date-display {
        background: #392c34;
    }

    .datepicker-container button {
        color: #392c34;
    }

    .datepicker-container button:focus {
        background: none;
    }

    .datepicker-container .is-selected {
        background: #7a5f70 !important;
    }

    .dropdown-content li>a,
    .dropdown-content li>span {
        color: #392c34 !important;
    }

    .datepicker-container input {
        color: #392c34 !important;
    }

    label {
        color: #392c34 !important;
        text-shadow: -1px 0 rgba(0, 0, 0, 0.2), 0 1px rgba(0, 0, 0, 0.2), 1px 0 rgba(0, 0, 0, 0.2), 0 -1px rgba(0, 0, 0, 0.2);
    }

    .input-field input[type=text] {
        border-bottom: 1px solid #392c34 !important;
        box-shadow: 0 1px 0 0 #392c34 !important;
    }

    .input-field input[type=text]:focus+label {
        color: #6b0742 !important;
    }

    .input-field input[type=text]:focus {
        border-bottom: 1px solid #6b0742 !important;
        box-shadow: 0 1px 0 0 #6b0742 !important;
    }

     ::-webkit-scrollbar {
        width: 0px;
        background: transparent;
    }

     ::-webkit-scrollbar-thumb {
        background: #FF0000;
    }

    @media only screen and (max-width: 1250px) {
        .container {
            width: 100% !important;
        }
    }
 <!DOCTYPE html>

        <meta charset="utf-8">
        <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
        <link rel="stylesheet" href="css/style.css" type="text/css">
        <link rel="stylesheet" href="css/materialize.css" type="text/css">

                    <form>

                            <input id="firstname" name="firstname" placeholder="" type="text" required>
                            1. Nome

                            <input id="lastname" placeholder="" type="text" required>
                            2. Sobrenome

                            <input id="height" placeholder="" type="text" maxlength="3" minlength="2" required>
                            3. Altura (CM)

                            <input id="dateofbirth" placeholder="" type="text" class="datepicker" required>
                            4. Aniversário (DD-MM-YYYY)

                            <select data-beloworigin="true" required>
                                  <option value="none" disabled selected>Escolha o gênero</option>
                                  <option value="M">Masculino</option>
                                  <option value="F">Feminino</option>
                                </select>
                            5. Sexo

                        <button id="register" class="btn btn-large waves-effect">OK</button>
                    </form>

A:

Here's an example from w3school that shows a nicely made form over a image in background.
Have a look in the below snippet.

body, html {
  height: 100%;
  font-family: Arial, Helvetica, sans-serif;
}

* {
  box-sizing: border-box;
}

.bg-img {
  /* The image used */
  background-image: url("https://www.w3schools.com/howto/img_nature.jpg");

  min-height: 380px;

  /* Center and scale the image nicely */
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;
}

/* Add styles to the form container */
.container {
  position: absolute;
  right: 0;
  margin: 20px;
  max-width: 300px;
  padding: 16px;
  background-color: white;
}

/* Full-width input fields */
input[type=text], input[type=password] {
  width: 100%;
  padding: 15px;
  margin: 5px 0 22px 0;
  border: none;
  background: #f1f1f1;
}

input[type=text]:focus, input[type=password]:focus {
  background-color: #ddd;
  outline: none;
}

/* Set a style for the submit button */
.btn {
  background-color: #4CAF50;
  color: white;
  padding: 16px 20px;
  border: none;
  cursor: pointer;
  width: 100%;
  opacity: 0.9;
}

.btn:hover {
  opacity: 1;
}

Form on Hero Image

  <form action="/action_page.php" class="container">

Login

    Email
    <input type="text" placeholder="Enter Email" name="email" required>

    Password
    <input type="password" placeholder="Enter Password" name="psw" required>

    <button type="submit" class="btn">Login</button>
  </form>

This example creates a form on a responsive image. Try to resize the browser window to see how it always will cover the whole width of the screen, and that it scales nicely on all screen sizes.

Now, lets modify the snippet according to your need (as mentioned in your question).
[ Pay attention to the changes in the style tag ]

Change height of form. (height attribute)
Change input text size. (font-size attribute)
Change input text font. (font-family attribute)

body, html {
  height: 100%;
  font-family: Arial, Helvetica, sans-serif;
}

* {
  box-sizing: border-box;
}

.bg-img {
  /* The image used */
  background-image: url("https://www.w3schools.com/howto/img_nature.jpg");

  min-height: 380px;

  /* Center and scale the image nicely */
  background-position: center;
  background-repeat: no-repeat;
  background-size: cover;
  position: relative;
}

/* Add styles to the form container */
.container {
  position: absolute;
  right: 0;
  margin: 20px;
  max-width: 300px;
  padding: 16px;
  background-color: white;
}

/* Full-width input fields */
input[type=text], input[type=password] {
  width: 100%;
  padding: 15px;
  margin: 5px 0 22px 0;
  border: none;
  background: #f1f1f1;
  height:10%;
  font-size:10px;
  font-family: monospace;
}

input[type=text]:focus, input[type=password]:focus {
  background-color: #ddd;
  outline: none;
}

/* Set a style for the submit button */
.btn {
  background-color: #4CAF50;
  color: white;
  padding: 16px auto;
  border: none;
  cursor: pointer;
  width: 100%;
  opacity: 0.9;
  height:10%;
  text-align:center;
}

.btn:hover {
  opacity: 1;
}

form{
  height:70%;
}

h2{
  margin-top:0px;
}

label{
  font-size:15px;
}

Form on Hero Image

  <form action="/action_page.php" class="container">

Login

    Email
    <input type="text" placeholder="Enter Email" name="email" required>

    Password
    <input type="password" placeholder="Enter Password" name="psw" required>

    <button type="submit" class="btn">Login</button>
  </form>

This example creates a form on a responsive image. Try to resize the browser window to see how it always will cover the whole width of the screen, and that it scales nicely on all screen sizes.

Hope, this gives you an idea about the whole thing.


Q:

App Engine editing an instance in a repeated KeyProperty via the instance itself

Lets say I have the following models:
class Author(ndb.Model)
    books = ndb.KeyProperty(kind='Book', repeated=True)

class Book(ndb.Model)
    title = ndb.StringProperty()

So at a certain point you'll have an author with a list of n books.
Questions:
When I'm editing a book how do I change the author without a reference to the 'current' author? Do I need to add a reverse relation with a KeyProperty on Book?
When changing the author I have to remove the book from the old author's list and add it to the new one. That feels kind of cumbersome. Is there a better way?
Bonus question: What if a book gets deleted? There will be a None value in the author's books list. Do I have to remove that?
Note: I'm using a repeated KeyProperty because this makes ordering the books easy, which in my case is important.

A:

When I'm editing a book how do I change the author without a reference to the 'current' author?

you can use ndb.Model.allocate_ids to reserve a key before the entity is saved

Do I need to add a reverse relation with a KeyProperty on Book?

Given your model, the addition of a reverse lookup key can make your life easier

What if a book gets deleted? There will be a None value in the author's books list. Do I have to remove that?

The key in Auther.books will not automatically becomes null in this case. You have to remove it yourself.

I'm using a repeated KeyProperty because this makes ordering the books easy, which in my case is important.

A potential problem is that an entity has a size limit of 1mb. If an author is very prolific writer (e.g. Edwy Searles Brooks has 800+ published works), it can exceed the limit.
I would design the model this way:
class Author(ndb.Model):
    name = ndb.StringProperty()

class Book(ndb.Model):
    authors = ndb.KeyProperty('Author', required=True)  # Usually it is at most a couple of authors
    title = ndb.StringProperty()

To find out all books written by a particular author with id 1234, you can
  Book.query(Book.authors == ndb.Key('Author', 1234)).fetch()

Apparently the ordering of books must be stored explicitly, I would suggest a third entity to keep track of this information:
class BookList(ndb.Model):
  name = ndb.StringProperty()
  book_keys = ndb.KeyProperty(kind='Book', repeated=True)

Then you can retrieve books in this manner
stephen_king_book_list = stephen_king_book_list_key.get()
books = ndb.get_multi(stephen_king_book_list.book_keys)
# Some of key can lead to None if the underlying book is already deleted
# You can define some background job to sweep clean the list from time to time
# But let filter out the bad guys first
books = [b for b in books if b]

If you think your lists are going to be very very long, you can break a list down into segments like a linked list structure
class BookList(ndb.Model):
  prev_segment = ndb.KeyProperty(kind='BookList', required=False)
  next_segment = ndb.KeyProperty(kind='BookList', required=False)
  name = ndb.StringProperty()
  book_keys = ndb.KeyProperty(kind='Book', repeated=True)

You can find the fist segment easily by:
  starting_point = BookList.query(BookList.name == 'Stephen_King',
     BookList.prev_segment == None
  ).fetch()

Of course if insertion is very frequent, you might want to use an alternative structure to hold the book list


Q:

( was unexpected at this time (If exist folder)

It's saying "( was unexpected at this time" the code:
:new_game
set /p name=Enter your name:

if exist Save\%name%\ (

echo This save exists delete it?
set /p var=[Y,N]

if %var% == N (
    goto new_game
) else (
    del /Q Save\%name%\
)
)
md Save\%name%\

It's up at the "if exist Save\%name%\ (".

A:

Within a block statement (a parenthesised series of statements), the entire block is parsed and then executed. Any %var% within the block will be replaced by that variable's value at the time the block is parsed - before the block is executed.
Hence, IF (something) else (somethingelse) will be executed using the values of %variables% at the time the IF is encountered.
Consequently,
if %var% == N (

is interpreted as
if  == N (

which is what the parser is complaining about.
Two issues:
First, if you are entering a string with a set/p, then there's no sying that the data entered doesn't contain Spaces. The way to get over that is to "enclose the srings on both sides of the comparison operator in quotes"
Second, since you want to enter the var string conditionally, you either need to structure the code differently (so the entry doesn't appear in the code-block) or use delayed expansion.
setlocal enabledelayedexpansion

will allow you to use the syntax if "!var!"=="whatever including spaces" to access the CURRENT value of var within a block. It's best set directly after the @echo off and has the advantage of restoring the environment to its original condition when the batch terminates.


Q:

Parameter file for bteq

I have a bteq file that delete a table.
.LOGON Server/User,Password;
del from  Database.table all;

.LOGOFF
.EXIT

This operation works. What I want is to take the user/password from this bteq file, put them in a parameter file and then call them fromp there.
Should i create a second bteq file as a parameter file ? and if so how can I declare those parameters and how can i call them ?

A:

You can use the .RUN command to call an external file containing valid BTEQ commands. In this instance, you would take the .LOGON command along with the credentials and place it in another file. Your BTEQ script above would look like this afterwards:
.RUN FILE={path}/{filename}.{ext};

del from  Database.table all;

.LOGOFF
.EXIT


Q:

Is this a correct construction of the underlying sets of free semigroups?

Question: Is the following a correct formal construction of the set of "strings"/"words" used in the construction of free semigroups? (And free monoids and free groups?)

Define for all $n \ge 1$ the set $[n]:= \{1, 2, \dots, n\}$ and $[0]:= \emptyset$. In what follows, use exponential notation for function spaces, i.e. the space of all functions $X \to Y$ is denoted $Y^X$.
Claim: The underlying set (i.e. I am not yet addressing the definition of multiplication) of the free semigroup generated by the elements of an arbitrary set $X$ can be taken to be:
$$\bigcup_{n \ge 1} X^{[n]}  $$
(Should this be a disjoint union instead of a union? There is no set of all sets, and I haven't explicitly identified a common superset of all of the $X^{[n]}$.)
Correspondingly I also claim that the underlying set of the free monoid generated by the elements of an arbitrary set $X$ can be taken to be:
$$\bigcup_{n \ge 0} X^{[n]} $$
There is exactly one function $\emptyset \to X$. My implicit claim is that we can sensibly identify the empty function with the empty string.
Multiplication would of course then just be "concatenation", but precisely defining that is annoying especially when the underlying idea is so much simpler than all of the constructions I can think of, so I will "leave it as an exercise for the reader".
Mostly I'm just interested in whether or not this is a standard construction of the set of all strings, or if there are better, more sensible ways to do it/think about it.
The underlying sets for free monoids and as a special case free abelian groups are given precise constructions in the sources I've read, but the same was not true for free semigroups/free monoids/free groups. (For free groups one could replace $X$ with $X \times X$ or something like that.)

A:

What you have done is fine, and is a very sensible way of providing a set-theoretic construction of the set of all finite strings of elements of a set (or non-empty finite strings, in the case of free semirings).
The choice of whether to use union or disjoint union doesn't particularly matter: the sets $X^{[n]}$ are pairwise disjoint anyway, so the union and disjoint union are in bijective correspondence.
For free groups, the matter is slightly complicated by the fact that you have to account for inverses of elements. In this case, the underlying set is
$$\bigcup_{n \ge 0} (X \cup X^{-1})^{[n]}$$
where $X^{-1} = \{ x^{-1} \mid x \in X \}$ is a set of 'formal inverses' of elements of $X$. Or, if you wanted to be super nitpicky, you could take $([2] \times X)^{[n]}$ rather than $(X \cup X^{-1})^{[n]}$, and interpret $(1,x)$ as $x$ and $(2,x)$ as $x^{-1}$. The group operation is then defined by concatenation followed by reduction, i.e. in any given string, keep deleting any instances of $xx^{-1}$ or $x^{-1}x$ until there are no such instances.


Q:

Drawing conclusions from impulse response of a discrete LTI system

I have an impulse response of an LTI system which is
h(n)= n*u(n)-u(n-2) where n=[0,3] (1)

Now regarding the stability and causality of this system, i've drawn the conclusion that the system is causal since the output only relies on past or present values of n and it is stable since n is bounded. In this case n=0,1,2,3. Correct me here if i'm wrong but in case h(n) was u(n) - u(n-2) without knowing anything about n, it would stil be stable right? And if h(n) is the same as the original (1) but again without knowing anything about n it would be unstable correct?
Now i want to analyze this h(n) in odd and even components and also find the linear difference equation of h(n) ,but i can't find anything in my textbook that is of any help. It's the first time i've attended a signals and systems course and i'm really struggling to understand a few things, so any help here would be greatly appreciated.

A:

You're right about your conclusions. And now a few hints to help you solve the questions:

Your textbook should state somewhere the definition of even and odd parts of a (real-valued) sequence: $$h_e[n]=\frac12\big(h[n]+h[-n]\big)\\h_o[n]=\frac12\big(h[n]-h[-n]\big)$$

In this case (FIR filter), the difference equation is simply given by the convolution of the input sequence $x[n]$ with the impulse response $h[n]$: $$y[n]=\sum_kx[k]h[n-k]$$


Q:

"Blog" link on offline page links to wrong blog

The blog link on the SO offline page links to blog.serverfault.com.
Since blog.stackoverflow.com is the main SE blog, it makes sense that issues regarding the maintenance would be posted there.  Should this link be updated?

A:

The Server Fault blog is run by the SE server administrators, who are responsible for the uptime and maintenance of the SE servers. Thus, they would post appropriate server information on their blog.


Q:

jsPDF: fromHTML vs addHTML

I'm trying to export an html(within a div with ID), and have managed to do so with fromHTML(), but unfortunately it doesn't read/use any css I have. This said, I tried with addHTML function, but it looks like nothing happens when I use following code:
function pdfExport(id) {
    window.html2canvas = html2canvas;
    var dddoc = new jsPDF('p', 'px', 'a4');
    var elem_to_export = $("#cmodal-id-" + id)[0];

    dddoc.addHTML(document.body, function(){
        console.log('saving');
        dddoc.save('test.pdf');
    });
}

Also, note that I don't get anything printed into console. Not sure if it's worth anything: Before I run this function pdfExport() - (it's ran onclick) - I get one get error in js console, as said image doesn't exist. Now, when I run the function, same error appears again, just as if that image is tried to be loaded again.

A:

This wasn't working because I used latest versions of both html2canvas and jsPDF. When I changed those to load from:
'https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.0.272/jspdf.debug.js',
'https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js'
everything was just working.


Q:

Writing predicate formulas on $\mathbb{N}$ using only the given predicates

Problem
(Source: "Mathematics for Computer Science", Lehman, Leighton, Meyers, 2018.)

In this problem we’ll examine predicate logic formulas where the domain of discourse is $\mathbb{N}$. In addition to the logical symbols, the formulas may contain ternary predicate symbols $A$ and $M$, where:
$A(k,m,n)$ means $k = m + n$
$M(k,m,n)$ means $k = mn$
For example, a formula $Zero(n)$ meaning that $n$ is zero could be defined as
$Zero(n)=A(n,n,n)$
Having defined $Zero$, it is now OK to use it in subsequent formulas. So a formula for $Greater(m,n)$ meaning $m > n$ could be defined as
$Greater(m,n) = \exists k \left( \neg \left( Zero(k) \right) \wedge A(m,n,k) \right)$
This makes it OK to use $Greater$ in subsequent formulas.
$M(k,m,n)$ means $k = mn$
Write predicate formulas using only the allowed predicates $A$, $M$ that define the following predicates:
(a) $Equal(m,n)$ meaning that $m = n$.
(b) $One(n)$ meaning that $n = 1$.
(c) $n = i(m \cdot j + k^2)$.
(d) $Prime(p)$ meaning $p$ is a prime number.
(e) $Two(n)$ meaning that $n = 2$.
(f) $Even(n)$ meaning $n$ is even.
(g) (Goldbach Conjecture) Every integer $n \geq 4$ can be expressed as the sum of two primes.
(h) (Fermat's Last Theorem) Now suppose we also have
$X(k,m,n)$ means $k = m^n$
Express the assertion that there are no positive integer solutions to the equation:
$x^n + y^n = z^n$
when $n > 2$.
(i) (Twin Prime Conjecture) There are infinitely many primes that differ by two.

Solution attempt
Attempts for each item:
(Note: As I define predicates in each item, I may reuse them in subsequent items.)
a) Since $m=n$ if and only if $m \leq n$ and $n \leq m$:
$Equal(m,n) = \left( \neg Greater(m,n) \right) \wedge \left( \neg Greater(n,m) \right)$
b) Any natural number $n$ multiplied by 1 is equal to $n$, so:
$One(n) = \forall k \left(M(k,n,k)\right)$
c) What I've attempted here is to break down the expression as follows: $n = i \cdot x_1$ for some $x_1$, $x_1 = (x_2 + x_3)$ for some $x_2$ and some $x_3$, $x_2 = (m \cdot j)$ for some $m$ and some $j$, and $x_3 = k^2$. So the attempt becomes:
$C(n) = \exists i \exists x_1 \exists x_2 \exists x_3 \exists j \exists k \left(M(n,i,x_1) \wedge A(x_1,x_2,x_3) \wedge M(x_2,m,j) \wedge M(x_3,k,k)\right)$
d) There are two ways that seem to work:
$Prime(p) = \forall a \forall i (One(a) \rightarrow \left( \neg Equal(i,a) \wedge \neg Equal(i,p) \rightarrow \neg \exists k \left( M(p,i,k) \right) \right)$
$Prime(p) = \forall i \exists a (One(a) \wedge \left( \neg Equal(i,a) \wedge \neg Equal(i,p) \rightarrow \neg \exists k \left( M(p,i,k) \right) \right)$
e) There are two ways that I thought of that seem to work for this one, based on the fact that 2 = 1 + 1:
$Two(n) = \exists k \left( One(k) \wedge A(n,k,k) \right)$
$Two(n) = \forall k \left( One(k) \rightarrow A(n,k,k) \right)$
f) $Even(n) = \exists a \exists b \left( Two(a) \wedge M(n,a,b) \right) $
The idea is that, if there exist $a$ and b such that $a$ is the number 2, and $n = ab$, then $n$ is even.
g) $\forall n \forall a \left( Four(a) \wedge \left(Greater(n,a) \lor Equal(n,a)\right) \wedge Even(n) \rightarrow \exists p_1p_2\left( Prime(p_1) \wedge Prime(p_2) \wedge A(n,p_1,p_2) \right ) \right)$
h) $\forall n \forall a \left( Two(a) \wedge Greater(n,a) \rightarrow \left( \neg \exists x,y,z,x_n,y_n,z_n \left ( X(x_n,x,n) \wedge X(y_n, y, n) \wedge X(z_n, z, n) \wedge A(z_n,x_n,y_n) \right ) \right ) \right)$
i) First, define a predicate that tests whether two numbers $m$ and $n$ are twin primes by checking that they are primes and they differ by 2:
$TwinPrime(m,n) = Prime(m) \wedge Prime(n) \wedge \exists t \left( Two(t) \wedge \left( A(q,n,t) \lor A(n,q,t) \right) \right )$
Then, the conjecture could be expressed as below:
$\left( \exists n,m \left( TwinPrime(n,m) \right) \right) \wedge (\forall n,m \left( TwinPrime(n,m) \rightarrow \exists q,p \left ( Greater(q,n) \wedge Greater(p,m) \wedge TwinPrime(q,p) \right ) \right ) )$
As an attempt to express that there are infinitely many twin primes, I'm stating two things: (1) there exist two numbers that are twin primes, (2) if there are two numbers $m,n$ that are twin primes, then there are two numbers $p,q$ that are greater than $m,n$ and are also twin primes.
Could someone please verify if these attempts make sense? Thank you in advance.

A:

Everything looks good!
Just a few nit-picks:
You never defined $Four(n)$ ... though that's easy:
$Four(n)=\exists a (Two(a) \land A(n,a,a))$
And yes, you always have a second option here:
$Four(n)=\forall a (Two(a) \to A(n,a,a))$
Also, your:

$TwinPrime(m,n) = Prime(m) \wedge Prime(n) \wedge \exists t \left( Two(t) \wedge \left( A(q,n,t) \lor A(n,q,t) \right) \right )$

should be:
$TwinPrime(m,n) = Prime(m) \wedge Prime(n) \wedge \exists t \left( Two(t) \wedge \left( A(\color{red}m,n,t) \lor A(n,\color{red}m,t) \right) \right )$


Q:

jQuery Mobile and MVC3 auto submit

The following code works perfectly if I take jQuery Mobile out of the question!
The form:
@using (Html.BeginForm("SearchTown", "Home", FormMethod.Post, new { id = "TheForm1" }))
{
    @Html.DropDownList("TownID", (SelectList)ViewBag.TownId, "Select a Town")
}

The Javascript:
<script type="text/javascript">
    $(function () {
        $("#TownID").live('change', function () {
            //$("#TownID").change(function () {
            var actionUrl = $('#TheForm1').attr('action') + '/' + $('#TownID').val();
            $('#TheForm1').attr('action', actionUrl);
            $('#TheForm1').submit();
        });
    });
</script>

But if I wrap jQuery Mobile around the site, then every time I submit the form, in my log only it tacks the ID field again and again to the end of the URL string. This only happens in my log, not in the browser. In the browser it still looks like it’s doing the right thing! E.g..
www.mysite.com/Home/SearchTown/2 the first time
www.mysite.com/Home/SearchTown/2/2 the second time
www.mysite.com/Home/SearchTown/2/2/2 the third time
But in the browser it still looks correct www.mysite.com/Home/SearchTown/2
Why is jQuery Mobile doing this?

A:

Iv'e left this one up long enough and no one has an answer!


Q:

the value to "out" parameter must be assigned in the method body, otherwise the method will not be compiled

I have the following code in c#
class Sample{
public void sum(out int num1,int num2)
{
}
public void print()
{ int i=12;
sum(out i,10);
Console.WriteLine(i);
}
}

I have read that it works like 'ref',then why the following code give error saying "the out parameter 'num1' must be assigned before control leaves the current method",even i am not writing any statement there or not using num1 and i already assign it the value in callee method?
if i am not using or initialise out parameter,then why it is not initialized to its default value,for here num1=0,and return that value to calee method?

A:

This is by design.
From out parameter modifier (C# Reference)

Although variables passed as out arguments do not have to be
  initialized before being passed, the called method is required to
  assign a value before the method returns.

A:

out is out. You can imagine that it's an alternative way to return the values. The significant difference between return and out is that you can only return one value, but out a various number of values. It's especially useful when your method needs to output more than just one value, such as bool Dictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value).
The error you see is like when you declare a method which returns a value without specifying what to return. The out arguments must be assigned before the code reaches a reachable endpoint. Write a statement which assigns a value to the out parameter is an usual way to get rid of the error:
public static void OutOfAssgnment<T>(out T value) {
    value=default(T);
}

But there are, in fact, at least three approaches other to make it compile:
public static void OutOfAnotherOut<T>(out T value) {
    OutOfAnotherOut(out value); // not necessarily be recursive, just an example
}

public static void OutOfThrowing<T>(out T value) {
    throw new Exception();
}

public static void OutOfInfiniteLoop<T>(out T value) {
    for(; ; )
        ;
}

The latter two don't assign the value of the out parameter, but make the endpoint unreachable would also compile.


Q:

Necessity for Interfaces, Injections in unique project

Why should I implement Interfaces and Dependency Injection on a site with almost no chance for reuse or upgrade by anyone else?

A:

It often makes unit testing quite a bit simpler. For example, you might have a type which uses another type which connects to a database. For unit testing the first type, you can inject a testing mock in place of the second type, allowing you to effectively unit test the first type without indirectly connecting to the database via the second type.

A:

When you learned how to program a computer, you were developing a kind of 'muscle memory' of your craft.  Over the years, you continue to program in that same mindset.  Most people don't learn all of the nifty OOP principles right from the start, so they seem like they are more effort than the way they learned.
You should get in the habit of using OOP design techniques whenever you are using an OOP language, because that will make you a better developer overall.  Your goal should be to retrain your muscle memory of programming to use those techniques.  Then you won't have to ask these questions and assume that the techniques are somehow 'getting in the way' of your programming.  You become a programmer that just programs that way.


Q:

How to stop of a Thread when it finishes its work?

I am working on web application on Java EE.
I have created a thread in my ServletContextLitner so it does some entries in database in background and user is sent to it's homepage.
My question is that how to stop this thread when it is done with its work?

A:

A Thread has a run() method that is executed when the Thread is started (start()).
The method run() contains all the logic of the Thread. When the method run() finishes, the Thread is marked for gc.
Which means, just finish the run() and the JVM will do the rest.


Q:

Does the USA have the highest cumulative CO2 emissions since 1750?

Vox has posted a cumulative graph of CO2 emissions since 1750. And the USA is flagged as the chief culprit. The actual title of the Vox article is:

Why the US bears the most responsibility for climate change, in one chart

It's unclear what the methodology is in establishing this, being just a tweet. (E.g. is it just industrial emissions? Is agriculture considered? Is it [not] considering absorption effects in forests etc.?) Are there some papers that explain/detail it? (And this might take us off the narrow Skeptics path, but is it still true in a per-capita graph? For example, when one considers the current yearly [thus not historically cumulative] emissions, the top per-capita looks very different than than the top per countries as a whole. Basically, is the claim technically true but misleading in some important way? [As a side note: a recent similar question here about climate-change claims is basically along the same broad lines as this last sub-question of mine, i.e. asking if we considered all the angles, not just the claim itself.])

A:

The US is cumulatively responsible for more CO2 emissions than any other single country.
US was responsible for 27% of 1850-2011 emissions according to the World Resources Institute.

The Carbon Dioxide Information Analysis Center (CDIAC) of the Oak Ridge National Laboratory maintains a data set that goes back to 1751, but not for every country does it go back that far.
The CDIAC based the oldest CO2 data on fossil fuel (including peat) production as reported in the reference World Energy Production 1800-1985 (1991), which the CDIAC says has some data back to 1751 in footnotes.


Q:

Store serialized object in session

I have a Service class that stores an object into the session
$this->session->set('utmUser', $this->session->serialize($this->utmUser));

And I get the unserialized object from the session:
$this->utmUser = $this->session->unserialize($this->session->get('utmUser'));

But the result is not an instance of the stored object.
The session contains this serialized string:

string(221) "a:2:{i:0;O:68:"Symfony\Component\HttpFoundation\SessionStorage\NativeSessionStorage":1:{s:10:"*options";a:5:{s:8:"lifetime";i:0;s:4:"path";s:1:"/";s:6:"domain";s:0:"";s:6:"secure";b:0;s:8:"httponly";b:0;}}i:1;s:2:"en";}"

Setting all properties of the object as protected doesn't work.
What am I doing wrong?

A:

session->serialize() and unserialize() do not do what you think they do, they do not serialize and unserialize an object, they serialize and unserialize the whole session. They do not take any parameters and in fact have been removed in Symfony 2.1
You can just set the object into the session and Symfony will take care of serializing and unserializing it for you, just use:
$this->session->set('utmUser', $this->utmUser);

and
$this->utmUser = $this->session->get('utmUser');

In any case you may reconsider if you really need to store the whole object into the session. If this is a big object this can be very inefficient. If that is the case and the object is stored in a database, you can store just the id of the object and then reload it from the id when you need it.


Q:

XSLT: Blank values after transformation

I am trying to do xsl transform: The File Id="" KeyPath="yes" Source=""  has Id and Source blank. I followed other articles and fixed namespaces but still no result.
Original file:
<?xml version="1.0" encoding="utf-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <Fragment>
        <DirectoryRef Id="INSTALLFOLDER">
            <Component Id="cmpF22D40156F8E16FBFA89C752FF9D0EF9" Guid="{965AF45C-4B87-44B9-A881-7BEB4CB8D1E1}">
                <File Id="fil2DACDED111D2125FD9BAF52808E5CEB0" KeyPath="yes" Source="$(var.BasePath)\api-ms-win-core-console-l1-1-0.dll" />
            </Component>
<Component Id="cmpCEE39BB900F45E2F684F712DD10CEF09" Guid="{FA583F14-6375-42BE-9BB0-046FB8DCB0D1}">
                <File Id="fil51FD07FBBBA9CBF4E0ABE1A9AD93D19C" KeyPath="yes" Source="$(var.BasePath)\Api.exe" />
            </Component>
        </ComponentGroup>
     </DirectoryRef>
    </Fragment>
</Wix>

Output:
<?xml version="1.0" encoding="utf-8"?>
<Wix xmlns="http://schemas.microsoft.com/wix/2006/wi">
    <Fragment>
        <DirectoryRef Id="INSTALLFOLDER">
            <Component Id="cmpF22D40156F8E16FBFA89C752FF9D0EF9" Guid="{965AF45C-4B87-44B9-A881-7BEB4CB8D1E1}">
                <File Id="fil2DACDED111D2125FD9BAF52808E5CEB0" KeyPath="yes" Source="$(var.BasePath)\api-ms-win-core-console-l1-1-0.dll" />
            </Component>
      <Component Id="cmpCEE39BB900F45E2F684F712DD10CEF09" Guid="{FA583F14-6375-42BE-9BB0-046FB8DCB0D1}"><File Id="" KeyPath="yes" Source="" />
      </Component>
  </ComponentGroup>
    </DirectoryRef>
    </Fragment>
</Wix>

XSL file:
<xsl:stylesheet version="2.0" xmlns="http://schemas.microsoft.com/wix/2006/wi" xmlns:x="http://www.w3.org/2005/Atom" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:wix="http://schemas.microsoft.com/wix/2006/wi" xmlns:util="http://schemas.microsoft.com/wix/UtilExtension">
  <xsl:output omit-xml-declaration="no" indent="yes"/>
  <xsl:param name="InstallFolder"/>
  <xsl:param name="DisplayName"/>
  <xsl:param name="Name"/>
  <xsl:param name="Description"/>

  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <!-- Set Directory Reference to INSTALLFOLDER (set if required) -->
  <xsl:template match="wix:DirectoryRef/@Id">
    <xsl:attribute name="Id">
      <xsl:value-of select="$InstallFolder"/>
    </xsl:attribute>
  </xsl:template>

  <!-- XSL Template to inject WiX service installation elements to a .wxs generated from Heat Project task -->
  <!-- There may be other ways to look for your file -->
  <xsl:template match='wix:Wix/wix:Fragment/wix:DirectoryRef/wix:Component[wix:File[@Source="$(var.BasePath)\Api.exe"]]'>

    <xsl:element name="Component">
      <xsl:attribute name="Id">
        <xsl:value-of select="@Id"/>
      </xsl:attribute>
      <xsl:attribute name="Guid">
        <xsl:value-of select="@Guid"/>
      </xsl:attribute>

      <xsl:element name="File">
        <xsl:attribute name="Id">
          <xsl:value-of select="File/@Id"/>
        </xsl:attribute>
        <xsl:attribute name="KeyPath">yes</xsl:attribute>
        <xsl:attribute name="Source">
          <xsl:value-of select="File/@Source"/>
        </xsl:attribute>

      </xsl:element>
      <xsl:element name="ServiceInstall">
    <!-- Service Install -->
    <xsl:attribute name="Id">SERVICEINSTALLER</xsl:attribute>
    <xsl:attribute name="DisplayName">
      <xsl:value-of select="$DisplayName"/>
    </xsl:attribute>
    <xsl:attribute name="Name">
      <xsl:value-of select="$Name"/>
    </xsl:attribute>
    <xsl:attribute name="Description">
      <xsl:value-of select="$Description"/>
    </xsl:attribute>
    <xsl:attribute name="Start">auto</xsl:attribute>
    <xsl:attribute name="Account">LocalSystem</xsl:attribute>
    <xsl:attribute name="Type">ownProcess</xsl:attribute>
    <xsl:attribute name="ErrorControl">normal</xsl:attribute>
    <xsl:attribute name="Vital">yes</xsl:attribute>

  </xsl:element>
  <!-- Service Control, set as required -->
  <xsl:element name="ServiceControl">
    <xsl:attribute name="Id">SERVICECONTROLLER</xsl:attribute>
    <xsl:attribute name="Name">
      <xsl:value-of select="$Name"/>
    </xsl:attribute>
    <xsl:attribute name="Remove">uninstall</xsl:attribute>
    <xsl:attribute name="Stop">both</xsl:attribute>
    <xsl:attribute name="Start">install</xsl:attribute>
  </xsl:element>
    </xsl:element>
  </xsl:template>

</xsl:stylesheet>

A:

Your approach to creating elements is way too complex. Don't use <xsl:element> unless you are planning to dynamically calculate the element name.
For elements with a fixed name, write out the element. I also shortened the match expression, it does not seem to be necessary to be this specific, and introduced attribute value templates.
Your basic error was however that it's not a File, but a wix:File:
<xsl:template match='wix:Component[wix:File[@Source="$(var.BasePath)\MircomApi.exe"]]'>
  <Component Id="{@Id}" Guid="{@Guid}">
    <File Id="{wix:File/@Id}" Source="{wix:File/@Source}" KeyPath="yes" />
  </Component>
</xsl:template>

Looking at your sample some more, I believe that you actually want to copy the elements as they are, except when they don't fulfill your condition.
That's much more easily done by writing an empty template for those elements that you want to remove, and use the identity template for everything else. Note the last template.
<xsl:stylesheet version="2.0" xmlns="http://schemas.microsoft.com/wix/2006/wi" xmlns:x="http://www.w3.org/2005/Atom" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:wix="http://schemas.microsoft.com/wix/2006/wi" xmlns:util="http://schemas.microsoft.com/wix/UtilExtension">
  <xsl:output omit-xml-declaration="no" indent="yes"/>
  <xsl:param name="InstallFolder"/>
  <xsl:param name="DisplayName"/>
  <xsl:param name="Name"/>
  <xsl:param name="Description"/>

  <xsl:template match="node()|@*">
    <xsl:copy>
      <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
  </xsl:template>

  <!-- Set Directory Reference to INSTALLFOLDER (set if required) -->
  <xsl:template match="wix:DirectoryRef/@Id">
    <xsl:attribute name="Id">
      <xsl:value-of select="$InstallFolder"/>
    </xsl:attribute>
  </xsl:template>

  <!-- any wix:Component that's NOT a match will be suppressed from the output -->
  <xsl:template match='wix:Component[not(wix:File[@Source="$(var.BasePath)\MircomApi.exe"])]' />
</xsl:stylesheet>


Q:

Elastic Search - Re boot index after updating synonym config file

I am using a synonym text file to define synonyms for my search index.
If I update this file, I have to stop and start the windows service before the new additions take effect..
Is there a way I can cause my index to be refreshed dynamically?
I am using NEST, but can of course make direct HTTP request to my index end point if needed.

A:

close index client.CloseIndex(indexName);
make changes
Open index client.OpenIndex(indexName);

I belive this should work.
Hope it helps.


Q:

Writing about website component in active voice

I can't seem to figure out how the below sentence would be written in a passive voice, even though my spelling software is complaining about it. Is there a way to rewrite it that I'm not seeing?
"The full-text search field is used a few times per day."
It's specifically highlighting "is used" as the error which seems essential in any sentence structure to me...

A:

It is not an error. There are cases where passive voice should probably be avoided, but not here. Your sentence with active voice would read like this:

(Someone/something) uses the full-text search field a few times per day.

I.e. you need a subject that acts upon the object (full-text search field), but it's really not necessary.
A few examples here of when it is appropriate to use the passive voice.


Q:

How many tries to guess

I have a lottery program that I would like to ask me to take a guess at the 'winning' numbers and then will generate said numbers. When it's done, it will print those numbers back to me, and tell me how many tries it took to arrive at the correct answer.
My code is below. I thought I'd gotten the answer from another thread, was so sure that I closed it - and can't find it now. My question is really just a 'What's wrong with my code?' type, as I think that the code is working, but since the array is 6 numbers I figure it will take the computer some time.
For that reason, I changed the array to just 1 number and it was still taking forever to come back with a "You guessed it in...!" Leading me to believe there is something else wrong I'm missing.
package lottery;

import java.util.Scanner;

public class lottery { // Begin lottery class
    public static void main(String[] args) { // Begin MAIN method

        // Define variables
        Scanner keyboard = new Scanner(System.in);
        int[] lottery = new int[6];
        int randomNum = 1 + (int) Math.random() * 59;
        int noTimes = 1;
        int guess = 0;
        // End variable definition

        System.out.println("Generating lottery numbers, what is your guess?");
        while (guess != randomNum) {
            guess = keyboard.nextInt();
            guess++;
        }

        // Input received - generate numbers now
        System.out.println("Thank you. Generating lottery numbers now...");

        for (int i = 0; i < 6; i++) {
            randomNum = (int) Math.ceil(Math.random() * 59); // Random number created here.
            for (int x = 0; x < i; x++) {
                if (lottery[x] == randomNum) // Here, code checks if same random number generated before.
                {
                    randomNum = (int) Math.ceil(Math.random() * 59);// If random number is same, another number generated.
                    x = -1; // restart the loop
                }

            }
            lottery[i] = randomNum;
        }

        for (int j = 0; j < noTimes; j++) {
            for (int i = 0; i < lottery.length; i++) {
                System.out.print("The winning numbers are: " + lottery[i] + " ");
            }
            System.out.println("\n");
            System.out.print("You correctly guessed in " + guess + " tries.");
        }
    } // End MAIN method
} // End Lottery class

Apparently, I don't know how to do the regular code tag? colors?

A:

There are various problems in your code, which are explained below.

To generate a random integer between 1 and 59 inclusive (but not 60), please use the following code snippet in your 3 places:
int randomNum = 1 + (int)(Math.random() * 59);

The guess-check logic needs to be fixed (as outlined below):
int noTimes = 0;  // Corrected
...
while (guess != randomNum) {
    guess = keyboard.nextInt();
    noTimes++;  // Corrected
}

The last pair of for-loops (the ones just before the 3 consecutive prints) look weird. Here is a more sensible replacement:
System.out.print("The winning numbers are:");
for (int i = 0; i < lottery.length; i++) {
    System.out.print(" " + lottery[i]);
}
System.out.println();
System.out.println("You correctly guessed in " + noTimes+ " tries.");

Other than these, your code looks okay to me so far.
PS: Choosing 6 ordered items from 59 elements has 32.4 billion possibilities.


Q:

What does " we've as much" mean?

"So what we did, we got in touch with a nature reserve out in the country, and asked them what you could see there. And that's when we realised that we've as much, if not more wildlife than they do."
What does the sentence "And that's when we realised that we've as much, if not more wildlife than they do." really mean? Could you please rephrase it?
Especially, " that we've as much" and " if not more wildlife than they do" make me really confused.
Thanks in advance.

A:

"we've as much, if not more wildlife than they do" -> we have as much wildlife as they do, maybe even more than they do.
With a sentence such a this one, you have to look for the noun that the comparison refers to. To get the meaning, skip the "if not more" which is not immediately relevant to get the meaning of the sentence.


Q:

Delegates query in Objective - C

So, I have a decent idea of what a delegate does, why use it, how to implement it etc. and I'm working on implementing it in one of my projects. The problem I'm trying to solve is to decouple my Controller objects from my Network Access class. In this context, the ideas get a little messy in my head.
I somehow intuitively feel that the NetworkAccessClass should be the delegate for a Controller object, because the NetworkAccessClass is acting as a helper for the Controller object. But it seems to work in a reverse fashion, because the following is apparently the right way to do it:
NetworkaccessClass.h
@protocol NetworkAccessDelegate
-(void) requestSucceded:(NSData *) data
-(void) requestFailed:(int) responseCode;
@end
@interface NetworkAccessClass : NSObject
{
    id<NetworkAccessDelegate> networkDelegate;
}

@property(nonatomic, assign) id networkDelegate;

-(void) initWithDelegate:(id) delegate; //

@end

NetworkAccessClass.m
@implementation
@synthesize networkDelegate

-(void) initWithParams:(id) delegate
{
    networkDelegate = delegate;
    // Assign GET/POST vals, create request etc
    [request startAsynchronous];
}

-(void) requestSucceded:(ASIHTTPRequest *) request
{
    if([networkDelegate respondsToSelector:@selector(requestSucceded:)]) {
        // Send the data to the controller object for it to use
        ...
    }
}

-(void) requestFailed:(ASIHTTPRequest *) request
{
    // Same as above. Send to request failed.
}

@end

And finally in my FirstViewController.h
#import "NetworkAccessClass.h"
@interface FirstViewController<NetworkAccessDelegate>
{

}
-(void) requestSucceded:(NSData *) data;
-(void) requestFailed:(int) responseCode;
@end

And the same in SecondViewController.h and so on.
Although this does decouple my Controllers from my Network class, I can't help feel it's wrong because the controllers in this case are acting as delegates or helper methods to the Network Class and not the other way round. Am I missing something basic? Or is this how it is?
Thanks,
Teja.

A:

Delegates aren't "helper methods". Think of them as objects that get notified when something happens. (Although don't confuse them with "Notifications"--that's a different thing entirely.) In this case, your network class does it's stuff and then calls its delegate method on the View Controller that instantiated and fired, it to report the contents of that response to the view controller. The controller will then, presumably, update the view with the data that the network connector got. Classic delegate pattern, right there.


Q:

How can I prove these propositions of infinite sum of random variables?

$x_1, x_2, x_3, ..., x_i, ...$ ~ $uniform(0, 1)$
The actual random variable is the following.
$P_i = (1-x_1)(1-x_2)...(1-x_{i-1})x_i$
And the goal is proving these...

$\sum_{i=1}^{n}P_i \leq 1$
If i's satisfying $P_{i}=0$ exist finitely,  $\lim_{n\to\infty}\sum_{i=1}^{n}P_i \to 1$

How can I do that?

A:

To facilitate this analysis, we denote the partial sums by:
$$S_n \equiv \sum_{i=1}^n P_i
\quad \quad \quad
\text{for all } n \in \mathbb{N}.$$
With a bit of algebra it is simple to establish that:
$$S_n = 1- \prod_{i=1}^n (1-x_i).$$
From this form you should easily be able to establish that $0 \leqslant S_n \leqslant 1$.  Assuming that the underlying random variables in your analysis are IID (you haven't specified if they are independent) then you should be able to show that $S_n \rightarrow 1$ almost surely (i.e., with probability one).


Q:

Calling methods when UITableViewCell is pressed

I would like to call a method when a UITableViewCell is selected/tapped. I could do it easily with a static table view, but it requires a UITableViewController which is not good for me in this case, therefore I'm using a normal vc.
I have 10 specified methods like this:
- (void) methodOne {
 NSLog(@"Do something");
}
- (void) methodTwo {
 NSLog(@"Do something");
}

....

And I would like to call the methodOne when the first cell was tapped, call the methodTwo when the second cell was tapped and so on..
As a first step I set the numberOfRowsInSection to return 10 cells, but have no idea how could I connect the selected cells with the methods. Is there any quick way to do it? It would be a dirty solution to create 10 custom cells and set the every method manually for the custom cells, and there is no free place for it.

A:

You can use this method for whenever any cell is tapped on the table view
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger selectedRow = indexPath.row; //this is the number row that was selected
    switch (selectedRow)
    {
        case 0:
             [self methodOne];
             break;
        default:
             break;
    }
}

Use selectedRow to identify which row number was selected. If the first row was selected, selectedRow will be 0.
Don't forget to set the table view's delegate to your view controller. The view controller also has to conform to the UITableViewDelegate protocol.
@interface YourViewController : UIViewController <UITableViewDelegate, UITableViewDataSource>

As long as the table view has a data source and a delegate, it doesn't matter what kind of view controller it is on. All a UITableViewController really is is a UIViewController that already has a table view on it and is that table view's delegate and data source.


Q:

Query table from model or controller in Laravel

I have table role_user which has two columns user_id and role_id. user_id is the user id from users table and role_id is the id from roles table.
I want to query role_user and show the role name next to each user. Example
table users
user_id username ...
   1      Test user

table roles
role_id  role_name
   1       Admin

table role_user
user_id   role_id
  1          1

I want to show on page
Test user - Admin

I have added this in my Users model
public function role()
{
    return $this->hasOne('App\Role', 'user_id', 'role_id');
}

and this in the controller
public function users()
{
    $userRole = User::find(1)->role;

    return View::make('users', [
        'userRole' => $userRole
    ]);
}

Currently I've got this which is obvious why:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'roles.user_id' in 'where clause' (SQL: select * from roles where roles.user_id is null and roles.user_id is not null limit 1)

The question is how to query role_user table from controller or from model and while displaying the users to display role name too.

A:

You have defined your table so one user can have many roles (using a pivot which is your role_user table.
If a user can only have one role you can remove the role_user table and add a column role_id to your users table.
Using your current implementation change role relationship in user model to following.
public function roles()
{
    return $this->belongsToMany('App\Role', 'role_user', 'user_id', 'role_id');
}

In your controller
public function users()
{
    $users= User::with('roles')->get();

    return View::make('users', [
        'users' => $users
    ]);
}

To simply show the names of roles use implode method of returned collection
@foreach ($users as $user)
    {{ $user->roles->implode('name', ',') }}
@endforeach


Q:

Audio is not playing in Android Emulator in MacBook Pro

This is an issue in MacBook Pro. I figured out the problem after few
  hours of debugging

I am using the following code to create a media player and play an mp3 file. I am using the built-in emulator in Android Studio. Any suggestions for debugging?
import android.media.MediaPlayer;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

    MediaPlayer mediaPlayer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mediaPlayer = MediaPlayer.create(this,R.raw.music);
        mediaPlayer.start();
    }
}

activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.ablejohnson.audiodemo.MainActivity">
</android.support.constraint.ConstraintLayout>

EDIT
For further debugging I added an onErrorListener for mediaPlayer
mediaPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            @Override
            public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
                Log.e("error","what:"+what+",extra"+extra);
                return false;
            }
        });

The following line is getting printed in logs.
D/Atlas: Validating map...
E/MediaPlayer: Should have subtitle controller already set
E/MediaPlayer: Error (1,-19)
E/error: what:1,extra-19

A:

This is a specific issue in Emulator running on MacBook Pro. I tried to run the same app on actual devices and windows+ emulator both cases it was working fine.
The solution here is hacky but it worked for me

turn off Bluetooth and relaunch the emulated device