Android Java Timer()

Question: I'm using Timer() due to its accuracy but works in the same was as PostDelayed Handler. It's called only once. Here is the Timer code:
    public void setWFT() {
        WFT = new Timer();
        WFT.schedule(new TimerTask() {
            @Override
            public void run() {
                WFTTimerMethod();
            }
        }, 60000); // 60 seconds delay
    }

    private void WFTTimerMethod() {
        this.runOnUiThread(Timer_Tick);
    }

    private Runnable Timer_Tick = new Runnable() {
        public void run() {
            // My commands here
        }
    };

This only calls run() once after 60 seconds once the Timer is started. Sometimes, I have to cancel the Timer to Update the delay (replace the "60000" value). To start the Timer again, I simply recreate the Timer by calling WFT() again with the new delay value.
Problem is, when I cancel the timer using:
WFT.cancel();
WFT.purge();

The Timer does not start. the run() doesn't execute when it's supposed to. So my question is do I use cancel() and purge() or just cancel()?
Thanks
Answer: From the Java API on purge():

Most programs will have no need to call this method. It is designed for use by the rare application that cancels a large number of tasks. Calling this method trades time for space: the runtime of the method may be proportional to n + c log n, where n is the number of tasks in the queue and c is the number of cancelled tasks.

So you only need to call cancel()
Comment: Also, as my Timer() acts like a PostDelayed and only called once 60 seconds in the future, will cancel() cancel and destroy the timer before it's execution or will it have no effect on my Timer() as it's a only due to be executed once?
Comment: From the same API link: `cancel()` "Terminates this timer, discarding any currently scheduled tasks. Does not interfere with a currently executing task (if it exists). Once a timer has been terminated, its execution thread terminates gracefully, and no more tasks may be scheduled on it." So it will cancel all future scheduled events.
Answer: from cancel() documentation :

No more tasks may be scheduled on this Timer.

Android Java Timer()


How to jump focus on the second textbox when value of first textbox is maxLenght=3

Question: I have 2 textboxes next to each other for the Telephone number field on an Online Request form.
The maxLenght of the first textbox is = 3, so after the user has entered in the value it must focus on the second textbox.
I added this function to my input type textbox, but it only allows one value and then it already focuses on the second textbox.
onkeypress="if(value.lenght==3)return false;
            document.getElementById('TelNumber2').focus();"

I tried this function too but the same happens
onkeypress="if(event.keyCode==3)return false;
            document.getElementById('TelNumber2').focus();"

These are my textboxes:
First textbox:
input type="textbox" id="TelNumber1" name="TelNumber1" value="" maxLenght="3"
style="width:40px; border: 1px solid #b5b6b5" size="3"
onKeyDown="limitText(this,3);" onKeyUp="MaxText(this,3);" />

Second textbox:
input type="textbox" id="TelNumber2" name="TelNumber2" value="" maxLenght="7"
style="width:115px; border: 1px solid #b5b6b5" size="7"
onKeyDown="MaxText(this,7);" onKeyUp="MaxText(this,7);" />

Will appreciate any help
Camerone
Comment: You spelled length incorrectly.
Answer: You just spelled length incorrectly. This works fine.
<input onkeyup='if (this.value.length >= 3) { document.getElementById("TelNumber2").focus(); }' />

EDIT: I stand corrected. It looks like when the code is in the attribute like that, you do not need to use this. value is already in scope.
Answer: You are returning back before you set the focus. So, your code to set the focus, i.e. document.getElementById('TelNumber2').focus(); is not being called at all.
Try the following. Don't use the return statement.
onkeypress="if(value.length==3) document.getElementById('TelNumber2').focus();"

Cheers! :)
Comment: Thank you for your reply,

I removed the return statement, but now it doesn't even jump focus to the next textbox anymore. It just stays in the first textbox

The function now looks like this;

onkeypress="if(value.lenght==3) document.getElementById('TelNumber2').focus();"

used this one too

onkeypress="if(event.keyCode==3) document.getElementById('TelNumber2').focus(); "


Multiple Numbers under one contact

Question: I have a ListView with a custom Lazy Adapter attached. I pull contacts from the phone and display them in my list. I am having an issue dealing with multiple numbers. If one contact has multiple numbers with different types they appear as different contacts as shown below:

Here is the code for getting my contact list:
public LazyAdapter getContactList(){
    ContentResolver cr = mContext.getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null);
    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                Cursor pCur = cr.query(Phone.CONTENT_URI,null,Phone.CONTACT_ID +" = ?",new String[]{id}, null);
                while (pCur.moveToNext()) {
                    String phoneType = "";
                    int type = pCur.getInt(pCur.getColumnIndexOrThrow(Phone.TYPE));
                    switch (type){
                        case Phone.TYPE_HOME:
                            phoneType = "Home";
                            break;
                        case Phone.TYPE_MOBILE:
                            phoneType = "Mobile";
                            break;
                        case Phone.TYPE_WORK:
                            phoneType = "Work";
                            break;
                        case Phone.TYPE_FAX_HOME:
                            phoneType = "Home Fax";
                            break;
                        case Phone.TYPE_FAX_WORK:
                            phoneType = "Work Fax";
                            break;
                        default:
                            phoneType = "Other";
                            break;
                    }
                    String phoneNo = pCur.getString(pCur.getColumnIndex(Phone.NUMBER));
                    map = new HashMap<String, String>();
                    map.put(KEY_CONTACT_NAME, name);
                    map.put(KEY_CONTACT_NUM, phoneType + ": " + phoneNo);
                    //map.put(KEY_CONTACT_IMAGE, getString(getPhotoUri(id)));
                    contactList.add(map);
                }
                pCur.close();
            }
        }
    }
    adapter = new LazyAdapter(getActivity(), contactList);
    return adapter;
}

And here is my lazy adapter
public View getView(int position, View convertView, ViewGroup parent) {
    View vi=convertView;
    if(convertView==null)
        vi = inflater.inflate(R.layout.contact_list, null);

    TextView contactName = (TextView)vi.findViewById(R.id.contactName); // title
    TextView contactNum = (TextView)vi.findViewById(R.id.contactNum); // artist name
    ImageView thumb_image=(ImageView)vi.findViewById(R.id.list_image); // thumb image

    HashMap<String, String> contact = new HashMap<String, String>();
    contact = data.get(position);

    // Setting all values in listview
    contactName.setText(contact.get(ContactFragment.KEY_CONTACT_NAME));
    contactNum.setText(contact.get(ContactFragment.KEY_CONTACT_NUM));
    return vi;
}

How can I display multiple numbers under one contact if they have multiple numbers?
Thanks
Answer: Figured out the answer. I just added the position number to the phone number I had. When adding the number to the LazyAdapter I looped through the array list and added the numbers like so:
ContactActivity
public LazyAdapter getContactList(){
    ContentResolver cr = mContext.getContentResolver();
    Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI,
            null, null, null, null);
    if (cur.getCount() > 0) {
        while (cur.moveToNext()) {
            map = new HashMap<String, String>();
            String id = cur.getString(cur.getColumnIndex(ContactsContract.Contacts._ID));
            String name = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
            map.put(KEY_CONTACT_NAME, name);
            if (Integer.parseInt(cur.getString(cur.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
                Cursor pCur = cr.query(Phone.CONTENT_URI,null,Phone.CONTACT_ID +" = ?",new String[]{id}, null);
                while (pCur.moveToNext()) {
                    String phoneType = "";
                    int type = pCur.getInt(pCur.getColumnIndexOrThrow(Phone.TYPE));
                    switch (type){
                        case Phone.TYPE_HOME:
                            phoneType = "Home";
                            break;
                        case Phone.TYPE_MOBILE:
                            phoneType = "Mobile";
                            break;
                        case Phone.TYPE_WORK:
                            phoneType = "Work";
                            break;
                        case Phone.TYPE_FAX_HOME:
                            phoneType = "Home Fax";
                            break;
                        case Phone.TYPE_FAX_WORK:
                            phoneType = "Work Fax";
                            break;
                        default:
                            phoneType = "Other";
                            break;
                    }
                    String phoneNo = pCur.getString(pCur.getColumnIndex(Phone.NUMBER));
                    map.put(KEY_CONTACT_NUM + pCur.getPosition(), phoneType + ": " + phoneNo);
                }
                contactList.add(map);
                pCur.close();
            }
        }
    }
    adapter = new LazyAdapter(getActivity(), contactList, "Contact");
    return adapter;
}

Lazy adapter
        TextView contactName = (TextView)vi.findViewById(R.id.contactName); // name
        TextView contactNum = (TextView)vi.findViewById(R.id.contactNum); // number

        HashMap<String, String> contact = new HashMap<String, String>();
        contact = data.get(position);

        // Setting all values in listview
        contactName.setText(contact.get(ContactFragment.KEY_CONTACT_NAME));
        for(int i = 0; i < (contact.size() - 1); i++){
            contactNum.setText(contactNum.getText() + contact.get(ContactFragment.KEY_CONTACT_NUM + i) + "\n");
        }

Multiple Numbers under one contact


output my Cisco 881 config

Question: how does one "print" the startup config or running config.
also what is the best way to import config you have stored as a text file?
Answer: Starting conf:
 #show startup-config
Running conf:
 #show running-config
If you have it already on the box, it's as easy as:
 #copy (desired-running-config) running-config
Comment: `copy new-config running-config` won't actually replace the running-config - it will actually merge the two configs. If you want to completely replace a running configuration, you *must* copy the new config to startup-config and then reload.
Comment: Ah, yeah, I knew there was something I was leaving out.
Thank you.
Answer: I highly recommend you to create a TFTP server, especially if you are experimenting a lot. You can copy much easier from the router to the server and the other way around. Once you have the TFTP server, you can just:
<code>router#copy tftp://new-config running-config
</code>

output my Cisco 881 config


AngularFire pushing to array doesn't work

Question: I'm developing a contact book application that can have groups with members in them. A member has a name, title, and email but that is not important. I have following controller that has an array of all groups, and an index of which group I'm currently dealing with. Also, there is a function that is supposed to add a member to a specific group like below:
   groupControllers.controller('MemberGroupController', ['$scope', '$firebaseArray', '$routeParams', '$location', '$routeParams', function($scope, $firebaseArray, $routeParams, $location, $routeParams) {
        $scope.groups = $firebaseArray(ref);
        $scope.whichGroup =  $routeParams.groupId;
        this.addToGroup = function(member){
            $scope.groups[$scope.whichGroup].members.push(member);
            $scope.groups[$scope.whichGroup].members.$save();
        };
    }]);

I know the addToGroup function is getting the member because it logs the correct member to the console. For some reason when I do this it doesn't actually add the member to firebase. Thanks!
Answer: You only need to call $save on $firebaseObject instances. In fact the call to $save might well break things, since it triggers a potential race condition between the push and the $save.
Update
This will work:
groupControllers.controller('MemberGroupController', ['$scope', '$firebaseArray', '$routeParams', '$location', '$routeParams', function($scope, $firebaseArray, $routeParams, $location, $routeParams) {
    $scope.groups = $firebaseArray(ref);
    $scope.whichGroup =  $routeParams.groupId;
    this.addToGroup = function(member){
        ref.child('groups').child($scope.whichGroup).child('members').push(member);
    };
}]);

Avoid building nests
Note that you seem to be building a so-called "nest", a hierarchy that seems intuitive, but will limit you down the line. Read the section of the Firebase documentation on structuring data to learn more about this.
Consider splitting up the group's members from its other metadata:
groups
  -Jy32724372
    name: "Group 1"
  -Jy46728671
    name: "Group 2"
groups_members:
  -Jy32724372
    twitter:3247423678
    email:23478101
    anonymous:23054389
  -Jy46728671
    email:23478101
    anonymous:45764357

Comment: Thanks! That's helpful, but doesn't solve the current problem. Is there a verison of $save for arrays?
Comment: Thanks! That almost works but I'm getting

Error: Firebase.push failed: first argument  contains an invalid key ($id) in property 'groups.JsW25ppMJYYkAezZzyJ.members.asdf'.  Keys must be non-empty strings and can't contain ".", "#", "$", "/", "[", or "]"
Answer: Call the $save method on firebase object to push local changes to firebase. Have a look on the following AngularFire $save guide:
https://www.firebase.com/docs/web/libraries/angular/guide/synchronized-objects.html#section-api-summary
Checkout the $save method guide. Hope, it helps!!!
Comment: Thanks! But I'm using FirebaseArray, and as the guy above said, $save doesn't really work for arrays.
Comment: You can convert array to Objects, before calling the $save function on firebase object and pass in the object as required by the function.
Comment: Got it!!! In case of firebaseArray, you can use $add method applicable on firebaseArrays. Have a look on following guide on firebase arrays:

https://www.firebase.com/docs/web/libraries/angular/guide/synchronized-arrays.html
Comment: When using $add I get that $add is not a function. Since the members array is inside the firebasearray of Groups, can I not call .$add on it?
Comment: No, you will not be able to call the $add method on any property of the array. You need to call it on returned array of firebaseArray function. In your case, you can call it like:

 $scope.groups.$add(param);

where param, while be your new member to be inserted.
Comment: Yeah but that would add another group, not a member to the group.

I'm trying to $scope.groups.members.$add(param) but that is resulting in $add is not a function
Comment: You are trying to update pre-exiting member in array, rather than saving a new member. In that case, you need to first fetch that particular member of array, then update data and finally call the save method  on array.
`Example:
var item = messages.$getRecord(someRecordKey);
item.user = "alanisawesome";
messages.$save(item).then(function() {
  // data has been saved to our Firebase database
});`

[link](https://www.firebase.com/docs/web/libraries/angular/guide/synchronized-arrays.html#section-modifying-the-array)
checkout the update code block


Is there a way to figure out which trigonometric integrals will be automatically zero?

Question: Now we have some examples of what I mean $$\int_0^{2\pi} \sin x~dx=0$$
$$\int_0^{8\pi} \cos 4x~dx=0$$
$$\int_{\pi}^{2\pi} \sin^3 10x~dx=0$$
Looking at the graph of $f(x)=\sin (x)$ for example it makes some sense to me that $$\int_0^{2\pi} \sin x~dx=0$$ because the region below the $x$ axis will "cancel" with the part above but I don't understand how I can make claims about more general integrals like  $$\int_{\pi}^{2\pi} \sin^3 10x~dx=0$$ which I just got from testing with an online integral tool.
Obviously there is something more deeper going on and I would like to understand when and why I can just claim that an integral will be zero as it will save me a lot of time.
I have had a thought but can't seem to conclude how it would be obvious that any of the less obvious integrals would be zero (like the third one I stated), I imagine that there is some kind of symmetry but I'm just not seeing it.
So if anyone could explain when (in a more general sense not just for the integrals above) and why this works I would appreciate it.
Answer: Roughly speaking, a trig integral (sine or cosine) that includes an integer number of cycles will be zero. The same goes for $\sin nx$ or $\cos nx$. Your "area above the line is the same as area below" is a perfectly good explanation.
As for powers of sines, any odd power of sine can be simplified by the rule
$$
\cos 2x = 1  - 2 \sin^2 x
$$
by rewriting
$$
\sin^2 x = \frac{1 - \cos 2x}{2}
$$
For instance,
$$
\sin^3 x = \sin x \sin^2 x = \sin x \frac{1 - \cos 2x}{2}
$$
Using this, you can express any odd power of sines as a product of lower power sines and cosines (albeit with $2x$ or $3x$ or $4x$, etc., instead of $x$) and such things also integrate to zero be the periodicity-and-symmetry argument.
On the other hand, if you integrate $\sin (x/2)$ from $0$ to $4 \pi$, for instance, you'll get zero as well, but not if you integrate only to $2\pi$.
That's because $2\pi$ is only a half-period for this function.
There are other ways to get zero: integrate $\sin$ from $-a$ to $a$, for instance. These depend on the symmetry of the function rather than its periodicity, and seem somehow different form the examples you gave.
There are other examples that are helpful to know even though you don't get zero. For instance, look at
$$
Q = \int_0^{2\pi} \sin^2(x) dx.
$$
That's clearly the same as
$$\int_0^{2\pi} \cos^2(x) dx,$$
because $\sin$ and $\cos$ are just shifted version of each other, and we're integrating over a whole period of either one.
But that means that
$$
2Q =
\int_0^{2\pi} \sin^2x + \cos^2 x ~dx= \int_0^{2\pi} 1 ~dx= 2\pi,
$$
so
$Q = \pi$.
And in general, integrals of even powers of sines and cosines will work out like this: they're always positive, so their integrals (over any interval of length > 0) will be positive.
Answer: Hint : for the first one, use the change of variable $y = x-\pi$ on $[\pi,2\pi]$, the fact that the function $sin$ is an odd function and $$\int_0^{2\pi} \sin x~dx=\int_0^{\pi} \sin x~dx+\int_{\pi}^{2\pi} \sin x~dx$$
Comment: Nice idea. What would the integral look like after the change of variable? Can you make a change in variable for the other two integrals? Can you generalize this method?
Comment: @John Joy  It's a technique to prove that  $$\int_{\pi}^{2\pi} \sin x~dx=-\int_0^{\pi} \sin x~dx$$ and then the integral is zero. For a generalization I have no idea.
Comment: As per part I of your hint (i.e. $y=x-\pi$) and noting that $dy/dx = 1$
$$\int_0^{2\pi}\sin xdx = \int_0^{2\pi}\sin ((x-\pi)+\pi)dx=\int_{-\pi}^{\pi}\sin (y+\pi)dy=\int_{-\pi}^{\pi}-\sin ydy$$
Sine being an odd function. Do you see how to generalize it now?
Comment: Just forget what I said; I'm way off track. oops.
Answer: Hint
If $f$ is periodic and odd, you will have $$\int_a^{a+T}f(x)dx=0$$
for all $a\in\mathbb R$.
For $$\int_\pi^{2\pi}\sin^3(10 x)dx$$
you have that $x\longmapsto \sin^3(10x)$ is odd and $\frac{\pi}{5}-$periodic. Moreover, $$\int_\pi^{2\pi}\sin^3(10x)dx=\sum_{k=0}^4\underbrace{\int_{\pi+\frac{k\pi}{5}}^{\pi+\frac{(k+1)\pi}{5}}\sin^3(10 x)dx}_{=0\ for\ all\ k}=0.$$
Answer: If $p$ is a period for $f$, then $p$ is also a period for $f^n$.
If the integral is over an interval whose length is a whole number of periods for the integrand, and if the integral over a single period is zero, then that integral is also zero.
A period for $\sin 10x$ is $p=2\pi/10 = \pi/5$. So $\pi/5$ is also a period for $\sin^3 10x$. The interval of integration is of length $\pi$, which is $5\times\pi/5$, so is a whole number of periods of the integrand.
It remains to see that the integral of $f(x)\equiv\sin^3 10x$ over a single period is zero. But that follows quickly from the observation that $$f( x+\frac12 p) = (\sin 10(x+\pi/10))^3$$
$$=(\sin (10x+\pi))^3 = (-\sin 10x)^3$$
$$=-\sin^310x=-f(x)$$
since the integral over the first half of the period would then add out with the integral over the second half of the period.


Force Firefox & Edge to reload page if URL has a hash value

Question: Is there any way to force such browsers as FF and Edge to reload page if URL has a hash value and a user press Enter button in the address bar (like Chrome do)?
Or maybe we could handle some JS events in this case?
P.S. I can't use load hashchange events because if the user press Enter button twice - hashchange event will not triggers.
P.S.S. Figured out that popstate is the event that works well for MS Edge in such situations.
Answer: You could try to listen the Keydown event, if click the enter button, using the window.location.hash to check whether the url has a hash value, then using the location.reload() method to reload the web page.
code as below:
    window.addEventListener('hashchange', function () {
        console.log('The hash has changed!')
    }, false);

    window.addEventListener("keydown", function (e) {
        if (e.keyCode == "13") {
            if (window.location.hash) {
                // Fragment exists
                alert("hashed");
                location.reload();
            } else {
                // Fragment doesn't exist
                alert("not exist");
            }
        }
    }, false);

Comment: Unfortunately, `keydown` does not work when the user press Enter from the address bar
Comment: @Bohdan Maliar, you could use the window.hashchange event with the window keydown event. The keydown event is used to listen the enter press event.


Why prolog fails to find a route to a vertices (in graph)?

Question: I have a question to you:
I have an exercise that says:
Let there be given edges in the directed graph arc (a, b), arc (b, c), arc (a, d), arc (d, e), arc (d, f), arc (f, a) and arc (f, g). Test go / 2, go1 / 3 predicates.
I need to know why Prolog answers false for the following query:
? - go1 (a, b, X).
I have a graph illustrated below and a code pasted below.

The code is here:
arc(a,b).%these are the edges.
arc(b,c).
arc(a,d).
arc(d,e).
arc(d,f).
arc(f,a).
arc(f,g).

go(X,X).
go(X,Y):-arc(X,Z),go(Z,Y).
% without arc(f,a):
% yes ?- go(a,c).
% no  ?- go(d,c).
% no  ?- go(f,a).
% yes ?- go(a,g).
%
% with arc(f,a):
% yes ?- go(a,c).
% out of local stack ?- go(a,g).

member1(H,[H|_]).
member1(H,[_|T]):-member1(H,T).

go1(X,X,_).
go1(X,Y,T):-arc(X,Z),not(member1(Z,[X|T])),go1(Z,Y,[X|T]).
% with arc(f,a):
% yes ?- go1(a,c,[]).
% yes ?- go1(a,g,[]).

So guys, please help me to figure out why it happens? Why does Prolog answer false for the following query:
? - go1 (a, b, X).
I've tried to trace the query and I've gotten the answer that is below:
[trace]  ?- go1(a,b,X).
   Call: (8) go1(a, b, _982) ? creep
   Call: (9) arc(a, _1202) ? creep
   Exit: (9) arc(a, b) ? creep
^  Call: (9) not(member1(b, [a|_982])) ? creep
   Call: (10) member1(b, [a|_982]) ? creep
   Call: (11) member1(b, _982) ? creep
   Exit: (11) member1(b, [b|_1206]) ? creep
   Exit: (10) member1(b, [a, b|_1206]) ? creep
^  Fail: (9) not(user:member1(b, [a|_982])) ? creep
   Redo: (9) arc(a, _1202) ? creep
   Exit: (9) arc(a, d) ? creep
^  Call: (9) not(member1(d, [a|_982])) ? creep
   Call: (10) member1(d, [a|_982]) ? creep
   Call: (11) member1(d, _982) ? creep
   Exit: (11) member1(d, [d|_1206]) ? creep
   Exit: (10) member1(d, [a, d|_1206]) ? creep
^  Fail: (9) not(user:member1(d, [a|_982])) ? creep
   Fail: (8) go1(a, b, _982) ? creep
false.

Well, what I don't understand is why we have here the answer below:
 Exit: (11) member1(b, [b|_1206]) ? creep
   Exit: (10) member1(b, [a, b|_1206]) ? creep
^  Fail: (9) not(user:member1(b, [a|_982])) ? creep

Why does the Prolog not recognize that there is an edge from a to b? Why does it say that b is in the list that there is only [a] after all. Why does this call fail there? What's the reason of the query failure?
Comment: This graph illustration helps greatly, I find it always sadly missing in questions.
Answer: You pass it a free variable X, so that means that the:
member(b, [a|X]).

call will succeed, indeed:
?- member(b, [a|X]).
X = [b|_2142] ;
X = [_2140, b|_2148] ;
X = [_2140, _2146, b|_2154]

Now not(member(Z, [X|T])) will succeed, given that the search of member(Z, [X|T]) fails, but here it will always succeed, since a free variable can always be grounded to a list that contains Z, hence it fails.
If you call it with:
go1 (a, b, [])
it will succeed, since then member(b, [a]) will indeed fail.
You can define a predicate that will reconstruct the path with:
go1(A, B, P) :-
    go1(A, B, P, []).

go1(A, A, [A], _).
go1(A, C, [A|T], V) :-
    arc(A, B),
    \+ member(B, [A|V]),
    go1(B, C, T, [A|V]).
and thus call it with go1(A, B, P) to obtain the path P.
Comment: So this means that we can use the empty list but not a variable to make this thing work. Am I right?
Comment: Okay. I get it. Thank you very much Willem. ;)


Cohomology ring of a wedge sum

Question: Suppose $X$ and $Y$ are finite cell complexes (then I may assume each point has a contractible neighborhood). Suppose we want to compute the cohomology ring structure of $X\vee Y$ (i.e. the wedge sum of both spaces). My lecturer proceeded as follows: use the cohomology Mayer Vietoris sequence. An easy argument shows that
$$H^* (X\vee Y)\cong H^*(X)\times H^*(Y)$$
for $^*>0$; and
$$H^0 (X\vee Y)\cong H^0(X)\times H^0(Y) / \langle(1_X,1_Y)\rangle$$
where $1_X$ denotes the identity of $H^*(X)$ and similarly for $1_Y$.
Then he concluded
that
$$H^* (X\vee Y)\cong H^*(X)\times H^*(Y) / \langle(1_X,1_Y)\rangle$$
and said that "the cohomology ring of the wedge sum is the product of the cohomology rings of the factors modulo some relation in grading zero".
But I don't understand such isomorphism. In fact, $ \langle(1_X,1_Y)\rangle$ is an abelian group (it is not a (graded) ideal of the (graded) product ring). So what sense does it make the quotient as a ring?
I am aware that one could use  reduced cohomology , but I want to work this out by using the absolute version....
Thank you
Answer: The right way to think of $H^*(X\vee Y)$ is not as a quotient of $H^*(X)\times H^*(Y)$ (which, as you point out, does not have a natural ring structure) but rather as a subring.  Indeed, this is what the Mayer-Vietoris sequence actually gives you, since the natural map is $H^*(X\vee Y)\to H^*(X)\times H^*(Y)$, not the other way around.
Specifically, $H^*(X\vee Y)$ is the subring of $H^*(X)\times H^*(Y)$ which contains everything in positive degrees and in degree $0$ consists of the set of pairs $(f,g)\in H^0(X)\times H^0(Y)$ such that $f(x_0)=g(y_0)$, where $x_0$ and $y_0$ are the basepoints of $X$ and $Y$ (considered as $0$-cycles on $X$ and $Y$).  Concretely, if $X$ has $m$ components and $Y$ has $n$ components so $H^0(X)\cong\mathbb{Z}^m$ and $H^0(Y)\cong\mathbb{Z}^n$, with the first coordinate in each corresponding to the component of the basepoint, then $H^0(X\vee Y)$ is the subring of $\mathbb{Z}^{m+n}$ consisting of all tuples whose first and $(m+1)$st coordinates are equal (which is isomorphic to $\mathbb{Z}^{m+n-1}$, by just removing one of those coordinates as redundant).
More conceptually, $H^*(X\vee Y)$ is the subring of $H^*(X)\times H^*(Y)$ consisting of all pairs $(a,b)$ such that $i^*(a)=j^*(b)$, where $i:\{*\}\to X$ and $j:\{*\}\to Y$ are the inclusions of the basepoints.  Indeed, this is exactly the description given by the Mayer-Vietoris sequence.  Since $H^*(\{*\})$ is trivial in positive degrees, this means $i^*(a)=j^*(b)$ is always true in positive degrees, and the only restriction is in degree $0$ as described above.

Cohomology ring of a wedge sum


How to rotate fixed object using PhysicsJS?

Question: I'm learning new javascript lib PhysicsJS (link).
If anybody can help me or show me example of:
How to rotate fixed object (like propeller and balls bounce of it)?
How to set in world some object that bounce with object that not bounce?
Edge-collision-detection (AABB) , Is it possible to do a circle instead of the cube?
Answer: You can rotate objects by changing angular property
like this:

world.on('step', function(){
  barrel.state.angular.pos += 0.02;
  world.render();
});
Answer: Your question about rotating a "fixed" object was asked in another post: PhysicsJS - how to create a body which rotates about a fixed point when struck?
As for setting some objects that bounce and some that don't: This can't be done yet. It's being worked out as part of future development: https://github.com/wellcaffeinated/PhysicsJS/issues/30
For edge collision detection, right now it's only possible to use rectangles. You would have to modify the edge collision detection code to make it a circle.
Comment: Example for fixed object is good but as I wrote, it is necessary to work as a propeller. Propeller should push the ball.


Scheduling Automatic Backups for Virtual Private Web Server running CENTOS 6.3 and WHM

Question: I'm pretty new to administering my own VPS - but thus far am finding it quite a compelling experience. There's something quite refreshing about having complete control over everything it does.
One thing that I would like to look at is a suitable backup solution (a few times a day).
My current setup is as follows:
I'm running a CENTOS 6.3 VPS with a single 25GB hard drive solely for the purpose of hosting websites. I'm using WHM & cPanel for administering them.
I now plan on adding an additional hard disk and hooking it up to my VPS. What I'm not sure about is how I get the two disks talking and get the backup process going. I'm not a seasons SSH-er so don't really know where to start.
I'm hosting with Serverlove (one of the best hosting providers I've used) and am provided with a number of unique identifiers for each hard disk so I imagine these may play a part in linking them together.
I appreciate that this is a little vague (I'm clutching at straws) but any assistance is very much appreciated.
Answer: Read the cPanel/WHM documentation http://docs.cpanel.net/twiki/bin/view/AllDocumentation/WHMDocs/ConfigBackup it will explain how to create backups for your accounts on your VPS/dedicated server.
Note: It is best to have backups stored on a different machine or even datacenter.
Comment: Thanks! Thought it would be more complicated than that. One thing I'm still not clear about is how to make it backup to the other mounted drive. I've followed the instructions as per the http://docs.cpanel.net/twiki/bin/view/AllDocumentation/AllFAQ/BackupFAQ#I%20want%20to%20run%20backups%20on%20a%20mount but can't see a way of referencing this drive in the backup configuration.
Comment: @OliverFarrell for this to happen, you need to use the mount point (is the drive mounted?) If so, it should be in the form of something like `/some/path/on/your/vps/` Typically in my setup I mount the hard drive `/dev/sdb` (where sdb is the name of your hd) as `/backup`. This allows me to `cd` into `/backup` which is really `/dev/sdb` You would put `/backup` under the field **Backup Destination** in `Home »Backup »Configure Backup`
Comment: Wahay! Got it working. Ended up prodding around in fdisk to mount the drive and create a partition. Thanks for giving me a nudge in the right direction @Adam!
Comment: @OliverFarrell yup np. Just remember to vote on the answer - seems like you are new StackExchange family.


Calculating Bayes Factor from a correlation coefficient

Question: I'm wondering whether anyone knows whether it is possible to directly calculate a Bayes Factor (comparing null model of zero correlation to non-zero correlation) given just a correlation coefficient and sample size.
I've found this site that allows you to calculate the Bayes factor from t-test or regression coefficients and am hoping that a similar thing could be done with correlation coefficients.
Many thanks.
Comment: The question is unclear as asked: if your observation is the empirical correlation coefficient, and if you know the distribution of this empirical correlation coefficient under both models being compared, you can compute the Bayes factor. Else you presumably cannot.
Answer: Here is a paper that has some derivations of Bayes factors for correlations (starting on page 21). This paper has some examples of the Bayes factors being used, and there is a link in that paper for the supporting R code. The R code requires just the sample size and the observed correlation.
Comment: Awesome, these papers are excellent! Don't know why I didn't find them in my searches. Thanks so much!
Comment: No problem. I should add that the calculations can also be done easily in a free software called [JASP](https://jasp-stats.org/).
Answer: You could convert the Pearson's $r$ value to its corresponding $t$-statistic and then use the app that you found. The conversion is
$$
t=\sqrt{\frac{(n-2)r^2}{1-r^2}}
$$
where $n$ is the sample size.
Comment: Thanks, that's almost an embarrassingly simply solution.


sql pivot data rows to columns

Question: I have a table similar to the one below. Its a table of items and their related bin locations. Some may have more than one bin location and all of them will have a preferred or primary bin location. How can I run a query to transpose the rows to columns and identifying which the preferred bin as the first?
Item   Bin   Preferred
A      2       Yes
A      3       No
A      1       No
B      3       Yes
B      4       No

The output should look like this:
Item   BinPreferred  Bin2 Bin3
 A     2               3    1
 B     3               4    -

I have tried using the PIVOT function with no luck.
Thanks,
Comment: Is there a fixed limit on the number of bins an item can be in? Or is it dynamic?
Comment: Since you have tsql as a tag, is this SQL Server? If so, what version?
Comment: What is logic of `Bin3`?
Comment: What exactly have you tried? List your `PIVOT` code.
Answer: This should be solution for case that one item has maximal number of 3 bins.
It will select main bin and two other that are not equal,if i am right.
Select distinct
mainbin.item,
mainbin.bin as binpreffered,
bin2.bin as bin2,
bin3.bin as bin3
from table mainbin
left join table bin2 on (mainbin.id=bin2.id)
left join table bin3 on (mainbin.id=bin3.id)
where mainbin.preffered='Yes'
and bin2.preffered='No'
and bin3.preffered='No'
and bin2.id<>bin3.id;

sql pivot data rows to columns


Regarding Android NDK Removal

Question: I have so many android ndks and sdks installed in my laptop and takes up space.
Because I use Android Studio I think I shouldn't uninstall the sdk but there are so many ndks.
Also, that I use Xamarin, I need one package of ndks so I thought which one should I uninstall.
And I can't see them in Programs and Features.
I'm using Windows, by the way. Any ideas?
Answer:
I can't see them in Programs and Features.

The NDKs aren't "installed" like typical Windows programs. They are just extracted zip files. To remove them you just delete them from your file system.
To remove any downloaded with Android Studio, they can be removed via the SDK Manager in Android Studio. For things installed with other tools, they might have a similar solution.
Answer: You can have one installation of Android SDK/NDK and delete the rest. You can manually set the SDK and Path in the Visual Studio and Android Studio to use
Comment: FYI, this does assume that all the tools you use support the NDK you choose. Idk what versions of the NDK Xamarin supports, but Android Studio should support up through r13 beta 2.

Regarding Android NDK Removal


Automatically Monitor MySQL servers for crashed tables

Question: Is there some ready off the shelf solution that would periodically connect to MySQL server, check for crashed tables and automatically initiate repair and/or send administrator an email?
Answer: MySQL has come up with a MySQL Enterprise Monitor web applciation tool that helps you to monitor the MySQL Servers. It can also be used to send an alert the administrators of errors.
Comment: Looks interesting, but it's a bit of an overkill for my task it terms of features and price
Comment: Hmm yes..I tried the evaluation version. It's pretty good to monitor the queries etc. I'm not sure whether there are any open source tools that are available for your requirement.
Answer: I resorted to writing a simple Scheduled task that runs myisamchk periodically
Answer: It is not ready off the shelf, but very easy solution - every table crash is written to MySQL error log (usually .err in data directory. You can create very simple script that is awaken every X minutes and checks this log file (using tail -XXX command for example) for entries with 'marked as crashed'. Then it can alert in any way.
Answer: Is it crash a lot? if it is crashing a lot , I think you have to find the reason for why it is crashing. May be there is a hardware problem or another problems.
Comment: voted down b/c this should be in the comments section.


What is the Distribution of Sum of Squared Errors?

Question: I know this might be a very basic question for anyone, but I'm not sure how to answer it correctly. It was recently asked at an interview. It would be great if someone could help me with answering this.
Comment: Need much more information that what you have given to provide a concrete answer, but I have written up a solution that should help you gain intuition.
Comment: If you didn't start with "Under what assumptions?" you would likely have been wrong anyway
Answer: Assuming that the data is coming from a normal distribution,
$$ X_1, X_2, \ldots, X_n \sim N(\mu, \sigma^2).$$
We obtain an estimate of $\mu$,
$$\bar{X}_n = \dfrac{1}{n} \sum_{i=1}^{n} X_i. $$
The true errors are then $X_i - \mu$ and the estimated errors are $X_i - \bar{X}_n$. So the sum of squared (true) errors are $\sum_{i=1}^{n} (X_i - \mu)^2$.
Note that each $$\dfrac{X_i - \mu}{\sigma} \sim N(0,1) $$ and so
$$\dfrac{1}{\sigma^2} \sum_{i=1}^{n}(X_i - \mu)^2 \sim \chi^2_n. $$
Thus, the sum of squared errors is distributed as a $\chi^2_n$ scaled by $\sigma^2$.
However, as mentioned in the comments, the true sum of squared errors cannot be realized in an estimate since $\mu$ is unknown, and so it is estimated with $\sum_{i=1}^{n} (X_i - \bar{X}_n)^2$. This is harder to find since now $\bar{X}_n$ is from the whole sample and is dependent on each $X_i$. Thus the same steps as above do not work. Intuitively, you lose one degree of freedom in estimating $\mu$, and
$$\sum_{i=1}^{n} \dfrac{X_i - \bar{X}_n}{\sigma^2} \sim \chi^2_{n-1}. $$
On how to get to this point, some details can be found here: Distribution of sum of squares error for linear regression?.
Comment: It's probably worth mentioning the distribution of $\sum_{i=1}^{n}(X_i - \bar{X})^2$ too.
Comment: Sorry about deleting that when you were replying. I realized you had simply taken the question differently than I had and withdrew the complaint. But now if you take it to be the sum of squares of unobservable errors, why mention the estimated errors? There's no simple, obvious path from the easy part you did to the other case. Someone who can't do what you did won't make the leaps required to what you didn't do. I have no big issue if you take the question to be purely about $X_i-\mu$ or about $X_i-\bar{X}$ but it's not really the case that showing the first makes the second easy.
Comment: (ctd) ... If you still want your answer to cover the other case you'd probably at least need to outline how it's done, or at least take dsaxton's suggestion and mention what the distribution is.


react + keycloak + rerender forces new authentification

Question: I am using react with keycloak-js and the framework react-keycloak from panz3r (Link to library ) Everything latest version.
I have almost the same structure like this example here: My project
I am using Functional Components and my App.tsx is also used as container -> I have all states defined here, which will be needed over all components.
Therefore my app looks like this (modified it for simplicity):
import packages
const App: React.FC = () => {
    const keycloakConfig = new (Keycloak as any)({
        realm: 'master',
        url: http://localhost:8280/auth/",
        clientId: 'reactPage',
    });

    const keycloakProviderInitConfig = {
        onLoad: 'check-sso',
    }

    const [data1, setData1] = useState<(Data[])>([]);
    const [data2, setData2] = useState<(Data | null)>(null);
    const [data3, setData3] = useState<(Data[])>([]);

    function onKeycloakEvent(event: any, error: any) {
        console.log('onKeycloakEvent', event, error)
        if (event === "onAuthSuccess") {
          setData1(Set anything);
        }
    }

    function onKeycloakTokens(tokens: any) {
        console.log('onKeycloakTokens', tokens)
    }

    return (
        <KeycloakProvider
            keycloak={keycloakConfig}
            initConfig={keycloakProviderInitConfig}
            onEvent={onKeycloakEvent}
            onTokens={onKeycloakTokens}
        >
            <Router history={myhistory}>

                    <MuiThemeProvider theme={theme}>
                        <React.StrictMode>
                            <RouterComponent
                                data1={data1}
                             data2={data2}
                             ...
                        </React.StrictMode>
                    </MuiThemeProvider>

            </Router>
        </KeycloakProvider>
    );
};

export default App;

The problem:
As soon as I modify any data in the app.tsx container react rerenders the page and the authentification starts again from the beginning.
Now I have an endless loop. It does not matter from where I set any data in the container (app.tsx) as soon as I modify any variable in the container I have a complete rerender of the app and also a new authentification
Answer: I could fix my problem with adding an extra layer before App.tsx. Maybe not the best solution, but it works


Dynamic processing of string field based on user IP

Question: I am a relative newbie looking for guidance on how to best tackle a requirement within the Drupal 7 realm. I have an entity defined with a field containing the URL for an external resource and would like to be able to manipulate the URL string programmatically before rendering the field as a hypertext link within a view. I thought about storing the alternate URLs in the database but the format is subject to change so the dynamic approach is more attractive since it would only involve a single edit. I need to first check the $_SERVER['REMOTE_ADDR'] to determine whether or not to execute this code because if the user is requesting the resource from a location off site then a proxy link must be generated for licensing purposes. What approach would make the most sense for this use case?
Answer: Store the data in the cleanest way possible and then use something like Custom Formatters
or a custom module to modify the presentation of the stored data.
As for using $_SERVER['REMOTE_ADDR'] I feel that I need more data on how and where this will be used.  Have you considered using the permissions or roles built into Drupal?
You would likely need to place this in a preprocess function to conditionally call it for a specific IP address.
For example.
<code>/**
 * Implements hook_preprocess_node().
 */
function hook_preprocess_node(&$variables) {
    //Obviously a real IP is required above for correct syntax.
    if ($_SERVER['REMOTE_ADDR'] == xxx.xxx.xxx.xxx) {
        //Next you can edit the output of any field you want if your remote address matches.
        $variables['field_myfield'][LANGUAGE_NONE][0]['value'] = 'Something Modified Here';
    }
}
</code>
Comment: edited question to clarify the usage of  $_SERVER['REMOTE_ADDR']


Can I leave intercept out in OLS?

Question: I have a model similar to the following:
y = a + b + c + d + e;

a,b, and c are binary variables while d is other control variables and e is error term. For my whole sample, each observation has a 1 for either a,b, or c -- each observation must belong to either a,b, or c (no observations can be 0 in all three). To avoid dummy variable trap, I can run my model two ways:
y = a + b + c + d + e (no intercept)
or
y = intercept + b + c + d + e
I've read around, including here, that intercept should never be dropped unless I am sure the regression goes through the origin. That would mean I should use the second model. However, is it possible for me to drop the intercept in this situation and use the first model -- would my estimates be biased if I dropped the intercept for the first model?
Thanks!
Comment: @Tim I believe this question isn't about using an intercept at all, but about coding categorical variables.  Both models listed in the question are equivalent.
Comment: Do you have reason to believe that the predicted response line would necessarily have to be travel through the origin and be zero at some combination of your dependent variables?  What is the issue with using the second model, which is quite standard?
Comment: I want to use the first model for ease of interpretation. I'm comparing the coefficients across the three groups.
Comment: I think you will find the information you need in the linked thread. (Although that thread discusses these issues in the context of *logistic* regression, the principles are the same.) Please read it. If it isn't what you want / you still have a question afterwards, come back here & edit your question to state what you learned & what you still need to know. Then we can provide the information you need without just duplicating material elsewhere that already didn't help you.
Answer: Yes, without in-depth knowledge of your situation, leaving out the intercept will create bias in the results. If you do not want to use one group as a baseline in the second model, consider using effects coding for your dummy variables?
Effects coding will let you compare the effect of each group to the overall mean, rather than one baseline group.

Can I leave intercept out in OLS?


Distribution of estimator of AR(1) parameter in presence of unit root

Question: I want to apply the unit root test to the original equation before writing it in the Dickey-Fuller form.
The original equation is:
$$
Y_t=b Y_{t-1} + u_t.
$$
I want to test for unit root directly by testing if $b=1$. I read in Enders's book "Applied Time Series Econometrics" that this is equivalent to the Dickey-Fuller test. However he didn't mention what critical value to compare to.
My $t$-test for $b=1$ hypothesis is $-1$. Can you please help me with the critical value?
Assume, the critical value is $-1.95$; what conclusion about unit root can I draw from my test?
Comment: Is this a question from a course or textbook? If so, please add the `[self-study]`
tag & read its [wiki](http://stats.stackexchange.com/tags/self-study/info).
Comment: It is not from a textbook and it is not for a course I'm taking rn. I'm reviewing my econometrics notes before I tutor a student.
Comment: @Abed, was my answer helpful, or do you need some extra elaboration? (Just checking since there was no response from you.)
Comment: Testing that (standardized) coefficient against the Dickey-Fuller distribution *is* the Dickey-Fuller test (not "equivalent to"). You can find the critical values in a Dickey-Fuller table. Testing it against the $t$-distribution is wrong, because it does not have a $t$-distribution under the null of a unit root, as mentioned below.
Answer: Regarding your second question:
If the critical value were indeed $-1.95$ (which I don't think it is as the estimator distribution is nonstandard under the null of a unit root), a test statistic of $-1$ would not allow rejecting the null hypothesis of $b=1$ at the confidence level corresponding to the critical value -- because the test statistic is less extreme (closer to zero) than the critical value: $-1.95<-1<0$.


SSH to private host via a public server

Question: I develop IoT hubs running Linux where I'd like to access them via SSH over the internet for development. They are often placed in remote locations. It seems the E3372 modem I use isn't able to port forward unless I download and install some software from an untrusted source.
I wonder is there a way or a service that would let me connect to a device not visible on the internet (has an internet connection) via a server such as AWS?
The hub might also connect to the server periodically to see if there's a connection request and then the connection is made by the mutually accessible server?
Thanks
Answer: You can make an outbound SSH connection with a RemoteForward tunnel back to the IoT device.
 Do this only for development, never production; your server is vulnerable to your users.
From the IoT device, run:
sleeptime=5
while sleep $sleeptime; do
  start=$(date +%s)
  ssh -N -i /path/to/unlocked/ssh/key \
    -R 1234:localhost:22 firstname.lastname@example.com
  if [ $(date +%s) -gt $((start + 600)) ] || [ $sleeptime -ge 81920 ]; then
    sleeptime=5
  else
    sleeptime=$((sleeptime*2))
  fi
done

I've performed a minimal effort not to loop endlessly when there are connectivity issues, but you'll likely want to do more. This sleeps for 5 seconds, saves the time, runs ssh (see below), and checks the time again. If it's >600s later, reset the sleep timer to 5s. Otherwise, double that timer up to a day (5s, 10s, 20s, 40s, 80s, 160s, 5m, 10m, 20m, 40m, 1.5h, 3h, 6h, 12h, 1d, repeat).
Warning, this solution is as fickle as the reliability of that ssh connection.
The ssh command uses:

-N: Do not execute a remote command, just forward ports and stay opened
-i KEY: Use this key to authenticate (do not password-protect that key)
-R 1234:localhost:22: connections to the remote host are forwarded to the IoT device's ssh server

On phone-home.example.com, add a phone-home-user and lock down its shell so it can't do anything but connect and port-forward (this will let a savvy user forward whatever they want —from your server's LAN— so be careful). Add the key's public side to that user's ~/.ssh/authorized_keys.
Now you can ssh into phone-home.example.com and then run ssh -p 1234 localhost to get to that host. (You could use ssh flag -g for global port forwards to connect from your system rather than jumping through the phone home server, but I don't recommend that since it means anybody else can too.)
If you want to support multiple hosts, you'll either need a system to map the ports to each dev IoT system or else consider a remote socket (see -R remote_socket:host:hostport in man ssh). I suspect sockets are vastly superior here.
 Don't forget: When development completes, revoke that key!
(remove it from authorized_keys)
Also monitor your phone home server's SSH logs for connection/authentication issues and ideally have a way of reaching out to that system's operator (e.g. using more sensible accounts than "phone-home-user").

SSH to private host via a public server


Ajuda com SqlQuery em contexto Entity Framework

Question: Preciso fazer um retorno do meu banco de dados de uma maneira específica, porém estou com um problema, a situação é a seguinte:
Tenho essa query já testada diretamente no SQL Server, e está funcionando perfeitamente:
SELECT
    COUNT (ate.id) AS data,
    pes.tp_raca AS categories,
    pes.genero AS name
FROM
    Atendimento ate
INNER JOIN Pessoa pes ON pes.id = ate.pessoa_id
WHERE
    ate.dt_atendimento >= '2018-08-20'
AND ate.dt_atendimento <= '2018-11-10'
GROUP BY
    pes.tp_raca,
    pes.genero

E retorna o seguinte resultado:
data categories  name
 1        5      Feminino
 1        2      Masculino
 2        5      Masculino

No código C#, a query ficou assim:
using (var context = new SiviasContext())
{
   DateTime inicio = new DateTime(2018,08,20);
   DateTime fim = new DateTime(2018,11,10);
   var result = context.Database.SqlQuery<List<Tuple<int, string, string>>>("SELECT COUNT (ate.id) AS data, pes.tp_raca AS categories, " +
    "pes.genero AS name FROM Atendimento ate INNER JOIN Pessoa pes ON pes.id = ate.pessoa_id " +
    "WHERE ate.dt_atendimento >= "+inicio.ToString("yyyy-MM-dd")+" AND ate.dt_atendimento <= "+ fim.ToString("yyyy-MM-dd") +
    " GROUP BY pes.tp_raca, pes.genero").ToList();
   ViewBag.result = JsonConvert.SerializeObject(result);
}

Do jeito que está, não apresenta erro, mas ele retorna uma lista vazia. Repare que a execução direta no SQL uso a data como string, mas se eu usar como string no código C#, ele apresenta um erro dizendo que não é possível usar uma string em um tipo DateTime. Ou seja, ele reconhece que o atributo de data no banco de dados é do tipo Datetime.
Já tentei usar a data sem passar o .ToString("yyyy-MM-dd") para formatar, porém ele também apresenta um erro reclamando dos 00 (zeros) do time contido na data.
Então, gostaria que pudessem me ajudar nisso, como resolvo?
==============================================================
A resolução foi dada seguindo a ideia do @Pedro Paulo, ficando assim:
List<RetornoConsulta> result = context.Atendimentos.Where(x => x.dt_atendimento >= dt_inicio)
                            .Where(x => x.dt_atendimento <= dt_fim)
                            .Select(g => new {
                                categories = g.Pessoa.tp_raca.ToString(),
                                name = g.Pessoa.genero
                            })
                            .GroupBy(g => new {
                                categories = g.categories,
                                name = g.name
                            })
                            .Select(g => new RetornoConsulta
                             {
                                 data = g.Count(),
                                 categories = g.Key.categories.ToString(),
                                 name = g.Key.name
                             }).ToList();

Comment: Por que voce não usa Linq? Suas models não estão mapeadas? Com linq a busca é mais simples e é mais facil de se usar
Comment: Eu gostaria mas não consegui pelo seguinte: Aqui estou apresentando um exemplo de query já pronta. Pois preciso montar uma query que receba filtros como parâmetros opcionais e também cruzar duas informações utilizando o _group by_, mas não consegui utilizar ele no _IQueryAble_. Funcionaria assim, o usuário escolhe os dois campos a serem cruzados. No retorno verifico qual o primeiro campo a ser cruzado e faço o _group by_ em cima dele, depois o segundo a ser cruzado e faço outro _group by_ dele em cima do anterior, mas tive dificuldade nisso, por isso optei por fazer digitando a query.
Answer: Primeiro crie uma classe que represente o retorno dos dados da sua consulta:
public class RetornoConsulta
{
    public int Data { get; set; }
    public string Categories { get; set; }
    public string Name { get; set; }
}

Na sua consulta iremos passar as datas de início e fim como parâmetros para a query com a classe SQLParameter do Entity Framework, e informaremos que o retorno será uma lista de objetos da nossa classe RetornoConsulta:
List<SqlParameter> parametros = new List<SqlParameter>
{
    new SqlParameter("@dataInicio", inicio),
    new SqlParameter("@dataFim", fim)
};

var result = context.Database.SqlQuery<RetornoConsulta>(
                 @"SELECT COUNT (ate.id) AS Data,
                     pes.tp_raca AS Categories,
                     pes.genero AS Name
                   FROM Atendimento ate
                   INNER JOIN Pessoa pes
                    ON pes.id = ate.pessoa_id
                   WHERE ate.dt_atendimento BETWEEN @dataInicio AND @dataFim
                   GROUP BY pes.tp_raca, pes.genero",
                   parametros.ToArray()
                ).ToList();

Comment: Consegui executar, ele não retornou erro, e retornou uma lista na quantidade que eu esperava, porém vieram vazias: **result: [[],[],[]]**
Comment: Como eu faço pra ele retornar o resultado já reconhecendo a classe?
Comment: Tente alterar da forma que está agora, removendo o `List` do `SqlQuery` e adicionando o `ToList()`.
Comment: Não dá certo, o próprio Visual Studio reclama: **Nõ é possível converter de 'string' para 'System.Type'**
Comment: Tente novamente da forma editada.
Comment: Retorna: **Não existe mapeamento do tipo de objeto System.Collections.Generic.List`1[[System.Data.SqlClient.SqlParameter, System.Data, Version=22.214.171.124, Culture=neutral, PublicKeyToken=b77a5c561934e089]] para um provedor gerenciado de tipo nativo.**
Comment: Tente passar os parâmetros `SqlParameter` individualmente, ao invés de uma lista, veja [aqui](https://stackoverflow.com/a/9149978/8133067), ou use `parametros.ToArray()` ao invés da lista, como sugerido [aqui](https://stackoverflow.com/a/9916146/8133067). Ou faça uma solução mesclada, escreva a query como eu sugeri, sem parâmetros, mas use a classe `RetornoConsulta` que o Pedro Paulo sugeriu, no lugar do `Tuple`.
Comment: Segui a sua ideia e consegui resolver o que precisava, porém utilizando o LinQ. Irei editar minha pergunta para demonstrar como ficou a solução
Comment: @PedroPaulo, depois seria interessante editar sua resposta modificando a passagem da lista `parametros` como argumento do método `SqlQuery()`, porque assim dá erro. Teria que passar cada argumento individualmente ou transformar a lista em array, como sugeri aí em cima.
Comment: Feito, obrigado!
Answer: A query do SQL Server funciona porque lá você está delimitando os valores do campo data entre aspas simples ('):
WHERE
    ate.dt_atendimento >= '2018-08-20'
AND ate.dt_atendimento <= '2018-11-10'

Mas no C# não está.
Faça assim:
var dtIni = inicio.ToString("yyyy-MM-dd");
var dtFim = fim.ToString("yyyy-MM-dd");
var result = context.Database.SqlQuery<List<Tuple<int, string, string>>>(
      "SELECT COUNT(ate.id) AS data, pes.tp_raca AS categories, pes.genero AS name" +
      " FROM Atendimento ate INNER JOIN Pessoa pes ON pes.id = ate.pessoa_id" +
     $" WHERE ate.dt_atendimento BETWEEN '{dtIni}' AND '{dtFim}'" +
      " GROUP BY pes.tp_raca, pes.genero"
   ).ToList();

Usei interpolação de strings (exemplo: $"'{var}'", disponível a partir do C# 6.0, Visual Studio 2015) para o código ficar mas legível:
     $" WHERE ate.dt_atendimento BETWEEN '{dtIni}' AND '{dtFim}'" +

Caso você esteja usando uma versão anterior do C#/Visual Studio, você pode trocar essa linha do filtro para usar String.Format():
      String.Format(" WHERE ate.dt_atendimento BETWEEN '{0}' AND '{1}'", dtIni, dtFim) +

Ou usar a concatenação de strings simplesmente, como estava fazendo antes:
      " WHERE ate.dt_atendimento BETWEEN '" + dtIni + "' AND '" + dtFim + "'" +

EDIÇÃO
Ainda assim o autor da pergunta relatou que ocorria o erro:

A conversão de um tipo de dados nvarchar em um tipo de dados datetime resultou em um valor fora do intervalo.
  (The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.)

Nesse caso o formato de data configurado para a base no SQL Server pode estar diferente de ymd. Para verificar qual formato está configurado para a base, execute a consulta:
DBCC USEROPTIONS

E verifique o registro cuja coluna Set Option seja dateformat.
Para forçar um formato nessa consulta, individualmente, use o comando SET DATEFORMAT ymd (docmentação e referência):
var result = context.Database.SqlQuery<List<Tuple<int, string, string>>>(
      "SET DATEFORMAT ymd; " +
      "SELECT COUNT(ate.id) AS data, pes.tp_raca AS categories, pes.genero AS name" +
      " FROM Atendimento ate INNER JOIN Pessoa pes ON pes.id = ate.pessoa_id" +
     $" WHERE ate.dt_atendimento BETWEEN '{dtIni}' AND '{dtFim}'" +
      " GROUP BY pes.tp_raca, pes.genero"
   ).ToList();

Comment: Olá Pedro, no caso, fiz aqui o teste, mas ele deu na mesma, ele retornou o erro _A conversão de um tipo de dados varchar em um tipo de dados datetime resultou em um valor fora do intervalo_.
Comment: Estranho, não faz muito sentido. Faz de novo como o Marcelo Macedo tinha sugerido, coloca um breakpoint ai nessa linha em que você monta a query, seleciona todo o texto da consulta e verifica qual foi o texto que ele gerou, depois pega esse mesmo texto e cola numa query no SQL Server Management Studio e roda, para ver se dá o mesmo erro.
Comment: Muito estranho mesmo. Executei no SQL Server, ele retornou _A conversão de um tipo de dados varchar em um tipo de dados datetime resultou em um valor fora do intervalo_. Se eu tiro as aspas, ele não dá erro mas também não retorna resultado
Comment: Aspas simples (`'`) ou aspas duplas (`"`)? Mas você não tinha dito que aquela consulta da pergunta, com aspas simples (`'`) estava funcionando no SQL Server? A forma normal de representar datas no SQL Server é usando as aspas simples, veja [aqui](https://docs.microsoft.com/en-us/sql/t-sql/data-types/datetime-transact-sql).
Comment: Quando você faz uma consulta no SQL Server Management Studio, em que formato ele exibe as datas? Veja o comando [SET DATEFORMAT](https://docs.microsoft.com/en-us/sql/t-sql/statements/set-dateformat-transact-sql) e essa resposta [aqui](https://pt.stackoverflow.com/a/141970/86952).
Comment: Entendi, então, eu verifiquei aqui, eu estava utilizando o _Navicat Premium_ para executar as querys, estava funcionando nele, mas quando executei no _SQL Server_ apresentou o erro de conversão da data
Comment: E como as datas são exibidas quando você visualiza os registros no SQL Server Management?
Comment: Retornei um _select * from_ e mostra assim: **2018-11-08 10:36:27.710**
Comment: Tenta fazer a consulta assim: `SET DATEFORMAT ymd; SELECT ...` para ver se dá certo.
Comment: Deu certo no SQL Server, e como faria no sistema então?
Comment: Consegui executar colocando o **SET DATEFORMAT ymd;** antes do **SELECT**, ele não retornou erro, e retornou uma lista na quantidade que eu esperava, porém vieram vazias: result: [[],[],[]]
Comment: @TácioBrito, ao invés de fazer `context.Database.SqlQuery>>("SELECT ...").ToList();`, tenta fazer assim: `context.Database.SqlQuery("SELECT ...").ToList>();`.
Comment: @TácioBrito, eu estava fazendo uma pesquisa e parece que o `context.Database.SqlQuery()` não pode ser usado mesmo em tipos "anônimos", como `Tuple`. Talvez você tenha que fazer uma solução como a que o Pedro Paulo sugeriu mesmo, criando uma classe específica com os campos que serão retornados na consulta.
Comment: Entendi, obrigado
Answer: Tenta utilizar between. Ficando assim:
var result = context.Database.SqlQuery<List<Tuple<int, string, string>>>("SELECT COUNT (ate.id) AS data, pes.tp_raca AS categories, " +
    "pes.genero AS name FROM Atendimento ate INNER JOIN Pessoa pes ON pes.id = ate.pessoa_id " +
    "WHERE ate.dt_atendimento between "+inicio.ToString("yyyy-MM-dd")+" AND "+ fim.ToString("yyyy-MM-dd") +
    " GROUP BY pes.tp_raca, pes.genero").ToList();
   ViewBag.result = JsonConvert.SerializeObject(result);

Comment: O Between deu na mesma, é o mesmo resultado
Comment: Já tentou "dd/MM/yyyy" ?
Comment: Também não, sem a condição WHERE da data ele retorna, mas com ela não ta funcionando
Comment: Cara põe um breakpoint na variável result e passa o mouse pra ver o que ta indo pra ela de string. Pode ser que tenha que pôr duas aspas duplas antes e duas depois das strings internas, ficando assim: ""yyyy-MM-dd"" .
Comment: Outra coisa que eu vi aqui @TácioBrito é que data e name são palavras reservadas do SQL, tenta por outras palavras no lugar.
Comment: A query retorna assim: SELECT COUNT (ate.id) AS data, pes.tp_raca AS categories, pes.genero AS name FROM Atendimento ate INNER JOIN Pessoa pes ON pes.id = ate.pessoa_id WHERE ate.dt_atendimento BETWEEN 2018-08-20 AND 2018-11-10 GROUP BY pes.tp_raca, pes.genero

a data vem sem aspa, mas se eu colocar aspa ele reclama dizendo que é sttring, ocorrendo incompatibilidade com o tipo DateTime. Mas no SQL direto funciona
Comment: Tenta aquela outra formatação de data. "dd/MM/yyyy". E testa esse lance de aspas duplas também.
Comment: Já testei todos essas sugestões que me passou, é emitido Exception em ambas
Comment: Até a questão das palavras reservadas que te falei acima?
Comment: Outra coisa que eu vi aqui @TácioBrito é que data e name são palavras reservadas do SQL, tenta por outras palavras no lugar. – Marcelo Macedo 13 mins atrás
Comment: Sim coloquei outras: COUNT (ate.id) AS qtd, pes.tp_raca AS categorias, "pes.genero AS nome

nada ta pegando, não to entendendo. Assim, poderia usar outra maneira pra essa query, por exemplo o CodeFirst, mas eu preciso fazer group by de campos dinamicamente, conforme o usuário seleciona, pra cruzar dados, mas nao consegui retornar pelo IQueryAble
Comment: Cara, posso ta enganado. Sua query tem duas colunas e ta passando pra uma list. A List não suportaria 1 só coluna? Tira uma coluna pra testar.
Comment: Me retornou um array de array vazio, assim: [[]]


How to add an Indicator to UIImagePickerController

Question: I have an image picker to pick multiple images from the photo library. The picked photos are resized and saved to file in imagePickerController:didFinishPickingMediaWithInfo:. It takes a few seconds.
Could I put an indicator on the view?
I have tried to use addSubview:indicatorView in imagePickerController:didFinishPickingMediaWithInfo: method. But indicatorView doesn't appear. It gets dismissed with the imagePickerView.
Answer: You should add the UIActivityIndicatorView at the top of the view hierarchy or it will get dismissed with the UIPickerViewController, unless you use a callback after the resize operation and in the callback you dismiss the UIImagePickerController.
Or you could use a progress HUD like SVProgressHUD.
Hope this helps =)
We did a little chat session and solved this way:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    dispatch_async(dispatch_get_main_queue(), ^{
          UIView *primaryImage = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,460)];
          primaryImage.backgroundColor = [UIColor redColor];
          primaryImage.alpha =0.9;

          UIView *secondaryImage = [[UIView alloc] initWithFrame:CGRectMake(0,0,70,70)];
          secondaryImage.center = CGPointMake(160, 240);
          secondaryImage.backgroundColor = [UIColor blackColor];
          secondaryImage.alpha = 0.9;
          secondaryImage.layer.cornerRadius = 12;
          [primaryImage addSubview:secondaryImage];
          UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 25, 25)];
          indicator.center = CGPointMake(35, 35);
          [indicator setHidesWhenStopped:NO];
          [secondaryImage addSubview:indicator];
          [indicator startAnimating];

          [indicator release];
          [secondaryImage release];

          [picker.view addSubview:primaryImage];

         [primaryImage release];
     });

    // Put here the code to resize the image

    dispatch_async(dispatch_get_main_queue(), ^{
    // Dismiss the picker controller

    });
});

Comment: Yes, i put it at the top of the view hierarchy, but it did not show up, until the dismissing animated period. That's what i mean "it will get dismissed with the UIPickerViewController".
Comment: For "at the top of the view hierarchy" I mean in the UIWindow. Anyway you could try to add the UIIndicatorView when you create the UIPickerController and control it with a ivar.
Comment: You mean add to the Window? let me try, still do not work. Yes I have created an indicator and hide it first, but once i set the hidden to NO, it doesn't work.
Comment: Is indicator an UIActivityIndicatorView instance? If yes, you should use hidesWhenStopped and then it will be visible when you call the startAnimating method.
Comment: Actually I put the indicatorView in side anotherUIView. such as  [anotherUIView addSubview:indicator]; And try to control the anotherUIView to hide and show.
Comment: I employed the ELCImagePickerController. Just modify the code inside "- (void)elcImagePickerController:(ELCImagePickerController *)picker didFinishPickingMediaWithInfo:(NSArray *)info " method. There i will resize and save the picked photos, so it takes a few seconds. https://github.com/elc/ELCImagePickerController
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/11199/discussion-between-greyhands-and-lu-yuan)
Comment: could you help me out of this problem? http://stackoverflow.com/questions/10633957/set-annotations-title-as-current-address


Passar parâmetros por jquery através de uma tabela

Question: uma dúvida: Tenho uma tabela e nela duas colunas, que são: CNPJ e Razão Social. Bem, preciso fazer o seguinte: Quando eu clico na coluna CNPJ, por exemplo, deveria passar o valor do CNPJ que está sendo clicado e ir como parâmetro para um método na Controller e retornar informações do BD. A questão toda é como passar o valor do CNPJ que está numa determinada coluna da tabela. Abaixo minha função jquery que pasa os parâmetros(esqueleto).
function MontaDetalhePDV() {
    $.ajax({
        url: '/GerenciarPDV/DetalhesEvento',
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        type: "POST",
        data: JSON.stringify({ _cnpj: resultado_cnpj, _razao: resultado_razao }),
        success: function (data) {
        },
        error: function (error) {
        }
    });
}

Meu método Controller:
[HttpPost]
public JsonResult DetalhesEvento(string _cnpj, string _razao)
        {
            V99_WEBEntities db = new V99_WEBEntities();

            var detalhe_evento = (from web in db.T_PDV

                             join testab in db.T_TipoEstabelecimento on web.IDTipoEstabelecimento equals (testab.IDTipoEstabelecimento)
                             join trede in db.T_TipoRede on web.IDTipoRede equals (trede.IDTipoRede)
                             join tusupdv in db.T_UsuarioPDV on web.IDPdv equals (tusupdv.IDPDV)
                             join tusu in db.T_Usuario on tusupdv.IDUsuario equals (tusu.IDUsuario)
                             join tstatus in db.T_CRM_StatusPDV on web.CNPJ equals (tstatus.DE_Cnpj)

                             select new
                             {
                                 web.CNPJ,
                                 web.RazaoSocial,
                                 web.NomeFantasia,
                                 web.Endereco,
                                 web.Bairro,
                                 web.Cidade,
                                 web.Estado,
                                 web.CEP,
                                 web.Complemento,
                                 web.Numero,
                                 web.QtdeCheckOuts,
                                 web.Telefone,
                                 web.NomeRede,
                                 web.Email,
                                 web.Celular,
                                 web.IS_Ativo,
                                 tstatus.IT_Status,
                                 trede.Nome,
                                 tipo = testab.Nome,
                                 contato = tusu.Nome,
                                 cel_contato = tusu.Celular,
                                 tel_contato = tusu.Telefone
                             });

            if (!string.IsNullOrEmpty(_cnpj))
                detalhe_evento = detalhe_evento.Where(cn => cn.CNPJ == _cnpj);
            if (!string.IsNullOrEmpty(_razao))
                detalhe_evento = detalhe_evento.Where(rz => rz.RazaoSocial == _razao);

            var detalheEvento = detalhe_evento.ToList();

            return Json(new { detalheEvento }, JsonRequestBehavior.AllowGet);
        }

resultado_cnpj e resultado_razao, são apenas sugestão, nada mais.
Alterei apenas o nome do método para DetalhesEvento.
function DetalhesEvento() {

    var str = "";
    //var obj = {};

    $('table tbody tr').click(function () {
        var obj = {};
        $(this).each(function () {
            obj = {
                _cnpj: $(this).find('td').eq(0).text(),
                _razao: $(this).find('td').eq(1).text()
            }
        });
    });

    $.ajax({

        url: '/GerenciarPDV/DetalhesEvento',
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        type: "POST",
        data: obj,
        success: function (data) {

            alert();

            str += '
';
            str += '
';
            str += '
';
            str += '
';
            str += 'CNPJ	';
            str += 'Razão Social	';
            str += '
';
            str += '
';
            str += '
';

            $(data.detalheEvento).each(function () {

                str += '
';// onclick="DetalhesEvento(this)"
                str += '' + this.CNPJ + '	';
                str += '' + this.RazaoSocial + '	';
                str += '
';
            })
            str += '
';
            str += '
';
            str += '
';

            str += '
';
            str += '
';
            str += 'Situação:';

            switch(data.detalheEvento[0].IS_Ativo){
                case true:
                    str += '  Ativo  ';
                    break;
                case false:
                    str += '  Inativo  ';
                    break;
            }
            str += 'Status:';
            switch (data.detalheEvento[0].IT_Status) {
                case 1:
                    str += ' OK';
                    break;
                case 2:
                    str += ' Alerta';
                    break;
                case 3:
                    str += ' Erro';
                    break;
            }
            str += '
';

            str += '
';
            str += 'Razão Social:';
            str += '' + data.detalheEvento[0].RazaoSocial + '';
            str += '
';

            str += '
';
            str += 'Nome de Fantasia:';
            str += '' + data.detalheEvento[0].NomeFantasia + '';
            str += '
';

            str += '
';
            str += 'CNPJ:';
            str += '' + data.detalheEvento[0].CNPJ  + '';
            str += '
';

            str += '
';
            str += 'Endereço:';
            str += '' +  data.detalheEvento[0].Endereco + '';
            str += '
';

            str += '
';
            str += 'Número:';
            str += '' + data.detalheEvento[0].Numero  + '';
            str += 'Complemento:';
            str += '' +  data.detalheEvento[0].Complemento + '';
            str += '
';

            str += '
';
            str += 'Bairro:';
            str += '' +  data.detalheEvento[0].Bairro + '';
            str += 'CEP:';
            str += '' + data.detalheEvento[0].CEP  + '';
            str += '
';

            str += '
';
            str += 'Cidade:';
            str += '' + data.detalheEvento[0].Cidade  + '';
            str += 'Estado:';
            str += '' + data.detalheEvento[0].Estado  + '';
            str += '
';

            str += '
';
            str += 'Telefone Fixo:';
            str += '' + data.detalheEvento[0].Telefone  + '';
            str += 'Celular:';
            str += '' +  data.detalheEvento[0].Celular + '';
            str += '
';

            str += '
';
            str += 'Tipo:';
            str += '' + data.detalheEvento[0].tipo + '';
            str += 'Qtde Checkouts:';
            if (data.result_dim[0].Checkout > 0) {
                str += '' + data.result_dim[0].Checkout + '';
            } else {
                str += 'Não há informação'
            }
            str += '
';

            str += '
';
            str += 'Tipo da Rede:';
            str += '' +  data.detalheEvento[0].Nome + '';
            str += 'Nome da Rede:';
            str += '' +  data.detalheEvento[0].NomeRede + '';
            str += '
';

            str += '
';
            str += 'Contato:';
            str += '' + data.detalheEvento[0].contato + '';
            str += '
';

            str += '
';
            str += 'Tel. Contato:';
            str += '' + data.detalheEvento[0].tel_contato + '';
            str += 'Cel. Contato:';
            str += '' + data.detalheEvento[0].cel_contato  + '';
            str += '
';

            str += '
';
            str += '
';
            str += '
';
            //str += '
';
            str += '<button type="button" class="btn btn-danger">Inativar</button>';
            str += '<button type="button" class="btn btn-primary">Add</button>';
            str += '
';
            str += '
';
            str += '
';

            str += '
';
            str += '
';
            str += '
';
            str += '
';
            str += '
';
            str += 'ID Evento	';
            str += 'Tipo	';
            str += 'Usuário	';
            str += 'Data de Inclusão	';
            str += '	';
            str += '
';
            str += '
';

            str += '
';

            $(data.result_evento).each(function () {

                //var data_evento = getFormattedDate(data.result_evento);

                str += '
';
                str += '' + this.ID_CRM_Evento + '	';
                str += '' + this.ID_TipoEvento  + '	';
                str += '' + this.DE_Usuario  + '	';
                str += '' + getFormattedDate(this.DT_Inclusao) + '	';
                str += '<button type="button" class="btn btn-primary">Abrir</button>	';
                str += '
';
            });
            str += '
';
            str += '
';
            str += '
';

            str += '
';
            str += '</form>';
            str += '
';

            cont++;

            $('#montaPesquisaGrid').html(str);
            str = "";

        },
        error: function (error) {

        }

    });
}

Fiz essa função, mas não sei como chamá-la no meu código.
$(document).on('click', 'td', function (e) {
    var ancora = $(this).find('label a');
    var valor = ancora.text();

    $('#txtCnpjRazao').val(valor);
});

Esse campo(txtCnpjRazao) é do tipo HiddenField e eu quero pegar o valor dele na minha variável no jquery e passar para o controller.
Comment: Onde está o seu problema? Seu Post está chegando a sua Ctrler?
Comment: Não é problema, mas sim, como fazer. Como eu pego o cnpj que está numa coluna de uma tabela e passo isso como parâmetro, via jquery para minha controller.
Answer: Você pode capturar o click na tr e montar o objeto, exemplo:
$('table tbody tr').click(function(){
    var obj = {};
    $(this).each(function(){
        obj = {
            _cnpj: $(this).find('td').eq(0).text(),
            _razao: $(this).find('td').eq(1).text()
        }
    });
});

JSFiddle
Ou você pode colocar onclick na tr e montar o objeto dentro da sua função:
HTML

JS
function MontaDetalhePDV(tr) {
    var obj = {};
    $(tr).each(function(){
        obj = {
            _cnpj: $(this).find('td').eq(0).text(),
            _razao: $(this).find('td').eq(1).text()
        }
    });
    $.ajax({
        url: '/GerenciarPDV/DetalhesEvento',
        dataType: "json",
        contentType: "application/json; charset=utf-8",
        type: "POST",
        data: obj,
        success: function (data) {
        },
        error: function (error) {
        }
    });
}

Comment: Tentei de várias formas e não consegui fazer funcionar. Simplesmente não dá erro nenhum, mas não chama o método da controller e consequentemente não retorna no sucesso do ajax. Vou editar o meu post e postar o que deveria retornar, o html que deveria ser montado.


When Is it Preferred to Allocate vs Rent an Array?

Question: I am currently designing a solution, and have found myself in an interesting performance scenario.  I have placed a very simple solution demonstrating this scenario that can be found here:
https://github.com/Mike-EEE/Stash/tree/master/AllocationVsRent
At heart of this issue is allocation vs. rental of an array.  One of the methods found in this solution performs a rental, as seen here:
[Benchmark]
public int Rented()
{
    var array = _pool.Rent(2);
    array[0] = 1;
    array[1] = 2;
    var result = array[0] + array[1];
    _pool.Return(array);
    return result;
}

The other performs an allocation, as seen here:
[Benchmark(Baseline = true)]
public int Allocated()
{
    var array = new int[2];
    array[0] = 1;
    array[1] = 2;

    var result = array[0] + array[1];
    return result;
}

When running these two benchmarks I get the following results:
BenchmarkDotNet=v0.11.5, OS=Windows 10.0.17763.475 (1809/October2018Update/Redstone5)
AMD Ryzen 7 2700X, 1 CPU, 8 logical and 4 physical cores
.NET Core SDK=3.0.100-preview5-011568
  [Host]     : .NET Core 3.0.0-preview5-27626-15 (CoreCLR 4.6.27622.75, CoreFX 4.700.19.22408), 64bit RyuJIT
  DefaultJob : .NET Core 3.0.0-preview5-27626-15 (CoreCLR 4.6.27622.75, CoreFX 4.700.19.22408), 64bit RyuJIT

|    Method |      Mean |     Error |    StdDev | Ratio | RatioSD |  Gen 0 | Gen 1 | Gen 2 | Allocated |
|---------- |----------:|----------:|----------:|------:|--------:|-------:|------:|------:|----------:|
|    Rented | 29.563 ns | 0.1736 ns | 0.1450 ns |  5.01 |    0.27 |      - |     - |     - |         - |
| Allocated |  5.825 ns | 0.1440 ns | 0.2522 ns |  1.00 |    0.00 | 0.0077 |     - |     - |      32 B |

While the Allocated benchmark is faster, it does invoke garbage collection.  Whereas for the Rented benchmark, it is slower but there is no garbage collection penalty.
So my fundamental question is: which one is preferred?  Is it OK to go with the allocation even though it does produce garbage?  While it is faster, its use still feels dirty to me, excuse the pun.
Please note: I cannot use stackalloc as my scenario in practice involves calling between two methods, and as I understand it this precludes the use of that.  I am certainly open to any suggestions that I am overlooking to get the best of both worlds here.
Thank you in advance for any assistance.
Comment: If those arrays are indeed so small, can't you use `stackalloc` represented as a `Span`? And then pass it to the underlying methods?
Comment: Even nanoseconds matter if they are iterated millions of times. But regardless of this there is no one right approach for all cases - everything depends on requirements. The ultimate adverbs like ever, never, always, etc. aren't applicable for engineering. You can still use allocation like many software do if your performance indicators aren't affected by this - it's simpler and more usual. You can switch to allocation-free approach if you can't achieve desirable performance profile and GC contributes to this situation. There are different types of solutions which use memory in different ways.
Comment: Wow @KonradKokosa I thought for sure I had tried this before but was under the impression that `Span` had some weird limitations that kept me from using it from my design.  I will look further into this to see if I can use that.
Comment: Your micro-scenarios don't give enough information to make any conclusion what's better for your situation. There can be many factors dictated by specific requirements (which you didn't provide) and even it's possible that it doesn't matter what approach to use if it has negligible impact on a final result.
Comment: @DmytroMukalov We are in nanosecond land so it's all negligible. :)  I suppose I am more interested in the general theory and approach here.  Is it ever OK to allow allocation if it is faster?  As it does lead to GC, there is a hidden cost there.
Comment: That's good insight and feedback, @DmytroMukalov, thank you!
Comment: More likely the benefits of `ArrayPool` begin when you are allocating large arrays (so they end up in Gen2 -not Gen0- or in the Large Object Heap, which are insanely slower to collect, since they clean up the whole managed heap [Full GC, they call it])
Answer: Since there is too much involved with my scenario to explain further (trying to keep it simple here), I am solving this problem by allowing the end developer to decide whether they want speed or garbage.
For a little more context, the API I am developing is zero-allocation first and foremost and speed as an important but secondary focus.
In all other calls, the API is zero-allocation and faster than an existing API that I am testing against, with the exception for this call.  So, by default, I will make it zero-allocation to be consistent with the rest of the API, but if the consuming/end developer is OK with garbage and wants those few extra nanoseconds, they can easily allow that instead.


Calls wrong image file path

Question: I have simple Image field, its file path is set to field/image so when you upload a file, its path is something like /sites/default/files/field/image/image.jpg.
But when I create content and upload the file, first of all, the thumbnail preview doesn't show up and when saved, the image is not loaded, because for some reason it's calling a wrong path of sites/default/files/styles/large/public/field/image/image.jpg.
But why? Why that path? There's no such path. Who is calling the wrong URL? It should call the correct path where the picture was uploaded and that's /sites/default/files/field/image/image.jpg.
I've tried using "Original Image" for the image field display, instead of the "Large" style, but no matter what I use, /styles/large/public/ is added to the URL.
Permissions are correct on the /sites/default/files folder (the original image is uploaded successfully), there are no related errors in the dblog report, and there's no problem with GD/Imagemagick in the status report.
What could be adding the extra part to the image URL?
Comment: Also I noticed even if it all has 777 permissions, it doesn't upload any image to sites/default/files/styles/thumbnail/public/ or any other image style dir/public/ so it obviously doesn't load it too. So all paths/dirs has 777 perms except /default/ has 555.
Comment: Just to clear it up, there wouldn't be an image uploaded to the /styles folder. If the file doesn't exist when it's requested, Drupal generates (or at least attempts to generate) the file and serve it straight back to the client. For subsequent requests the file exists, so the generation isn't necessary. It seems you have multiple problems: 1, the derivative images aren't being generated, and 2, the paths for `` tags are somehow being re-written
Comment: So what causes that?
Comment: For the image styles check your server error logs, if there's nothing in there I'm not sure what to suggest. For the other problem, check custom/contrib modules that might be to blame (disable them methodically until the problem is fixed). But it would be worth fixing the former problem first, it might also fix the latter
Answer: You might simply be editing the wrong "display". Happened to me :)
If you have the Display Suite Drupal module installed, node types can each have several option sets (called "displays") how to display their fields, and a template or view then selects one of them to show the node. With the Taxonomy display Drupal module, the same is possible for taxonomies.
In these cases, you might simply be trying to adapt the image style setting in the wrong display. Check if you have a second line of tab-like options (starting with "Standard") for either nodes or taxonomies. In that case you have multiple displays for this node type / taxonomy, and you have to configure the image type for the right one.
You'll have to visit one of these admin menu items to check for displays:

"Structure → Content Types → [your content type] → Manage Display"
"Structure → Taxonomy → [your taxonomy] → Manage Display"

Calls wrong image file path


Magento 2:How get price configurable in product list

Question: How can get price product
With simple product:
$oldPrice= $_product->getPrice();
$newPrice= $_product->getSpecialPrice();
it returns the right results
With configuable product:
$oldPrice= $_product->getPrice(); //return Null
$newPrice= $_product->getSpecialPrice(); // return Null
I have 1 configuable product and 2 simple products
TestCon1
 Simple1: Price 120$. Special price: 100$
 simple2: Price 120$. Special price: 90$

I need get  price of configuable return: TestCon1 Price 120$. Special price: 90$.
i use $oldpriceConf= $_product->getFinalPrice(); // retunr 100$
Comment: Did you found a solution for this?
Comment: How to get the price of the child product
Answer: Configurable products don't have any regular price or special price.
On front end the price of their child product is taken as their regular price.
Comment: Yes! i know! Can you help me get price simple product of configurable(Magento 2 is new). Thanks!
Answer: Try this for configurable product prices:
Regular price:
$oldPrice = $_product->getPriceInfo()->getPrice('regular_price')->getValue();

Final price:
$finalPrice = $_product->getPriceInfo()->getPrice('final_price')->getValue();

Answer: Take a look at this file in Magento 2:
vendor\magento\module-catalog\Block\Product\ListProduct.php

It contains 2 methods that you can paste into your block:
/**
 * @param \Magento\Catalog\Model\Product $product
 * @return string
 */
public function getProductPrice(\Magento\Catalog\Model\Product $product)
{
    $priceRender = $this->getPriceRender();

    $price = '';
    if ($priceRender) {
        $price = $priceRender->render(
            \Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE,
            $product,
            [
                'include_container' => true,
                'display_minimal_price' => true,
                'zone' => \Magento\Framework\Pricing\Render::ZONE_ITEM_LIST,
                'list_category_page' => true
            ]
        );
    }

    return $price;
}

/**
 * Specifies that price rendering should be done for the list of products
 * i.e. rendering happens in the scope of product list, but not single product
 *
 * @return \Magento\Framework\Pricing\Render
 */
protected function getPriceRender()
{
    return $this->getLayout()->getBlock('product.price.render.default')
                ->setData('is_product_list', true);
}

Use like so in your .phtml template file:
<?php echo $this->getProductPrice($product); ?>

This works well to display preformatted price and sale price with crossed out old price.


Trocar de view pelo controller (Ng-Click)

Question: Estou utilizando o ng-route para desenvolver uma single page application com o angularjs+laravel. Estou com um problema na parte de trocar de view por meio do ng-click e o controller.
Tenho um botão em uma view, e gostaria que ao fosse clicado ele redirecionasse para outra view, levando uma informação (id).
Esse é meu arquivo de rotas do angular. Quero redirecionar da página Gerenciar Colaboradores para a página Novo Colaborador.

angular.module('registrosGerais')
   .config(function($routeProvider) {
        $routeProvider
        .when('/', {
            templateUrl: 'views/index.html',
            controller: ''
          })
          .when('/colaboradores', {
            templateUrl: 'views/colaboradores/gerenciarcolaboradores.html',
            controller: 'colaboradoresController'
          })
          .when('/colaboradores/novocolaborador', {
            templateUrl: 'views/colaboradores/novocolaborador.html',
            controller: 'colaboradoresController'
          })
          .otherwise({
            redirectTo: '/colaboradores'
          });
      });

Esse é o botão que deve ser clicado para que redirecionar a nova view.

<button id="btn-add" class="btn btn-primary btn-xs"
        ng-click="toggle('add', 0, '/#/colaboradores/novocolaborador')">Novo Colaborador</button>

Esse é meu controller.

app.controller('colaboradoresController', function($scope, $http, API_URL) {

    $http.get(API_URL + "colaboradores")
            .success(function(response) {
                $scope.tbcolaborador = response;
            });

    $scope.toggle = function(modalstate, id, $location) {
        $scope.modalstate = modalstate;

        $location.path('/#/colaboradores/novocolaborador');
}

A troca de view deveria ser feita levando uma informação (0 caso for adicionar um novo) e o id caso seja um colaborador já existente. Desde ja agradeço pela ajuda.
Answer: Como o controller é descartado na mudança de rota, uma forma é preparar seu config router para receber o parâmetro id na própria url.
.when('/colaboradores/novocolaborador/:id', {
              templateUrl: 'views/colaboradores/novocolaborador.html',
              controller: 'colaboradoresController'
            })

Assim, você poderá passar opcionalmente o id pela url (concatenando com a variável, por exemplo):
$scope.toggle = function(modalstate, id, $location) {
    $scope.modalstate = modalstate;

    $location.path('/colaboradores/novocolaborador/' + id);

...e recuperar o mesmo quando na outra view, através do $routeParams. Não esqueça de injetar esse serviço no seu controller.
var id = $routeParams.id;

Comment: Beleza, entendi essa explicação. Porém não estou conseguindo fazer a troca de view, o "$location.path" parece não estar funcionando...
Comment: Hmm, acredito que aquela hashtag não seja necessária. Tenta usar apenas '/colaboradores/novocolaborador/', se funcionar eu edito a resposta.
Comment: funcionou, valeu pela ajuda
Comment: Gostaria de saber como recuperar o id quando ja estiver na outra view. Você disse através do $routeParams, porem se eu ja estiver na outra view, com um novo controller, o que devo fazer para recuperar esse id? Criar uma função que recupera o id? onde devo chamar essa função, no início da view?
Comment: Consegui recuperar esse id por meio de um botão na nova view(fiz apenas para teste), porem gostaria de fazer isso automaticamente, quando ele entrar na view ele ja recuperar o id pelo routeparams...
Comment: Uma forma é você criar uma função e já chamar ela no início do seu controller, assim ela será executada na abertura da tela. Você verifica se $routeParams.id existe e, se existir, atribui o valor para a variável que deseja (se for usar na view, ela deve estar no $scope).
Comment: Cara fiz o seguinte funcao no meu controller: http://freetexthost.com/p3rx05ptjb Chamei ela no inicio da minha view {{recuperarId()}} porem ela está sendo executada infinitamente, acredito que seja por que a view é atualizada toda hora. Eu queria saber se existe algum "metodo construtor" da view, para que eu possa recuperar o id somente uma vez.
Comment: Não há necessidade de chamar a função pela view. Está sendo executada muitas vezes porque, da forma como você fez, ela é executada a cada ciclo do Angular. Uma forma simples é chamar ela no início do seu controller mesmo: http://freetexthost.com/6on6bb5zc1


UltiDev IP address binding

Question: I am trying to create a web service for my android application. The web service is supposed to run on UltiDev, the issue i get is when i try to access the web service through a local android emulator. I was advised to change the url of the web service to http://10.0.2.2:portnumber/serviceName but when i attempt to make this change i get an error in UltiDev. It turns out that i have to bind the port first before i can do this, however UltiDev does not allow me to do this. This is the error i get. Sorry i can't post the actual image because i need reputation points first.
Failed to register application because System.ApplicationException: Unable to register application because not all required applications settings are specified: Listen endpoints are either not specified or are already taken by other applications.
at UWS.Configuration.WebAppConfigEntry.ApplyFinalDefaultsAndValidateBeforeSaving()
.....
Answer: Could you please clarify whether you are trying to do this programmatically, or using UWS Explorer UI? Please attach a screenshot - it always helps.
In case you use UWS Explorer, the screenshot below shows how to add a port binding. If you click "Specify host name or IP address" radiobutton, you will be able to specify an IP address.
If you do all that, but then you still get the same error, it means your system acts as if all IP+ports are already taken, which often is caused by security software, like firewall+antiviruses.

UltiDev IP address binding


do predicates in Ubercart really work?

Question: I´m trying to update a shipment cost for different zones of a country
(using predicates, conditional actions)
Using the trigger Getting shipping quote via Flat Rate
class uc_flatrate, activated , I´m trying to modify the rate..
Still the trigger doesn´t get called,
I tried to modify the objects with php , didn´t work ,
then i tried a simple test to display a message to the user, didn´t work..
then I tried to write a simple text into a file to see if the event gets called... didn´t work
How can I run a php script when I press calculate shipment cost? (or whenever the shipment cost is calculated) ?
Comment: what I could do is define multiple rates / kg on weight quotes and edit it's default created predicate and put an condition of the location with no action, so it applies the quote..
Still that doesn't help much as I have multiple prices for ranges of weight 0-10 , once price, 11 to 30 another etc..

I just want to be able to control this with PHP :(
Answer: To directly answer your question, yes, Predicates work. I use them extensively at a D6 Ubercart site of mine. Aside from that, my store is all digital goods, so no shipping.
Answer: If you have:
CountryA

Zone1
Zone2
Zone3

CountryB

Zone1
Zone2
Zone3

Where Zone 1 and 2 of Country A and Zone 3 of Country B cost the same, then create one shipping method which has the same flat rate, give it 3 conditions under "Order: Shipping Address" - "Check an order's shipping State/Province" and state Zone1, Zone2, Zone3. Make sure you select OR as the operator at the top.
If the other zones are also the same costs, do the same. To have a shipping condition for "the rest of the destinations", you may do either of two methods whichever is fewer: 1.) Select all the state/provinces that already have shipping quotes and negate them, meaning "NOT" these destinations. Or, just keep going with the select destination "TRUE" method.
If you want to complicate things further with different countries and provinces, you can sort out the conditions and "override" the rules using weights for importance of the rule. Lowest weighted condition will triumph. Have a think about the best method to sort your shipping rules.

do predicates in Ubercart really work?