java byte array output stream gives nothing

Question: I have the following code and I can't figure out why it won't work:
final ByteArrayOutputStream bos = new ByteArrayOutputStream();
final String p1 = "HELLO WORLD";
process(p1, bos);
Assert.assertEquals("BOS value should be: "+p1, p1, bos.toString("UTF-8"));

It prints:

junit.framework.ComparisonFailure: BOS value should be: HELLO WORLD expected:<[HELLO WORLD]> but was:<[]>
    at junit.framework.Assert.assertEquals(Assert.java:81) etc...

and process looks like this:
public static void process(final String p1, final OutputStream os) {
    final Runtime rt = Runtime.getRuntime();
    try {
        final String command = "echo " + p1;
        log.info("Executing Command: " + command);
        final Process proc = rt.exec(command);

        // gobble error and output
        StreamGobbler.go(proc.getErrorStream(), null);
        StreamGobbler.go(proc.getInputStream(), os);

        // wait for the exit
        try {
            final int exitVal = proc.waitFor();
            log.info("Command Exit Code: " + exitVal);
        } catch (InterruptedException e) {
            log.error("Interrupted while waiting for command to execute", e);
        }
    } catch (IOException e) {
        log.error("IO Exception while executing command", e);
    }
}

private static class StreamGobbler extends Thread {
    private final InputStream is;
    private final OutputStream os;

    private static StreamGobbler go(InputStream is, OutputStream os) {
        final StreamGobbler gob = new StreamGobbler(is, os);
        gob.start();
        return gob;
    }

    private StreamGobbler(InputStream is, OutputStream os) {
        this.is = is;
        this.os = os;
    }

    public void run() {
        try {
            final PrintWriter pw = ((os == null) ? null : new PrintWriter(os));
            final InputStreamReader isr = new InputStreamReader(is);
            final BufferedReader br = new BufferedReader(isr);
            String line = null;
            while ((line = br.readLine()) != null) {
                if (pw != null) {
                    pw.println(line);
                }
                log.info(line); // Prints HELLO WORLD to log
            }
            if (pw != null) {
                pw.flush();
            }
        } catch (IOException ioe) {
            log.error("IO error while globbing", ioe);
        }
    }

When I run the jUnit test I get an empty string as the actual. I don't understand why this wont work.
EDIT: I am using RHEL5 and eclipse 3.6 if that makes a difference at all.
Comment: Mention your operating system; answers may depend on whether echo is an application or a shell function.
Comment: RHEL5. I put a log.info(line) inside the loop in StreamGlobber and it prints HELLO WORLD. But my ByteArrayOutputStream doesn't have that.
Comment: Your "Command Exit Code" and "Executing Command" aren't displayed in your output--did you trim that out?
Comment: Yeah. They're both correct. Executing Command: echo HELLO WORLD, and Command Exit Code: 0
Answer: maybe you should wait on the thread filling the stream:
    Thread thr = StreamGobbler.go(proc.getInputStream(), os);

    // wait for the exit
    try {
        final int exitVal = proc.waitFor();
        log.info("Command Exit Code: " + exitVal);
        thr.join();//waits for the gobbler that processes the stdout of the process
    } catch (InterruptedException e) {
        log.error("Interrupted while waiting for command to execute", e);
    }

Comment: cause the main thread might finish the method (and go through the assertEquals) before the gobbler thread has a chance to run and collect any data


Embed activity feed of a public Facebook page without forcing user to login/allow

Question: This is similar to questions asked several times before, but no matter what I read, I'm still confused.
I have a public Facebook page, like White Collar for example, whose activity feed I need to embed into my Android app. I understand how to get the app-id and app-secret, but I don't understand how to get the short-lived access token, which I understand is necessary to get a long-lived access token.
From what I understand, which can quite possibly be wrong, the user has to login through the app to get a short-lived access token, but I don't want any user to have to login to view the activity feed.
Once I have that, how do I then use it to bring this activity feed into my app?
The Facebook documentation for this is terrible so I need some help.
If it or anything else requires site-specific permissions, I have access to the site in question.
Thanks!
Answer: To get the activity feed of a public Facebook page, like White Collar, follow these steps:
1) Get your App-id and App-secret by choosing an existing app or creating a new one at this url:
https://developers.facebook.com/apps/

2) Get an access token by making a GET request to this url:
https://graph.facebook.com/oauth/access_token?client_id=" + APP_ID + "&client_secret=" + APP_SECRET + "&grant_type=client_credentials

3) Get the page-id of your fan page. To do this, you need the page-name. Go to your fan page on facebook and look at the url. It will have this form:
https://www.facebook.com/{fan-page-name}

Once you have that, make a GET request to this url:
https://graph.facebook.com/{fan-page-name}?access_token={access-token}

It will return a bunch of JSON. You're looking for the first "id" element. This is your page-id.
4) Get the fan page JSON data with a GET request to this url:
https://graph.facebook.com/" + page-id + "/feed?access_token=" + URLEncoder.encodeUTF8(access-token)

To avoid having exceptions thrown, I had to use URLEncoder.encodeUTF8().
The data you're looking for is under the "data" element.
I wasn't able to find anything that would do the JSON parsing of the Facebook feed for me, but I did find this tutorial that will do a lot of the formatting for you to make it look like Facebook.
Hope that helps anyone else trying to do this.
Comment: It seems like facebook requires app approval before they will give you 'Page Public Content Access.' I now get this error after using a valid access token for a brand new, unapproved app: ""(#10) To use 'Page Public Content Access', your use of this endpoint must be reviewed and approved by Facebook. To submit this 'Page Public Content Access' feature for review please read our documentation on reviewable features: https://developers.facebook.com/docs/apps/review."
Comment: +1 for the link to the Android Hive article!  I was able to easily adapt that to fit my needs in my Android app.
Comment: For step3, it is already not supported now. And it will give out error:
{"error":{"message":"An access token is required to request this resource.","type":"OAuthException","code":104,"fbtrace_id":"FEz1d5Z\/Gnz"}}
Comment: I'm sorry to hear that! It is still supported for apps using the older api. I wish I had time to debug and figure out a new solution for you. On part 2 of Step 3, you might try using `URLEncoder.encodeUTF8()` to make sure it's getting outputted in the right format.
Comment: Step 2 seems to be broken as well, now :(


Deduced conflicting types for universal reference and pointer to member

Question: I want a function like this:
template<typename C, typename T>
void foo(C &&aclass, T (C::*const memberFunc)(unsigned)) {

}

The parameters are (in words because C/C++ type syntax is mental):

A universal reference to a class, e.g. MyClass.
A const pointer to a member function of MyClass that takes an unsigned int and returns T.

This sort of works, however if I call it with an l-value reference as the first parameter I get an error like:

candidate template ignored: deduced conflicting types for parameter 'C' ('MyClass &' vs. 'MyClass')

As far as I understand it, it is deducing C from the first and second parameters, but comes up with different deductions and gets confused.
According to this answer you can make it only do deduction on the first parameter, and somehow use the typename keyword on the second parameter. But I can't work out the syntax to do this when I do want it to deduce one of the types in the parameter (T), but not the other (C).
This answer is also helpful but they solve it by just not using references for C at all, which in that case is equally efficient, but not in mine.
Is this possible?
Comment: I daresay that holding C accountable for a syntax it doesn't have is unfair
Comment: I meant the syntax used to specify types in C is bonkers. The result is often worse in C++ because its types are more complex, but [the complicated syntax comes from C](http://www.unixwiz.net/techtips/reading-cdecl.html).
Answer: With lvalues C will be deduced to be an lvalue-reference type (i.e. MyClass & for your case) for the 1st parameter, which is the expected behavior of forwarding reference; you can remove the reference-ness via std::remove_reference when using C in the 2nd parameter, e.g.
template<typename C, typename T>
void foo(C &&aclass, T (std::remove_reference_t<C>::*const memberFunc)(unsigned)) {

}

And as @Quentin pointed, using of std::remove_reference also introduces non-deduced context, that would prevent C from being deduced from the 2nd parameter.
Comment: It's worth noting that `std::remove_reference` will *also* introduce a non-deduced context, which is helpful.
Comment: @Timmmm Yes. This feature was introduced from C++14; in C++11 you can write `typename std::remove_reference::type` instead.
Comment: Did you mean to have `_t` on the end of `remove_reference`?
Answer: Actually I just found that having a universal reference overload forward it to an l-value reference version works. Not particularly elegant though; I feel like there should be a better way.
template<typename C, typename T>
void foo(C &aclass, T (C::*const memberFunc)(unsigned)) {
  // Code goes here.
}

template<typename C, typename T>
void foo(C &&aclass, T (C::*const memberFunc)(unsigned)) {
  foo(aclass, memberFunc);
}


Minimum ladder over wall optimization

Question: A fence 6 feet tall runs parallel to a tall building at a distance of 2 feet from the building. We want to find the the length of the shortest ladder that will reach from the ground over the fence to the wall of the building.
Here are some hints for finding a solution:
Use the angle that the ladder makes with the ground to define the position of the ladder and draw a picture of the ladder leaning against the wall of the building and just touching the top of the fence.
If the ladder makes an angle 0.46 radians with the ground, touches the top of the fence and just reaches the wall, calculate the distance along the ladder from the ground to the top of the fence.
a.The distance along the ladder from the top of the fence to the wall is
b. Using these hints write a function L(x)  which gives the total length of a ladder which touches the ground at an angle , touches the top of the fence and just reaches the wall.
 L(x) = .
c. Use this function to find the length of the shortest ladder which will clear the fence.The length of the shortest ladder is
I know that the length of the ladder that touches the fence is 6/ sin(0.46). The function would probably be a positive quadratic that would involve the length of the ladder as a variable. The ladder cannot be less than 0 feet (one portion is already about 13 ft. long).
How do I figure out the distance from the fence to the wall?
How do I then figure out the function to get the length of the ladder?
Comment: Anything wrong with this question? The way I asked it? The content? Or will there always be boo-birds who vote questions down no matter what?
Answer: Hint: (not using the angle) Put the fence top at $(2,6)$ so the wall is the $y$ axis, and the base of the ladder is on the $x$ axis somewhere to the right of $2$. The line connecting $(x,0)$ to the point $(0,y)$ where the top of the ladder just hits the wall must go through $(2,6)$. You can minimize for simplicity the squared length $x^2+y^2$ of the ladder, and use similar triangles to get a relation $(x-2)/6=x/y$ between $x,y$. From here you can get a one variable function to minimize, and then don't forget to take squareroot for the actual ladder length.
Answer: We need a labelled picture.  The wall of the building is on the left. The bottom of the fence is at $B$, the top of the fence is at $T$, the foot of the ladder is at $F$, and the ladder hits the building at $L$. It is clear that to make the ladder short, it should touch the fence at $T$, even though this risks damaging the fence.
I will use the trigonometric approach, because it is the suggested one. But I would not necessarily start that way otherwise.
Let $x$ be the angle $BFT$ that the ladder makes with the ground. Then $\frac{6}{FT}=\sin x$, so $FT=\frac{6}{\sin x}$.
The rest of the ladder has length $TL$. Note that $\frac{2}{TL}\cos x$, so $TL=\frac{2}{\cos x}$.
Thus the total length $f(x)$ of the ladder is given by
$$f(x)=\frac{6}{\sin x}+\frac{2}{\cos x}.$$
Calculate $f'(x)$. For the critical point, you should end up with an equation of the shape $\tan^3 x=a$.

Minimum ladder over wall optimization


In Lambda calculus, are there two terms said A, B which are typeable but when they combine, they become not typeable?

Question: I have also provided my own examples and I am wondering if  they are correct.
Example 1: $A = x$ and $B = x$, they are both typeable but $A B = x x$ which are not typeable(?)
Example 2: $A = \lambda x.x$ and $B = x$ so they are both typeable but $A B = \lambda x.x x$ which are not typeable (?)
Can you answer me whether are my answers correct and are there any other examples out there that fulfill the constraints above?
Comment: Write in $\LaTeX$ on your posts.
Answer: Yes, this is possible.
Your example 1 is correct, and all the standard examples of untypeable terms eventually boil down to this kind of self-application.
Your example 2 is incorrect. $A = \lambda x.x$ will have a function type $\sigma \to \sigma$, and combined with a suitable term $B = x$ of type $\sigma$ yields the application term $(\lambda x.x)x$ with type $\sigma$. Because note that $AB = (\lambda x.x)(x)$, not $\lambda x. (xx)$.
The general pattern is that type assignment fails when running into loops, when a type wants to be assigned in terms of itself. In the example of , the whole term will have some type $\rho$; and since it is an application term, the functor $x$ must have a function type with input  and output $\rho$; that is, : $\sigma = \tau \to \rho$. But the input to this function is  again, so the type of the input must be the same as the type of the functor itself: We have =, and hence : $\sigma = \sigma \to \rho$. The fact that  occurs on the right-hand side of the equation is precisely the problem. Attempting to assign a simple type to $x$ in this occurrence context will trigger an infinite loop, so $xx$ is not typeable, and neither is any term that contains, or beta-reduces to a term that contains, $xx$ as a subterm. All untypeable terms will have this pattern, where in the type equation =...,  occurs again on the right-hand side.
You may want to look into the type assignment algorithm, which has rules to perform certain manipulations on these kinds of type equations. The algorithm will either terminate with a suitable type, if the term is typeable, or with $\mathrm{fail}$, if the term is not typeable, which happens precisely when this sort of loop-structure type assignment is encountered. For the details see e.g. H. Barendregt (1992), Lambda calculi with types, ch. 4.4.
Comment: I don't know about a general formula. You certainly don't need free variables to create typeable $A$ and $B$ such that $A\,B$ is untypable.. E.g. if $A = \lambda g.\lambda x.g x x$ and $B = \lambda x . x$, then $A$ and $B$ are typable but $A\,B$ is not.
Comment: is there a general formula so that I can get two terms A and B which are typeable but when apply they are not? I noticed that my example 1 are two free variables, are there examples in which A and B only involve bound variables? I always like to revise with textbook but the textbook does not give any concrete examples andI am not used to it.
Comment: The general rule is that type assignment fails when running into loops, when a type wants to be assigned in terms of itself. In the example of $xx$, if we try to assign a type $\sigma$ to $x$, it must be a function type with input $\tau$ and output $\rho$; that is, $xx: \sigma = \tau \to \rho$. But the input will be $x$ again, so the type of the input must be the same as the type of the functor itself: We have $\tau = \sigma$, and hence $xx: \sigma = \sigma \to \rho$. The fact that $\sigma$ occurs on the right-hand side of the equation is precisely the problem.
Comment: All untypeable terms will have this form where in the type equation $\sigma = ...$, $\sigma$ occurs again on the right-hand side. You may want to look into the type assignment algorithm, which makes use of these equations and has a rule `fail` that fires precisely these loops, indicating that a term is not typeabble.
Comment: Rob Arthan's example will also fall into the category of such loop-structured type assignments, after resolving the application term $AB$ into appropriate type equations.
Comment: Sorry, in my first comment, replace "$xx$"  by just "$x$". The type of $xx$ would be $\rho$, the output type of the functor, but the fact that the type of $x$ can not be resolved makes the whole thing untypeable.
Comment: @DanielV No. Typeability in the simply-typed lambda calculus is decidable. The mentioned algorithm exists. See e.g. H. Barendregt's (1992) *Lambda calculi with types*, ch. 4.4.
Comment: @lemontree Oh thanks.  They must be a small enough subset of convergent turing machines that the general restriction doesn't apply.
Comment: @DanielV If I am not mistaken (but no warranty on the second part), the situation is: All typeable functions halt, because the typeable terms are strongly normalizing, but not all halting functions are typeable, namely those that are only weakly normalizable, and the functions that don't halt are those that are not normalizable.
Comment: @lemontree Maybe I'm misunderstanding you, isn't $x~x$ strongly normalizing (actually not even containing a redex) but not typeable ?
Comment: @DanielV Yes, but there is no contradiction: All typeable terms are strongly normalizable, but not all strongly normalizable terms necessarily are typeable.


Need help understanding Proposition 2.3.7 from Howie's Semigroups.

Question:
I don't understand the author's argument in the second line of the proof. In particular, I don't see exactly how such a bijection does exist.
I see that $ab \in L_b$ implies $H_b = H_{ab}$, and the bijection goes from $H_b$, but don't see how it goes onto $L_a \cap R_b$.
Comment: $H_b$ has no reason to be equal to $H_{ab}$, contrary to your claim.
Comment: I understand why it is false to claim so now. Thank you for your help.
Answer: By Green's Lemma, $\rho_c$ induces an $\mathcal R$-class preserving bijection from $L_b$ to $L_{bc}$. In particular $bc \in R_b$. Moreover since $L_{ab} = L_b$ and $\rho_c(ab) = abc = a\,$, one gets $L_{bc} = \rho_c(L_b) = \rho_c(L_{ab}) = L_{abc} = L_a\,$. Thus $bc \in L_a$ and finally $bc \in L_a \cap R_b$.


Schur-Weyl Duality (Example for k = 3)

Question: I am an undergraduate student interested in representation theory.
I know that you can decompose the iterated tensor product $(C^n)^{\otimes k}$ into the direct sum of irreducible $S_k \times GL(V)$ representations $S^\lambda \otimes U^\lambda$, where the length of $\lambda$ is smaller equal n.
For the partitions $(k)$ and $(1^k)$ these are just the symmetric / skewsymmetric tensors.
However, I am interested in the third part (example for k = 3)  $S^{(21)} \otimes U^{(21)}$. I tried to compute both of them seperatly, but I'm stuck somewhere:
I think $U^{(21)}$ is the kernel of the canonical map $Alt^2(V) \otimes V \rightarrow Alt^3(V)$. How does $S^{(21)} \otimes U^{(21)}$ look like though?
And how does this decompositions helps us in any way? I assume the general goal is to compute the multiplicities of irreducible representations?
Thank you in advance for advice!
Answer: Let $\tau:V^{\otimes 3}\to V^{\otimes 3}$ be defined by $\tau(u\otimes
v\otimes w)=v\otimes w\otimes u$. Then the $S^{(21)}$ part of
$V^{\otimes 3}$ is the kernel of $\textrm{id}+\tau+\tau^2$.
Comment: Thanks for your quick answer! If I understand you correctly, those are tensors of the form $\sum_{\sigma \in A_k} v_{\sigma(1)}...v_{\sigma(3)}$. How does that fit/interact with $U^{(21)}$ though? Shouldn't I get just one subspace, let's say $H^{(21)}$?
Comment: No, they aren't. What you write down is the direct sum of the symmetric and antisymmetric tensors: the kernel of $1+\tau+\tau^2$ is a complement to that. @Amjad
Comment: Okay, got it. And how does $S^{(21)} \otimes U^{(21)}$ look like? Isn't $S^{(21)}$ already the whole part of the decomposition? And if it doesn't give me any new information, what is the purpose of computing $U^{(21)}? Sorry that I've got so many questions.

Schur-Weyl Duality (Example for k = 3)


How do I improve my singing?

Question: I enjoy singing, and I want to improve. I've had an ear for music since I was very young, and I have no problems finding/matching/hearing a tune in my head. However as I've gotten older, I've found it increasingly difficult to sing a note that I can hear in my head. I guess my voice has just changed over time, making it harder to reach notes that I once could. I feel very limited and constrained vocally. What exercises/techniques can I practice to broaden my vocal capabilities and reach my potential?
Answer: The best advice I can think to offer is for you to find a vocal instructor in your area and begin studying with them.  Based off the information in your question, it seems as though you are trying to sing material inappropriate for your voice type.  Working with a trained vocalist will not only give you the pedagogical tools you need to develop and refine your vocal production, but will provide information about what type of voice you have and what sort of material you should be performing.
Myself or someone else providing suggestions exercises would only serve as a quick-fix and would be doing you a disservice.
Potentiality increases over time as your technique and knowledge improve.  In order to succeed at the best possible level, I'd suggest long-term work by studying with a voice instructor (not a "vocal coach" unless their credentials offer appropriate merit.)
I realize that this answer is probably not the one you were looking for, but I think it is one that needs to be offered.
Hope that helps.
Answer: I agree with jjmusicnotes. He has very good points to offer.
If you are willing to spend some money on practicing your craft I recommend Brett Manning's Singing Success click here for the website. His work is truly amazing and he has help me increase my range by a full octave. It has also helped my style tremendously.
If you can not afford his program then I recommend doing lip rolls (look up videos on how to do lip rolls) on a comfortable scale. Do that daily and then start to increase the pitch of the scale slowly moving upward (you can do it down in pitch too). Along with the lip rolls make sure you sing daily. Practice singing your favorite songs, but never over do it! You can harm or hurt your voice if you strain it or sing too much and too long.
With that said have fun and keep singing!

How do I improve my singing?


Meraki VPN behind NAT breaks Bitbucket Git on WSL2 (Ubuntu 20) on Windows 10

Question: I access two Meraki VPNs from my Windows 10 Pro (10.0.19042 Build 19042) machine:

One which is not behind a NAT - when I switch this on, I can do git clone [...] or git fetch [...] just fine.
Second, which is behind
a NAT - when I switch that on and run git fetch, I am geting error message: "fatal:
unable to access 'https://bitbucket.org/[project]/[project-name].git/':
gnutls_handshake() failed: Error in the pull function."

To make the second VPN work, I've executed following commands in the PowerShell:

Set-ItemProperty -Path "HKLM:SYSTEM\CurrentControlSet\Services\PolicyAgent" -Name "AssumeUDPEncapsulationContextOnSendRule" -Type DWORD -Value 2 –Force;
reg add "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Rasman\Parameters" /v AllowL2TPWeakCrypto /t REG_DWORD /d 1 /f
reg add "HKEY_LOCAL_MACHINE\System\CurrentControlSet\Services\Rasman\Parameters" /v ProhibitIpSec /t REG_DWORD /d 0 /f

It was also necessary to disable IPv6.
That made the VPN work for Windows, but not for Linux inside WSL2. Any suggestions? Thank you very much!
Answer: The problem was in a mismatch between VPN MTU and Linux under WSL2 MTU sizes.
It can be identified via 2 commands:
Windows PowerShell (run as administrator)
netsh interface ipv4 show subinterfaces
Notice the first row - it shows how big MTU is allowed in your VPN.
Linux (inside WSL2) console
ip addr
Notice the row starting 'eth0' - its MTU must match or be lower that the one above.
In my case the MTU in Linux was higher.
Solution
The following command instantly solves the problem:
sudo ip link set dev eth0 mtu 1400 (update MTU value to fit your VPN)
I have put it inside my ~/.bashrc and put /usr/sbin/ip into sudoers NOPASSWD for my account.
Better solution
So far I haven't managed to use any of the standard Linux tools to change MTU on Linux startup inside WSL2 (and hence to avoid putting it into .bashrc).

rc-local doesn't work under WSL2
/etc/dhcp/dhcpclient.conf doesn't
propagate changes into default interface-mtu nor supersede interface-mtu
netsh interface ipv4 set subinterface "vEthernet (WSL)" mtu=1400 store=persistent doesn't affect Linux
/etc/netplan
doesn't run inside WSL2

If you find the way, I'd be more than happy to have it here!
Comment: I found this helpful implementing this solution https://askubuntu.com/questions/216804/want-to-execute-sudo-command-on-shell-startup
Comment: I'm not an expert, but I think you need to allow an extra 28 bits to be eaten on top of the VPN MTU, so make the MTU 28 lower than the VPN's MTU.
Answer: My solution here was:
sudo ip link set dev eth0 mtu 1350

NOT:
sudo ip link set dev eth0 mtu 1400

Test it by lowering the MTU value to adapt to your network settings.


How to access personal contact form in search

Question: Using Drupal 7. All of the people on my site have personal contact forms. When I type their name into the search bar, I get 'no results'.
I need people to be able to find users' personal contact form links by using the search function.
I'm using the core Search module and have enabled 'users' to be included in the search, but no results come up, regardless of which name I use. Site has been re-indexed, caches flushed, etc.
All users have a status of 'authenticated' and permissions have been set on 'contact' and 'search' to allow the results to show.
Any help is appreciated. Thanks.
Answer: Okay. I was under a deadline so I came up with an annoying but functioning solution.

1) I added the Search by page module (https://www.drupal.org/project/search_by_page) and enabled it.
2) I made a new search environment by going to admin/config/search/search_by_page.
3) In the new search environment, I enabled all the content types I wanted the module to pull.
4) How I got it to pull users' contact pages was:
5) Go to the enironment I made and clicked 'edit'
6) On the top right of the page are two tabs: 'General settings' and 'paths'
7) I clicked on 'paths'and then clicked 'add new path'
8) I opened a new browser window and navigated to the 'People' tab. I clicked on a user and selected their 'Contact' tab, and copied the path (in my case, user/number/contact
9) I went back to the 'add new path' tab and pasted that info in the 'page to index' section
10) I entered a page title (Contact Mr. Smith) and saved. Clicked on 'add new path' for next user.
11) Repeated steps 7-11 for all 50 users.
12) Re-indexed site by running cron. Voila, contact pages come up in search results.

This was a cumbersome, time-consuming way of doing this, and I'm sure there's a better solution. However, if you're pressed for time like I was, I hope this helps someone.


Obj-C parse seconds to dd:hh:mm:ss

Question: I'm calculating difference between two dates. I've create my own solution:
NSDate *actualDate = [NSDate date];
NSTimeInterval sec = [eveDate timeIntervalSinceDate:actualDate];
int secondsBetween = sec;
int minBetween     = sec / 60;
int hoursBetween   = sec / 3600;
int daysBetween    = sec / 86400;

_lblDays.text  = [NSString stringWithFormat:@"%d", daysBetween];
_lblHours.text = [NSString stringWithFormat:@"%d", hoursBetween % 24];
_lblMin.text   = [NSString stringWithFormat:@"%d", minBetween % hoursBetween];
_lblSec.text   = [NSString stringWithFormat:@"%d", secondsBetween % minBetween];

But I believe that there is a better solution for this (like native class for example) but I couldn't find anything. Could you tell me how to do it better?
Comment: [NSDateComponentsFormatter](https://developer.apple.com/library/prerelease/ios/documentation/Foundation/Reference/NSDateComponentsFormatter_class/index.html)
Answer: This is an another way to calculate.
NSDateComponents *components = [[NSCalendar currentCalendar] components: NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond
                                                 fromDate: startDate toDate: endDate options: 0];
NSInteger days = [components day];
NSInteger hour=[components hour];
NSInteger minutes=[components minute];
NSInteger sec = [components second];

Comment: Especially this is the correct way to do it, because it respects time switches.
Answer: You can use NSCalendar and NSDateComponents class for doing this:
NSCalendar *calendar         = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSCalendarUnitDay|NSCalendarUnitHour|NSCalendarUnitMinute|NSCalendarUnitSecond fromDate:actualDate toDate:eveDate options:0];
NSLog(@"Days->%d Hour->%d, Minute->%d, Second->%d", components.day, components.hour, components.minute, components.second);

Obj-C parse seconds to dd:hh:mm:ss


In what order will the matrix C be returned if you call it like C(:)

Question: I have called C(:) for the following matrix:
[0 0 1]
[1 1 0]
[0 1 0]

and the output I get is: [0 1 0 0 1 1 1 0 0], i.e. it returns the matrix from the very last entry moving right to left to the very first entry.
Other times it returns the array that includes entries from top left, moving left to right to the very last entry. And sometimes it just returns something unknown.
I have tried using C(:) on
[0 1 1]
[1 0 1]
[0 0 0]

and I get: [0 1 0 1 0 0 1 1 0]. How can I get it to consistently return the entries starting from the top left entry moving left to right, to the very last one?
Answer: There are no inconsistencies about C(:) at all.  It behaves the same regardless of what matrix you use when you call it this way.  C(:) unwraps the matrix so that it's stacked in column-major format.  This means that all of the columns of the matrix are stacked on top of each other to produce a single column:
>> C = [1 2 3; 4 5 6; 7 8 9]

C =

     1     2     3
     4     5     6
     7     8     9

>> C(:)

ans =

     1
     4
     7
     2
     5
     8
     3
     6
     9

If you want to unwrap row-wise, you must transpose the matrix first.  This way, all rows become columns and vice-versa, and so when you stack the columns in column-major order, the rows are now the columns, thus completing what you want:
>> C = [1 2 3; 4 5 6; 7 8 9]

C =

     1     2     3
     4     5     6
     7     8     9

>> C = C.'

C =

     1     4     7
     2     5     8
     3     6     9

>> C(:)

ans =

     1
     2
     3
     4
     5
     6
     7
     8
     9

Answer: Is this MATLAB/Octave? If so, as far as I know, it's relative to the dimension number. For example, in a 2D matrix, the first dimension are the lines, second dimension are the columns.
So, using the (:) operator will do the following:
octave:1> x = magic(3)
x =

   8   1   6
   3   5   7
   4   9   2

octave:2> x(:)
ans =

   8
   3
   4
   1
   5
   9
   6
   7
   2

If you want it the other way around, just transpose the matrix beforehand:
octave:3> x'(:)
ans =

   8
   1
   6
   3
   5
   7
   4
   9
   2

Comment: The tag is MATLAB, and doing `x'(:)` is unfortunately undefined in MATLAB.... though in an ideal world, that would be nice.
Comment: Yes, you have to transpose first and place into a variable, then unroll it... hence that's what my answer says.  MATLAB unfortunately requires that you create intermediate variables before you can slice into them or do operations on them.  As such, doing something like `A(1:4)(1:2)` isn't defined in MATLAB, but Octave has it defined.... and it'd be nice if MATLAB had the same functionality too.
Comment: Actually I did [x'](:)
Comment: Still undefined in MATLAB :)
Comment: @rayryeng how about `colon(x')`?


Multiple linear regression degrees of freedom

Question:
The degrees of freedom in a multiple regression equals $N-k-1$, where $k$ is the number of variables.

Does $k$ include the response variable (i.e., $Y$)? For example, in the model $Y = B_0 + B_1X_1 + B_2X_2$, then does $k = 3$ (i.e., 1 df each for $Y$, $X_1$, & $X_2$)?
Comment: I don't know where you found this quote, but it sure is poorly phrased.
Answer: It's the number of predictor (x) variables; the additional -1 in the formula is for the intercept - it's an additional predictor. The Y doesn't count. So in your example $k=2$ and the error df is $N-3$
Comment: Another (ultimately equivalent) way to think about this is that you use 1 df for each parameter estimate (ie, $\hat\beta$), plus 1 df for the mean of the response (ie, $\bar y$), since the intercept is determined once you have $({\bf\bar x}, \bar y)$ and the slopes.


Redirecionar para outra aplicação CodeIgniter

Question: Tenho um CodeIgnter com 3 aplicacoes, dentro de cada uma o welcome view padrao, a estrutura esta parecida com isso:

www
applications

site
site2
site3

system

Preciso descobrir como redirecionar para o site2 por exemplo a partir do site 1.
Comment: Cada uma tem o seu próprio endereço?
Comment: vai ser tipo sub.site.com ( site 1 )
sub.site.com/site2
sub.site.com/site3
Comment: Vai dar choque na rota não vai?
Comment: A estrutura de pastas pensei esta, mas aceito outras sugestoes, preciso de 3 aplications no mesmo codeignter
Answer: Adriano,
Uma sugestão é usar a função header, apontando para a URL do aplicação a ser redirecionada:
header('Location: http://www.example.com/');
header('Location: https://pt.stackoverflow.com');

É uma solução simples, nativa do PHP, que permite fazer redirecionamentos. Para mais informações, a documentação do PHP explica mais alguns detalhes.
Answer: Controller Site 1 para chamar site 2
 public function redirecionar() {
        redirect('nomecontrollersite2/indexsite2');
     }

Controller Site 2
  public function indexsite2() {
          $this->load->view('indexsite2',);
}

Comment: nao funcionou, sao aplicacoes diferentes


Organizar Classes EDMX

Question: Tenho um projeto DB First que utiliza um EDMX para mapear a base de dados. As tabelas possuem colunas padrão que existem em todas elas e que eu poderia organizar e deixar o código bem mais genérico se fosse possível implementar interfaces na mesma com estas propriedades, mas não é uma boa prática alterar as classes geradas automaticamente pelo EDMX.
Há alguma boa prática ou padrão para melhorar a organização e reaproveitamento de código no modelo DB First?
Atualização
Vendo que, aparentemente, não existe uma solução direta para este problema, existe, talvez, alguma forma então de fazer com que um código iniciado com CodeFirst mude automaticamente com alguma alteração realizada no banco? (importar as modificações)?
Comment: *"...mas não é uma boa prática alterar as classes geradas automaticamente pelo EDMX"*. Depende. Se o banco é modificado com frequência, não é mesmo. Caso contrário, não há problema. Gostaria de uma resposta considerando o segundo caso?
Comment: *"[...] mas não é uma boa prática alterar as classes geradas automaticamente pelo EDMX."*. Não é que não seja uma **boa prática**, né. Isso não é uma **boa ideia**, porque, como já foi dito, sempre que mudar o banco essas classes vão ser geradas novamente.
Comment: Bem interessante sua pergunta, realmente não conheço uma solução "elegante" e matadora para este caso. Mas pesquisando me deparei com algo semelhante ao se tentar implementar MetaDataTypes em classes geradas pelo DB first. Como essas classes são geradas como partial, será que você não poderia criar novas classes parciais também e implementar sua ideia?  No link a seguir tem um exemplo de algo parecido,veja se te ajudar a achar uma direção: Link -> http://stackoverflow.com/questions/9071120/defining-data-annotation-using-dbcontext-versus-objectcontext-in-the-database-fi/9073286#9073286
Comment: Sim, gostaria sim. O banco até não é alterado com frequência, mas toda a vez que fosse alterado ele iria importar novamente as classes e desfazer o que foi feito. Tem como evitar isso?
Comment: Então, mas a minha resposta vai acabar com esse esquema de importação, ok?
Comment: Sim. Sabendo de todas essas questões, como então eu poderia criar uma solução melhor para este problema, já que não posso usar CodeFirst e o projeto todo já se baseia nessas tabelas importadas?
Comment: Pois então, este link é útil para colocar propriedades e métodos adicionais a uma classe gerada automaticamente sem perder as modificações, mas no meu caso eu preciso implementar uma interface. Vou testar se é possível fazer isso com MetaDataTypes aqui.
Comment: Existe, talvez, alguma forma então de fazer com que um código iniciado com CodeFirst mude automaticamente com alguma alteração realizada no banco? (importar as modificações)?
Answer: Descobri que a solução é mais simples do que eu esperava.
<code>//Classe gerada automaticamente pelo EF
public partial class BaseClassPartialTests
{
    public string PropTeste1 { get; set; }
    public string PropTeste2 { get; set; }
    public string PropTeste3 { get; set; }
}

//Como a classe gerada pelo EF é uma Partial Class,
//basta criar, em outro arquivo, uma outra classe parcial herdando da interface que eu quero.
public partial class BaseClassPartialTests : IBaseProps
{
    public BaseClassPartialTests()
    {
        PropTeste1 = PropTeste2 = PropTeste3 = string.Empty;
    }
}

//Interface para aplicar nas classes.
public interface IBaseProps
{
    string PropTeste1 { get; set; }
    string PropTeste2 { get; set; }
}
</code>
A desvantagem é que eu vou ter que criar uma classe parcial para cada classe gerada automaticamente pelo EF, mas ao aplicar a interface nelas, vai possibilitar deixar todos os meus códigos de acesso a dados bem mais genéricos e menos repetitivos. Inclusive com a possibilidade da criação de construtores.

Organizar Classes EDMX


Please Help I am Stucked in Between the Application

Question: i am Explaining the whole question:
I will take 2 forms, 3 text box and 2 buttons .
In 1st form i have draged 1 button and 2 textbox.
Now when i will enter some value and click on button . then one new 2nd form will appear with one button and 1 textbox . Now i have to enter the value in textbox in the new 2nd form. Now the first should be disable till I click the button on the 2nd form or close the 2nd form. and after the 2nd form is closed or the first form should get the focus. And if clicked on the button at the 2nd form then also the 2nd form should be closed and 1st form should get the focus.
Please help ... I am stucked in between the application..
Comment: where is the code ? What have you tried ? What is not working ?
Answer: This can be accomplished in Form1 using code like this for the button click handler:
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        Form2 f2 = new Form2();
        f2.ShowDialog(); // <-- Form1 will be inaccessible until "f2" is closed
    }
}

Over in Form2, you have:
public partial class Form2 : Form
{
    public Form2()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        this.DialogResult = System.Windows.Forms.DialogResult.OK;
    }
}

But you didn't really say what was supposed to be happening with the TextBoxes...


Highlight active menu and submenu using JavaScript

Question: I have mostly got this work, however I have 2 issues:

The Home menu link always remains active
When I select a sub-menu item, the sub-menu item shows as active, however I also require the parent to remain active.

See the live site here - http://www.lync.geek.nz/
JavaScript:

HTML Menu:

Home

Tools

Admin Tools

Call Accounting/Reporting

Phone Edition Log Viewer

Sonus SBC 5k/SWe Log Viewer

Customer Support Tool

PowerShell Scripts

PowerShell One-Liners

Lync Updates

Lync 2013 Server

Lync 2010 Server

Lync 2013 Client

Lync 2010 Client

Lync for Mac

Lync Store App

Lync Room System

Lync Phone Edition

Training

End User

Troubleshooting

SIP

Deployment

About

Contact

CSS:
/*DROPDOWN MENU MOD*/

/* ----- CSS Nav Menu Styling ----- */
#nav {
margin: 0px 0 0 0px;
padding: 0px 0px 0px 0px;
width: 1148px;  /* Set your width to fit your blog */
/*font: $(tabs.font); Template Designer - Change Font Type, Size, Etc */
/*color: $(tabs.text.color); Template Designer - Change Font Size */
}

ul#nav li a.active {
    position: relative;
    z-index: 1;
    background: #dd7700 none repeat scroll bottom;
    color: #ffffff;
    -moz-box-shadow: 0 0 0 rgba(0, 0, 0, .15);
    -webkit-box-shadow: 0 0 0 rgba(0, 0, 0, .15);
    -goog-ms-box-shadow: 0 0 0 rgba(0, 0, 0, .15);
    box-shadow: 0 0 0 rgba(0, 0, 0, .15);
}

#nav ul {
/*background: $(tabs.background.color) $(tabs.background.gradient) repeat-x scroll 0 -800px;*/
_background-image: none; /* Template Designer - Change Menu Background */
height: 20px; /* Change Height of Menu */
list-style: none;
margin: 0px;
padding: 0px;
}

#nav li {
float: left;
padding: 0px;
}

#nav li a {
/*background: $(tabs.background.color) $(tabs.background.gradient) repeat-x scroll 0 -800px;*/
_background-image: none; /* Template Designer - Change Menu Background */
display: block;
margin: 0px;
/*font: $(tabs.font); Template Designer - Change Font Type, Size, Etc */
text-decoration: none;
}

#nav > ul > li > a {
/*color: $(tabs.text.color); Template Designer - Change Font Color */
}

#nav ul ul a {
/*color: $(tabs.text.color); Template Designer - Change Color */
}

#nav li > a:hover, #nav ul li:hover {
*/color: $(tabs.selected.text.color); Template Designer - Change Font Color on Hover */
/*background-color: $(tabs.selected.background.color); Template Designer - Change Font Background on Hover */
text-decoration: none;
}

#nav li ul {
/*background: $(tabs.background.color) $(tabs.background.gradient) repeat-x scroll 0 -800px;*/
_background-image: none; /* Template Designer - Change Menu Background */
display: none;
height: auto;
padding: 0px;
margin: 0px;
position: absolute;
width: 300px; /* Change Width Of DropDown Menu */
z-index:9999;
}

#nav li:hover ul {
display: block;
}

#nav li li {
/*background: $(tabs.background.color) $(tabs.background.gradient) repeat-x scroll 0 -800px;*/
_background-image: none; /* Template Designer - Change Background */
display: block;
float: none;
margin: 0px;
padding: 0px;
width: 300px; /* Change Width Of DropDown Menu */
}

#nav li:hover li a {
/*background: $(tabs.selected.background.color); Template Designer - Change Background of Link on Hover */
}

#nav li ul a {
display: block;
height: auto;
margin: 0px;
padding: 10px;
text-align: left;
}

#nav li ul a:hover, #nav li ul li:hover > a {
/*color: $(tabs.selected.text.color); Template Designer - Change Text Color on Hover */
/*background-color: $(tabs.selected.background.color); Template Designer - Change Background on Hover */
border: 0px;
text-decoration: none;
}
/*DROPDOWN MENU MOD*/

Heres an example of what happens:

Any guidance would be much appreciated.
Comment: Is there a reason why you don't use a click event to set which nav element is active?
Comment: I'm certainly no master at this stuff, so it could be a better solution, I just don't know how to implement. I search all over the net and this was the best I could come up with. Also with this being a blogger site, I thought JavaScript might be the easiest.
Answer: You might want to rethink your link hierarchy/architecture and restructure your links with folders:

Tools

and have your pages be "index.html" files in those folders,
(I am assuming a dynamic page is outside your limitations for now)
and for the home page: simply call the index.html there (or what ever it is called) in the link
Comment: Hey Ben, I am not sure Blogger supports that particular structure unfortunately. I had a bit of a look and it doesn't appear to.
Answer: The reason your home link is always active is that "/" is ALWAYS going to appear in the url.  I think you want to use document.location.pathname, and test for equality instead.
For the second problem, why not just walk up the parent tree until you are no longer in a link?  Here is an example to fix both problems:
if (document.location.pathname == aObj[i].href) {
    var link = aObj;
    while (link.tagName === 'a') {
        link.className = 'active';
        link = link.parentElement;
    }
}

Just be sure to remove the active class up the chain in your onmouseout event handler as well.
Comment: Thanks very much. I added as follows, however it seems to have stopped it working altogether:
Comment: Could you elaborate on the event handlers, this may be my issue?
Answer: Thanks to everyone for their input. I managed to get this working, and have fully documented the process on my blog, where you can also see the result.
http://www.lync.geek.nz/2015/02/highlight-current-active-menu-using-jquery-or-javascript.html


If $u=\log{\big(x^3+y^3+z^3-3xyz\big)}$.Find $\Big(\frac{\partial}{\partial{x}}+\frac{\partial}{\partial{y}}+\frac{\partial}{\partial{z}}\Big)^{2}{u}$

Question: I just started learning functions of several variables and found the above problem in my book.
The solution given in my book was by finding the value of  $\Big(\frac{\partial{u}}{\partial{x}}+\frac{\partial{u}}{\partial{y}}+\frac{\partial{u}}{\partial{z}}\Big)$ and squaring it which gives: $$\Big(\frac{\partial}{\partial{x}}+\frac{\partial}{\partial{y}}+\frac{\partial}{\partial{z}}\Big)^{2}{u}=\dfrac{9}{(x+y+z)^2}$$
I also found the same question here and the solution given here by @Ivo Terek seems to be perfect. But here: $$\Big(\frac{\partial}{\partial{x}}+\frac{\partial}{\partial{y}}+\frac{\partial}{\partial{z}}\Big)^{2}{u}=\dfrac{-9}{(x+y+z)^2}$$
My Doubt:
Is $\Big(\frac{\partial{u}}{\partial{x}}+\frac{\partial{u}}{\partial{y}}+\frac{\partial{u}}{\partial{z}}\Big)^{2} = \Big(\frac{\partial}{\partial{x}}+\frac{\partial}{\partial{y}}+\frac{\partial}{\partial{z}}\Big)^{2}{u}$ and which of the above solution is correct ?
Also it will be great help if someone can attach the source to learn this specific concept as my book doesn't have much clear explanation. Thanks!
Answer: Note that
$$
\left(\frac{\partial}{\partial x} + \frac{\partial}{\partial y} + \frac{\partial}{\partial z}\right)^2u = \left(\frac{\partial}{\partial x} + \frac{\partial}{\partial y} + \frac{\partial}{\partial z}\right)(u_x+u_y+u_z) = u_{xx}+u_{yy}+u_{zz} +2u_{xy}+2u_{yz}+2u_{zx}
$$
but
$$
\left(\frac{\partial u}{\partial x} + \frac{\partial u}{\partial y} + \frac{\partial u}{\partial z}\right)^2 = (u_x)^2+(u_y)^2+(u_z)^2+2u_xu_y+2u_yu_z+2u_zu_x
$$
which are clearly not equal in general.
The problem comes from the fact that the square in the first expression is a squared composition, i.e. the composition of an operator with itself, whereas the square in the second expression is the "standard" algebraic square, i.e. multiplication with itself.
You should follow IvoTerek's resolution $-$ which saves a lot of time by the way $-$, which produces a negative sign (it was expected, since $(\ln x)'' = -1/x^2$); however, beware of his solution still different from yours.


How can I set up an nginx reverse proxy combined with try_files?

Question: I'd like to call a named location which handles a reverse proxy directive. So I've tried the following lines in my virtual host section:
upstream node_upstream {
    server 127.0.0.1:8000;
    keepalive 64;
}

server {
  server_name my.host-name.com;
  listen 80;
  access_log  /home/webhost/logs/my-host-name.access.log;
  error_log  /home/webhost/logs/my-host-name.error.log;

  root /home/webhost/www/my.host-name.com/node-canary/public;

  location / {
    index index.html;
    try_files $uri $uri.html $uri/index.html $uri/ @node;
  }

  location @node {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $http_host;

    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";

    proxy_pass http://node_upstream/;
    proxy_redirect off;
    proxy_read_timeout 240s;
  }
}

This is pretty straight forward, but on running it, I get
nginx: [emerg] "proxy_pass" cannot have URI part in location
given by regular expression, or inside named location, or inside
"if" statement, or inside "limit_except" block in
/home/webhost/sites-enabled/my.host-name.com:29
nginx: configuration file /usr/local/etc/nginx/nginx.conf test failed

For me this means I can't use proxy pass in the @node named location.
So, I tought I could outsmart nginx by simply moving the directives located in the @node location into the root (i.e. /) location. Anything outside remains the same. Like this:
server {
  server_name my.host-name.com;
  listen 80;
  access_log  /home/webhost/logs/my-host-name.access.log;
  error_log  /home/webhost/logs/my-host-name.error.log;

  root /home/webhost/www/my.host-name.com/node-canary/public;

  location / {
    index index.html;
    try_files $uri $uri.html $uri/index.html $uri/ $uri;

    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header Host $http_host;

    proxy_http_version 1.1;
    proxy_set_header Upgrade $http_upgrade;
    proxy_set_header Connection "upgrade";

    proxy_pass http://node_upstream/;
    proxy_redirect off;
    proxy_read_timeout 240s;
  }
}

But with this setup, something weird happens. When an existing static file is being hit, the request is being answered by the proxy connection (a node app) – not by responding with the static file itself.
That's the only case a request returns a valid response. Any route not matching a static file returns a an nginx 500 server error.
This sort of baffles me up to the point of being flabbergasted.
Comment: Use `proxy_pass http://node_upstream;` instead of `proxy_pass http://node_upstream/;` - Nginx is complaining about the trailing `/` which you probably don't need anyway.
Comment: Yes, it was the trailing slash. Thank you so much!!! I've been doing this for so long now and still step into the same traps.

I you turn you comment into an answer, I'll mark it of as valid answer for your credits.
Answer: The error message "proxy_pass" cannot have URI part in ... is simply referring to the trailing / in your proxy_pass statement.
Use:
proxy_pass http://node_upstream;

instead of:
proxy_pass http://node_upstream/;

See this document for details.


Try except clause adjacent to if statement conflict

Question: Let me explain the problem with some demo codes:
 def my_func:
    if not a:
        #operations A here.
    try:
        #operations B here.
    except:
        #operations C here.

The problem here is that the try-except clause seems to be included into the if statement. Only if "not a" is True, the try-except clause statements would be executed, other wise they would never be executed.
I tried to shrink some indent space before try-except clause as follow:
def my_func:
    if not a:
        #operations A here.
try:
    #operations B here.
except:
    #operations C here.

Now everything seems to work as try-except is executed independently with the if statement.
Any explanation is really appreciated.
Comment: The first block works as expected for me: see http://ideone.com/yLahE2
Comment: The indentation in your sample looks correct. You should show us some real code instead.
Comment: You may have mixed tabs and spaces, leading the interpreter to think the indentations are different. Please try to run the program with `python -tt` and python will probably complain about mixing tabs and spaces. In this case fix the indentation using always spaces instead of tabs. The only thing I can tell for sure is that *if* the problem is not this mixing and *if* the code has indeed the same structure you show, then there must be something else wrong with *your* code so you should consider providing an example that we can run.
Comment: @bakuriu Please make your comment as answer. It seems to I did mix tab with whitespace in this situation.
Answer: You have mixed tabs with spaces in your indentation, this lead the interpreter to misinterpret the indentation levels, thinking that the try was one level higher:
>>> if True:
...     if True:   # indentation with 4 spaces. Any number will do
...     a = 1      # indentation with a tab. Equals two indents with spaces
...     else:      # indentation with 4 spaces
...     a = 2
...
>>> a   # as if the "a = 1" was inside the second if
1

To check whether this is the problem launch the program via python -tt which raises an error if it finds mixed tabs and spaces. Also note that when using python3 it automatically runs with the -tt option, not allowing mixing tabs and spaces.


Show that solution satisfies the differential equation

Question: $$a \equiv a(\sigma,t)$$
$$b \equiv b(\sigma,t)$$
$$ \frac{1}{2}\frac{d^2}{d\sigma^2}(b^2p) - \frac{d}{d\sigma}(ap) = 0$$
Show that the following satisfies the above differential equation:
$$p(\sigma) = \frac{A}{b^2}e^{\int^\sigma \frac{2a}{b^2} d\sigma'}$$
Considering the boundary conditions that as $\sigma \to \infty$, $p \to 0$ and $\frac{dp}{d\sigma} \to 0$
Attempted solution: the line of attack is to differentiate with respect to $\sigma$ given what we have for $p$.
So, starting with the first order differential:
$$\frac{d}{d\sigma}(ap) = a.p' + a'p$$
Exuse the mixed notation style. Given the boundary conditions in the question don't both of these terms become 0?
Also, is there a way to calculate the value of A given the boundary conditon. I asked a related question here but we ended up finding the solution to the DE, instead of showing that the given solution satisfies the DE. Hence this new question.
Answer:
Given the boundary conditions in the question don't both of these terms become 0?

The boundary conditions apply on the boundary. The verification of equation is done inside the domain. These are unrelated things.

Actually, you don't need to find the derivative of $ap$. Begin from the other end: take the derivative of
$$
b^2p = A\exp\left( \int^\sigma \frac{2a}{b^2} d\sigma' \right)
\tag1$$
with respect to $\sigma$:
$$
\frac{\partial}{\partial\sigma}(b^2p) = A\,\frac{2a}{b^2}\exp\left( \int^\sigma \frac{2a}{b^2} d\sigma' \right) = 2ap
\tag2$$
Thus, the equation becomes
$$
\frac{1}{2}\frac{\partial}{\partial\sigma}(2ap) - \frac{\partial}{\partial\sigma}(ap) = 0
$$
which is obviously true.

I don't see how one could get $A$ from the boundary conditions you have, unless $A$ is zero.  Notice that if $p$ is a function that satisfies all of the stated conditions, then $2p$, $3p$, etc also satisfy them.


Programmatically added Views in TableLayout / TableRow have a height and width of 0

Question: I have a TableLayout in my app, which I need to define and add programmatically, as it builds upon the output of an SQL query. Basically, the result should look similar to a timetable (7 columns for each day in a week, multiple rows for different timeslots per day). For the cells/timeslots, I just need ordinary views with a certain background colour.
The problem is, that all views end up with a height and width of 0, although defined otherwise. What am I doing wrong?
Code:
RelativeLayout.LayoutParams tableLayout = new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
tableLayout.addRule(RelativeLayout.BELOW, R.id.myOtherLayout);
tableLayout.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);

TableLayout table = new TableLayout(this);
table.setBackgroundColor(Color.WHITE);
table.setMinimumHeight(PixelConverter.pxToSp(this, 240));

// get availability table data
int[][] tableData = getTableData(...);

if (availability != null) {
    // init array of tablerows, which represent one line each for every timeslot
    for (int timeSlot = 0; timeSlot < 12; h++) {
        // init row
        TableRow newRow = new TableRow(this);
        newRow.setLayoutParams(new LinearLayout.LayoutParams(
            LayoutParams.FILL_PARENT, // width
            10)); // height
        newRow.setMinimumHeight(10);

        // create 7 views in each row - one for each day in a week
        for (int day = 0; day < 7; d++) {
            View v = new View(this);
            v.setLayoutParams(new LinearLayout.LayoutParams(
                10, // TODO width
                10)); // height
            v.setMinimumWidth(10);
            v.setMinimumHeight(10);

            int cellHue = tableData[day][timeSlot];
            if (cellHue >= 0) {
                v.setBackgroundColor(Color.HSVToColor(new float[] { cellHue, 100, 100 }));
            } else {
                v.setBackgroundColor(Color.TRANSPARENT);
            }

            // add view to tablerow
            newRow.addView(v, day);
        }

        table.addView(newRow, timeSlot);
    }
}

table.setId(R.id.my_table_id);
mainLayout.addView(table, tableLayout);

Answer: I've encountered a similar issue - the problem appears to be with the choice of type of LayoutParams used after inflating your views.  Particularly, the following is probably the root of your problem:
View v = new View(this);
        v.setLayoutParams(new LinearLayout.LayoutParams(
            10, // TODO width
            10)); // height

I'd suggest that you try:
View v = new View(this);
        v.setLayoutParams(new TableRow.LayoutParams(
            10, // TODO width
            10)); // height

The key is that you apparently should specify the type of the parent view when using LayoutParams, rather than the type of the view that you're setting them on.  Note that in this case, you'll probably need to specify TableLayout.LayoutParams when calling setLayoutParams on your row, too.
I don't know how well documented this is - I noticed it mentioned on an arbitrary blog I'd found (lost the link now, alas) and I haven't had chance to go back to the official documention yet, but presumably it's there somewhere... :)
Hope this helps!
Comment: Yup, glancing at the doc for LInearLayout: "Set the layout parameters associated with this view. These supply parameters to the **parent** of this view specifying how it should be arranged. There are many subclasses of ViewGroup.LayoutParams, and these correspond to the different subclasses of ViewGroup that are responsible for arranging their children."
Comment: Yes, that worked - thanks Matt ! Actually worked around it in different ways, but I could swear I saw an official Google tutorial taking the "wrong" LayoutParams (therefore thought they are more or less interchangable).
Comment: Yeah, I'm pretty new to Android and I've seen *plenty* of examples knocking about using the wrong LayoutParams.  Ah well, got there in the end :)


Reduction of order - Differential Equations?

Question: I have this problem:
$$yy''+ (y')^2 = 1$$
I know I have to use: $y' = z$ and $y'' = z \frac{dz}{dy}$
but I'm not getting the answer which is: $$y^2 = c_1 + (x + c_2)^2$$
Please help
Answer: Hint: try the substitution $w(x) = y(x)^2$, and calculate what $w''(x)$ in terms of $y(x)$ and its derivatives.


Hide Ribbon Button Crm 2011

Question: I have to hide a ribbon button when the owner of the record isn't the current user.
I'm using Visual Ribbon Editor for CRM 2011 however I didn't find out the solution yet. I tried to use Field rule ValueRule but it just allows me to put a bool value (1 or 0).
Can anyone please tell me how can I do that?
Thank you in advance!
Comment: try with Ribbon Workbench http://www.develop1.net/public/page/Ribbon-Workbench-for-Dynamics-CRM-2011.aspx I don't remember if is possible to do without a javascript rule, if I have time I will test and write an answer
Comment: possible duplicate of [crm 2011 how to hide/show the ribbon button with javascript](http://stackoverflow.com/questions/14585141/crm-2011-how-to-hide-show-the-ribbon-button-with-javascript)
Answer: Add a Enable Rule like this:
<EnableRules>
    <EnableRule Id="YourEntity.Form.XXX.MainTab.XXXXXXXXXX.CustomRule" />
</EnableRules>

Rule Definitions as below:
<RuleDefinitions>
    <TabDisplayRules />
        <DisplayRules />
        <EnableRules>
            <EnableRule Id="Email.Form.email.MainTab.XXXXXXXXXX.CustomRule">
                <CustomRule FunctionName="DisableButton" Library="$webresource:new_/js/xxx.js" InvertResult="true" />
            </EnableRule>
        </EnableRules>
</RuleDefinitions>

Write a JavaScript function DisableButton and to return true or false based on your condition. Reference the js webresource in CustomRule Library.
Comment: @BrunoWillian your welcome, Please mark as a answer if it helped you. Cheers
Comment: Why does that code don't work with ? like this.
Comment: @BrunoWillian have you tried to use RibbonEditor? You can easily generate the working xml using RibbonEditor.
Comment: Yes I did but its dosn't able me to insert custom rule on ribbon button. This way you gave me totally works with Enable Rule. But what I wanted is put a custom rule in Display Button not in Enable button. I've searched for that but all examples and posts I've found out is about Enable. Sadly it's looking like that's not possible to put a Custom Rule in Display Rule of a button.
Answer: Value Rules cannot be used with Hide Actions - so you'll need to use a Custom JavaScript Rule with an Enable rule to enable/disable the button rather than hide it.

Hide Ribbon Button Crm 2011


why am i getting a Drupal\Component\Plugin\Exception\PluginNotFoundException: when the plugin does exist?

Question: I wrote a custom source plugin and put it in migd8_node_blog/src/Plugin/migrate/source/Node.php
with
<?php

/**
 * @file
 * Contains \Drupal\migd8_node_blog\Plugin\migrate\source\Node.
 */

namespace Drupal\migd8_node_blog\Plugin\migrate\source;

use Drupal\migrate\Row;
use Drupal\node\Plugin\migrate\source\d7\Node as D7Node;

    /**
     * Custom node source including url aliases.
     *
     * @MigrateSource(
     *   id = "migd8_node_blog_node"
     * )
     */

    class Node extends D7Node {

but i keep getting this error when i run drush mim migd8_node_blog Drupal\Component\Plugin\Exception\PluginNotFoundException: The "migd8_node_blog_node" plugin does not exist.
even after flushing the cache and reinstalling the module.
Comment: Two last things that I'd add - firstly what are you running to get the error (presumably `drush mim` but being explicit is good), and I'd confirm that the path you've provided to the file is relative to `module/src`. Hopefully after that the downvoters will revisit and reconsider, as it would then be a good question IMO
Comment: And the casing's right on the file/class names? For `node.php` the class would be `node`, not `Node`, for example. Or if the class is `Node` the filename needs to be `Node.php` depending on how you want to look at it
Comment: Did you add a correct namespace matching the machine name of your module?
Comment: yes namespace Drupal\migd8_node_blog\Plugin\migrate\source;
Comment: yes class Node extends D7Node { the file name is Node.php
Comment: use Drupal\migrate\Row;
use Drupal\node\Plugin\migrate\source\d7\Node as D7Node;
Comment: You should put all the extra information (and fix the filename) in the question, it won't be useful in the comments
Comment: ive done that now
Comment: when i disabled and reenabled the module and deleted the configuration it worked.
Answer:
after flushing the cache and reinstalling the module

Check that the module is indeed installed at /admin/modules, if it's not, it's due to a migrate tools bug. Perhaps you deleted the part
dependencies:
  enforced:
    module:
      - migd8_node_blog

that you have in your other question, which fixes the reinstall bug if you have it before you install the module.
But if you installed it without the above code, you'll have to run this code once/one time only, and it will allow you to install again as this code removes the stuck configuration.
  $module_path = DRUPAL_ROOT . base_path() . drupal_get_path('module', 'migd8_node_blog') . '/config/install';

  $configs = array();
  $files = file_scan_directory($module_path, '/migrate_plus/');
  if ($files) {
    foreach ($files as $file) {
      $configs[] = $file->name;
    }
    // Delete each config using configFactory.
    foreach ($configs as $config_name) {
     \Drupal::configFactory()->getEditable($config_name)->delete();
    }

    return TRUE;
  }

If the modue is indeed installed, then the issue is due to you trying to assign migd8_node_blog_node as a plugin under the wrong key.
Since this is a source plugin and should be used only be used under source: and not/never under process: or any other key. See my answer.
Comment: id: migd8_node_blog
label: Custom node migration from Drupal 7
migration_group: cncs
dependencies:
  enforced:
    module:
      - migd8_node_blog_node
source:
 plugin: migd8_node_blog_node
 node_type: blog_entry
destination:
  plugin: entity:node
  bundle: blog
Comment: okay as in the previous question after uniinstalling and reinsalling the module and deleting the configuration it finally worked.


Creating many new dataframes in R

Question: I need to create a lot of dataframes. is there any faster way where you can only specify the names of new tables and assign <- data.frame () once ?
results_test <- data.frame()
results_OA<- data.frame()
results_SVM <- data.frame()
results_SVM_linear <- data.frame()
results_SVM_RBF <- data.frame()

Answer: Use replicate to create a list of n data frames, name them using setNames.  Finally, with list2env put the list objects into e.g. the global environment.
df.names <- paste0("results_", c("test", "OA", "SVM", "SVM_linear", "SVM_RBF"))
df.list <- setNames(replicate(n=length(df.names)), df.names)
list2env(df.list, envir=.GlobalEnv)

Result:
ls()
# [1] "df.list"            "results_OA"         "results_SVM"        "results_SVM_linear"
# [5] "results_SVM_RBF"    "results_test"

Answer: Here is using for loop, base R
names<-c("test", "OA", "SVM", "SVM_linear", "SVM_RBF")
for(i in 1:length(names)){
  assign(paste0("results_",names[i]),data.frame())
}

Creating many new dataframes in R


Basic principles of piano fingering for simple right hand melody

Question: I play various instruments already but am teaching myself piano. I want to play simple melodies like the one shown below. It seems a general principle regarding fingering is to allocate one finger to each note in a scale over a 5 note span, and then to pivot using the thumb. However it is not always clear where to pivot, and it also seems that the occasional deviation from such a strict pattern may well increase playability considerably.
I'm wondering if someone could give me some pointers on which fingers to use for the right hand melody in the piece below, along with a description of the general principles from which the specific fingering is derived?
Comment: I'd highly recommend practicing scales. It will make it a lot easier to figure out fingerings on your own, since they provide you with a fundament you can fall back on.
Comment: Can't help asking why, when the piece is in key Em, there are 2# in the key signature. Or is it deemed to be in E Dorian?
Comment: Couple of points - Swallowtail Jig was originally for fiddle and tin whistle, both of which can play repeated notes more easily that piano. And some pianos (mainly grands) have a far quicker key recovery, making those repeated notes easier to play, with different , or the same finger/s.
Comment: Definitely Dorian. Many "minor" Irish tunes use a kind of "melodic Dorian", with major 6 ascending and minor 6th descending.
Answer: Let's consider three "positions" which are very common...

I made up the three labels "5 finger", "full octave scale",  and "full octave chord", but something like those labels is used in many piano method books.
Now apply those to a passage with some position changes starting at bar 2 beat 2...

Or it could be done like this...

The slur lines are not meant to be actual performance phrases, but are meant only to show groupings of notes into one of the three position types.
Notice that the F#4 marked with * is common between two positions, an incomplete run of 5 finger on E, which ends on finger 2, and the beginning of a full octave chord on D. That finger 2 is the place where you "pivot" between two positions.
Also notice the G4 to F#4 marked with **. This is the other place where you "pivot" into a different position. Especially notice how the first G4 is played with finger 1, but after the pivot into a new position, the G4 is played again, but with finger 3.
You can think of some of these position changes as "contracting" or "expanding" beyond a given position. For example, at the first change * you can think of the move from F#4 finger 2 "expanding" or "extending" the end of a 5 finger on E down a step to reach the D to start a full octave chord position.
The change at ** can be seen as a "contracting" of the full octave scale on D where normally the Gf to F#4 would be played with fingers 1 and 3, but because we a pivoting to a 5 finger on E the F#4 is then played by finger 2. It's like the bottom part of the full octave scale on D is "contracted" up into the E position.
Expanding and contracting positions like that happens all the time. But also some position changes are accomplished switching fingers on a repeated note, or silently changing fingers on a held note.
A lot of piano methods are based on playing  5 finger position, scales, arpeggios, repeated notes, and double note scales (like playing scales in thirds in one hand.) When you practice those kinds of patterns in all major and minor keys, and apply the patterns to simple harmonic patterns like I V I, you eventually start to make position changes without too much thought.
My suggestion is get a good method book to practice you scales, arpeggios, etc. while working on actual pieces like the jig. If drills seem boring, first be selective about the method books you choose. Some are more creative than others. Also, make your own variation on practice drills. Keep drill time at a level that suites you. Don't do zero drilling, you will miss out on a lot of fundamental skill development. Don't do to much that it kills your enthusiasm. Think of it as support for playing the real music.
Comment: Has this answer been edited since it was first posted? I seem to remember a longer section of melody. In the current one, there is no section relating to comments marked **.
Comment: @RobinAndrews, I probably just made a mistake in my final post. But I still have the notation file. I added a second image that was about the **.
Answer: I recommend Rami-Bar Niv's book "The Art of Piano Fingering: Traditional, Advanced, and Innovative".
As the title suggests it shows commonly known "standards". It later talks about finding your way, and mentiones suitable starting postitions for various keys.
Find more about the author and pianist at Wikipedia.


SQL Sum of Count Values

Question: I have this query and I'd like to get a sum of the count values in the 'membership count' column. How can I get the sum of the count values?
select count(MAJOR_KEY) 'membership count', chapter
from Name
where MEMBER_RECORD = 1 and
(STATUS = 'I' or STATUS = 'SN')
group by CHAPTER
order by CHAPTER

Comment: Help us help you - share some sample data and the result you'd like to get for that sample
Answer: If you want to get a total count from all the chapters you can use rollup/cube
try: group by rollup(CHAPTER)
select sum(c) as [membership count], chapter
from
(
   select count(MAJOR_KEY) c, chapter
   from Name
   where MEMBER_RECORD = 1 and
   (STATUS = 'I' or STATUS = 'SN')
   group by rollup(CHAPTER)
) sub
group by CHAPTER
order by CHAPTER

Answer: If you want a last row with the sum then use GROUP BY ROLLUP:
select count(MAJOR_KEY) [membership count], chapter
from Name
where MEMBER_RECORD = 1 and (STATUS = 'I' or STATUS = 'SN')
group by ROLLUP(CHAPTER)

Answer: Remove the group by:
select count(MAJOR_KEY) as membershipcount
from Name
where MEMBER_RECORD = 1 and
      STATUS in ('I', 'SN');

Note that I also simplified the WHERE clause by using IN.

SQL Sum of Count Values


Python, loops and iteration

Question: Define the method below to return the lowest factor of an arbitrary integer. The lowest factor is the smallest number greater than 1 that will divide evenly into the parameter(which will be 2 or higher).And this is my code, I don't know why is incorrect.
def first_factor(n):
    for num in range(2,n):
        if n % num == 0 and sqrt(n):
            return num

Comment: What exactly is the problem?
Comment: post the code here, not as a screenshot.
Comment: I don't know why is incorrect,could you help me thanks
Comment: @Xuan for your recently deleted question here is a start https://repl.it/EhJz/1 :)
Answer: You should be using the square root of the number in the range, not as one of the conditions.
def first_factor(n):
    for num in range(2, int(n**0.5)+1):
        if n % num == 0:
            return num

Comment: Sorry this code is not correct, could you help me,thanks.
Comment: @Xuan - Not correct in what way? It works fine for me.
Comment: @Xuan - Without any description of what's incorrect about it (wrong result? error messages?), I can't possibly help.
Answer: This is only the definition of the function - you have to call it and print the result to see it.
The full code may be:
def first_factor(n):
    for num in range(2, n + 1):
        if n % num == 0:
            return num

print(first_factor(3))

Note that I totally omitted square root as it is useless and it prevented to give a result for prime numbers.

Python, loops and iteration


Induction step in showing a convex set is convex iff it contains all convex combinations?

Question: I'm trying to follow this proof for the one in the title above.
It is here, from page 3 for the only if portion.
What I don't get is why they introduce this:
$$ y = (1-\lambda_m)[\sum_{i=1}^m \frac{\lambda_i}{1-\lambda_m}y_i] + \lambda_m y_m$$
since with each sum, the outside $(1-\lambda_m)$ simply cancels out the denominator.  Isn't it the same as writing out:
$ y = \sum_{i=1}^m \lambda_iy_i + \lambda_m y_m$ ?
Comment: It looks as though it is to express $y$ explicitly as a convex combination
Comment: @MarkBennet - Thanks, I completely missed the (1-lambda) + lambda pairing.
Answer: By definition a set $A$ is convex if $(1-t)x+ty \in A$ whenever $0\leq t \leq 1$ and $x,y \in A$.  So the idea in this proof is to write $y$ as a convex combination of just two elements of $A$. We use induction hypothesis to see that $\sum\limits_{i=1}^m \frac {\lambda_i} {1-\lambda_m}y_i$ belongs to $A$. Call this $z$. Then we use the equaltio $y = (1-\lambda_m)z+\lambda_m y_m$ to conclude that $y \in A$.


Can I describe an arbitrary graph?

Question: This is, I think, a fairly simple question, but I haven't been able to find an answer to. Is there any graph for which there's no way to describe it in terms of a polynomial, function, or any other formula? If so, why?
Comment: You can always define a function $f$ of two variables, such that $f(x,y)=1$ if the point $(x,y)$ is on the graph, and $f(x,y)=0$ otherwise.
Answer: I can draw (any) arbitrary curve that represents a function, but measuring what that function is exactly (with infinite precision) from the drawing is an insurmountable task.
Comment: @GENIVI-LEARNER the problem of keeping track of infinite number of coefficients exceeds the space available for computation
Comment: Can we simply use b-splines or Fourier series with infinite terms to describe potentially any drawings?
Comment: this makes lots of sense.

Can I describe an arbitrary graph?


Representations of $\pi_1M$ and Heegaard Splittings

Question: I am reading Floer's Instanton-Invariant paper, and am stuck on a sentence. To set the stage:
Consider a closed connected oriented 3-manifold $M$ and the nonabelian group $SU_2$. Denote the equivalence classes of representations $\mathcal{R}(M)=Hom(\pi_1M,SU_2)/\text{ad}(SU_2)$.
Now given a Heegaard splitting $M=M_+\cup_SM_-$, one can consider $\mathcal{R}(M)$ as the intersection of $\mathcal{R}(M_+)$ and $\mathcal{R}(M_-)$ in $\mathcal{R}(S)$. Indeed, Seifert van-Kampen's theorem gives $\pi_1(M)\cong\pi_1(M_+)\ast_{\pi_1(S)}\pi_1(M_-)$ and then the statement follows by the universal property of amalgamated free products.
The resulting intersection number (ignoring the trivial representation) can be shown to be independent of the particular Heegaard splitting.
[The "result" refers to the integer-valued Casson invariant, which assigns a sign to each intersection $a\in\mathcal{R}$].
How is this done?
Comment: Presumably what they're getting at is that $\mathcal R(M)$ is an idea that is independent of any particular presentation of $\pi_1 M$.
Comment: I don't understand what you mean by "the resulting intersection."
Answer: (For completeness)
This is explained/proved in the main reference of the invariant: Casson's Invariant for Oriented Homology 3-Spheres (by Akbulut and McCarthy).


What does it mean when there are two treble clefs in the same piece?

Question: What am I supposed to do in the first 12 bars?
See below for the piece.
Comment: see this question for the answer: http://music.stackexchange.com/questions/41352/piano-grand-staff-with-two-treble-clefs-where-to-place-hands
Answer: Imagine the bottom stave in each pair is played with r.h. Those are the notes to play. BUT - they're all played with l.h. as it's the bottom stave. Reason is simple. Those notes could be written in bass clef(F clef), but they'd all be on leger lines, and be a little more tricky to read.
It could all have been written in the 'normal' way,but an octave lower, with '8va' included,to sound the same, and be as easy/difficult to play.
This question may disappear as very similar ones already exist.


Filtering PrivateMsg types by "sent" or "inbox"

Question: I'm wondering what approach programmatically I should take when displaying message links that are either sent to the user loading the list, or sent out to other users.
Using some modifications to the example code listed at http://drupal.org/node/624528, I've loaded all unread and read messages regardless of author:
foreach ($query->execute() as $key => $thread) {

if ($count <= 25) {
                        // Generate a link with the subject as title that points to the view message page.
                        $items[] = array(
                            'data' => 'thread_id . '">' .
                            '

' .
                            '
' . $username . "
" .
                            '
' . $thread->subject . "
" .
                            '
' . format_date($thread->last_updated, 'short') . "
",
                            'class' => array($class),
                            'id' => $key
                        );
                        $count++;
                    } else {
                        break;
                    }

and the output is done through a theme() call. I'm seeing that messages sent return null in $thread->participant. Would this be a sufficient use case to track for sent messages?
Answer: From the page that you linked to:
// Replace 'inbox' with 'sent' to display sent messages or 'list' to display all messages.
$query = _privatemsg_assemble_query('list', $user, 'inbox');

Note that the privatemsg_filter module needs to be enabled for that to work.
Comment: The privatemsg_filter module is all that it's needed to display inbox and sent messages as tabs.


proving a wiki statement about uniform convergence and supremum

Question: This wiki page says that a sequence $f_n$ is uniformally convergenct to  $f: S \to \mathbb{R}$ if and only if $||f_n - f||_{\sup} \to 0$. I am trying to prove this statement.
For the forward implication, we have that $f_n \to f$ uniformaly, so we have that $|f_n - f| < \epsilon$. Now, it seems as though the obvious option here is to simply take the supremum of this to get the result if we choose $N$ which gives us $|f_n - f| < \epsilon$. How would I do this step by step, I mean - it seems wrong to just take the supremum of everything as this doesn't use the fact that $f_n$ is uniformaly convergent to $f$
I have yet to try the backwards implication.
Answer: It's just another way to state the definition :
This is your base definition
$$\forall \epsilon > 0, \exists N, \forall n > N, \forall x, \quad |f_n(x)-f(x)|< \epsilon$$
This is what means $\|f_n-f\|_{\sup} \to 0$ :
$$\forall \epsilon > 0, \exists N, \forall n > N, \quad  \|f_n-f\|_{\sup} < \epsilon$$
And now replace $\|f_n-f\|_{\sup}$ by it's definition :
$$\forall \epsilon > 0, \exists N, \forall n > N, \quad  \sup_{x} |f_n(x)-f(x)| < \epsilon$$
And it's the same thing that
$$\forall \epsilon > 0, \exists N, \forall n > N, \forall x, \quad |f_n(x)-f(x)| < \epsilon$$


Confused with why private variable can be accessed?

Question: I recently see a question that what is the execution result of this code below.
public class Sandys {
    private int court;
    public static void main(String argv[]){
        Sandys s = new Sandys(99);
        System.out.println(s.court);
    }
    Sandys(int ballcount){
        court = ballcount;
    }
}

I think it can't be executed because in main i try to access a private variable.
However, this code can be perfectly executed, and the result is 99. So I am confused, why the private variable can be accessed in this code? Though the main is in Sandys class, however i create a new Sandys. Can I still access the private variable of the new Sandys object in main?
Comment: Answer is here. http://docs.oracle.com/javase/tutorial/java/javaOO/accesscontrol.html
Comment: http://stackoverflow.com/questions/4707504/why-can-i-access-a-private-variable-from-main-method
Answer: You can access private members from inside the same class, even in static methods.
Answer: main() is a special method because it is used as a starting point for java application. However, it is still a normal static method and it follows all access restrictions of static methods. Is this main() a class method? Yes, it is. Hence, it can access private members of the same class.
Consider this: if there was no access to private fields factory methods would have to be written differently.
class A {
  private int a=0;
  private int b=0;

  private A() {}

  //getters

  public static A getNewInstance(int a, int b) {
    A a = new A();
    a.a = a;
    a.b = b;
    return A;
  }

It does make sense, doesn't it?
Answer: You can access ALL private, protected, public and not modifier variables inside class, but you can not access private variable from another class.
P.S. It is truth also for C#, C++ and many other programming languages.
Answer: A class is defined to some particular job and in that way it may use some variables that  it don't want others to access it("others" means outsider classes) and some you want other classes to access it.It all depends on your requirement.
"Private instance variables are defined to be used in only with in the class".and since in your code you are trying                to access the private instance variable inside the class itself then it is perfectly legal.
Note: A static method cannot access the instance variables if u want specify the instance i mean create the instance(object) inside of the static method and access it through the created reference.


Angular 2 how to implement two way binding for level 2 child?

Question: An object is a property of parent component
const public object = {value1: 'test1'};
And it's used as a property for child component
<app-child [(obj)]="object"></app-child>
the child component itself has other child that takes value1 field as a property
<app-child-2 [(value)]="obj.value1"></app-child-2>
The question is, can I use [(value)] for the second child or the only way how I can set up two way binding from the parent to the second child is't
<app-child-2 [value]="obj.value1" (valueChange)="updateObjectFun()"></app-child-2>
where updateObjectFun will set emit objectChange Output.
Comment: Have you tried `ngModel` ?
Comment: you should use [(ngModel)] and not [(propertyName)]
Comment: app-child is the parent of appchild2 right? Then app-child2 should emit to app-child which inturn will emit to parent.
Answer: You can use the two-way binding syntax if your child component has the correct 'interface'. So, for eg, if your second child component has an input binding of value and an output binding of valueChange then you can use the two-way binding syntax: [(value)]="obj.value1".
The two-way binding syntax is the exact equivalent of:
[value]="obj.value1" (valueChange)="obj.value1=$event"

where $event is the object emitted from the valueChange output property of your component. If you have control over the interface of your component (i.e. you can create whatever properties you want), then feel free to take advantage of the two way binding syntax.
ngModel is only necessary for situations where you don't have control of the interface of the component you're binding to, and as such can't use the two way binding syntax shortcut.
(The above statement is not completely true since ngModel also serves an extra purpose when dealing with template-driven forms, but for your use case, that's not a concern).
Comment: Any idea why this example does not work? https://angular-yqhzlp.stackblitz.io
Comment: In the previous example, clicking the top button would update all three, but clicking the bottom button only updated its immediate parent. In this new example, I changed the hierarchy to use an EventEmitter at the top, and at the bottom, I have a BehaviorSubject. Now clicking either button updates all three bindings. https://stackblitz.com/edit/angular-wgggtd?file=src%2Fapp%2Fparent.component.ts
Comment: I think you've misunderstood the problem here. The question isn't about how to achieve two-way binding (which your answer covers), it's about what happens when you try to do that through 2 layers of nested components. I think the author of the question is correct in that you have to separate out the inputs and outputs in the middle layer template to make this propagate correctly all the way out.


Batch echo in FOR /F loop

Question: I have a CSV file which has 3 columns. I'm trying to extract the value in the column third and remove quotes from values and write it into another csv. The columns are seperated with "," so I select the column third with
for /f "tokens=3 delims=, " %%a in (example.csv) do (
 echo %aa >> example2.csv
)

It works perfect but the data comes with quotes like "5884" so I tried
for /f "tokens=3 delims=, " %%a in (example.csv) do (
    set /A tirnak=%%a
   echo %%tirnak >> example2.csv
)

When I "set /A tirnak=%%a" output value has no quotes in CMD and I can make it echo in a text file, but when I use it in the loop output in the file is
ECHO is on.
I tried echo %tirnak%, echo %tirnak, echo %%tirnak but the output in the file is either ECHO is on, empty, sth like %tirnak etc. How can I do that? Thank you.
Comment: [enable delayed expansion](https://stackoverflow.com/q/22278456/995714) and use `!tirnak!`
Comment: Or just avoid using multi-line code blocks all together: `do call :SetTirnak %%a`, then define a label `SetTirnak` add your code there and terminate it with an `exit /b 0`. Don't forget to add an `exit /b 0` after the for loop though.
Comment: You should consider reading the help file for the commands you are trying to use.
Answer: Using your chosen Tokens and Delims, this looks like what you need:
For /F "UseBackQ Tokens=3 Delims=, " %%A In ("example.csv") Do (
    Echo %%~A)>>"example2.csv"

Comment: Absolutely! OP: please cut-and-paste code - don't rewrite it. Your code line `echo %aa >> example2.csv` could not give you the results you claim. `echo %%a >> example2.csv` - now *that* I'd believe.

Batch echo in FOR /F loop


Duvida em desenvolvimento de webservice para APP(android) e WEB(php)

Question: Olá, estamos desenvolvendo uma APP para android e essa vai fazer uma consulta em um webservice(que ainda não esta feito) para validar dados solicitados pela APP.
O mesmo projeto roda na web e esta desenvolvido em php, jquery etc.
Então tenho 2 aplicações uma para WEB(php) acessada por PC,Tablet, Celular e outra  somente para Android (.apk), as duas versões fazem a mesma coisa basicamente que é consultar dados em um webservice, este irá retornar dados para as aplicações com informações da consulta solicitada.
Pergunta: Como as duas aplicações (web e apk) irão fazer consultas nesse webservice que vamos desenvolver, qual a melhor opção para desenvolver este webservice de maneira que o mesmo seja rápido e atenda as duas aplicações?  Desenvolver em PHP, JAVA, NODEJS? Qual diferença entre cada webservice, alguma vantagem que algum tem sobre o outro? Se precisar de mais informações favor comentar.
Já tenho algumas dicas que andei pesquisando, quero uma ajuda e um parecer de alguem que já tenha feito algo parecido.
Espero ter deixado claro a pergunta e explicação. Desde já Obrigado.
Answer: Penso que o melhor para ajudar é desde já definir que tipos de webservices pode encontrar aos dias de hoje "os mais comuns".
Defino duas situações embora um seja na realidade um protocolo:

Webservice SOAP - Simple Object Access Protocol (SOAP) um padrão que utiliza o XML como base da sua arquitectura. Pode ser utilizado em SMTP, HTTP, FTP etc. Exige suporte de "middleware", mecanismo bem definido para definir serviços como WSDL + XSD, WS-Policy retornará dados estruturados em XML
Webservice RESTFul - Representational State Transfer (REST) de serviços web. São serviços da Web de segunda geração. Serviços Web RESTful, comunicacam via HTTP e ao contrário de um serviço baseado em SOAP não necessita da estrutura XML ou das definições de serviço WSDL-API. HTTP simples não sendo necessário nenhum "middleware". Padrão, REST pode retornar XML, texto simples, JSON, HTML etc

Já utilizei os dois e ainda utilizo mas tenho ao longo do tempo abandonado o SOAP e substituído por serviços REST equivalentes. E porquê?
Como profissional sigo o mercado e a tendência é claramente o REST certamente vê muita referência ao REST API. Pessoalmente entendo que o REST é definitivamente o caminho actual para criar um serviço Web.
O seu API será mais limpo e mais fácil de entender/descobrir. Ao sincronizar dados com um site e ou aplicativo, é provavelmente mais fácil para descansar o utilizador porque você pode simplesmente dizer sincronização ("/artigos/1/") ou qualquer outra coisa. Mapear operações é fácil... operações CRUD, etc.
Dito isto resta a resposta directa à sua pergunta:

Desenvolver em PHP, JAVA, NODEJS?

Da minha experiência iria pelo PHP. É uma linguagem "script" de servidor, suporta muito bem o protocolo HTTP, a comunidade é extensa e cheia de exemplos mas como razão principal olho para a sua experiência.
Tendo dito na pergunta que já tem um projecto WEB feito em PHP e JQUERY é indicador que já detêm conhecimento nesta linguagem pelo que a sua curva de aprendizagem será certamente inferior às outras e este sinceramente é no meu entender o motivo principal.
Comment: Obrigado, era isso que precisava ouvir.


Async querySelector access

Question: I'm trying to access df-chips.

However, that doesn't load at first sight, so I was trying to access it with asyng / await. But... I'm not good at javascript, so I'm doing something wrong and I don't know what.
This is my code:
// Function to catch asynchronous that node
const asyncQuerySelector = async (node, query) => {
  try {
     if (node.querySelector(query)){
      return await node.querySelector(query);
     }
  } catch (error) {
    console.error(`Cannot find ${query ? `${query} in`: ''} ${node}.`, error);
    return null;
  }
};

const root = document.querySelector('#messageList')
const foo = asyncQuerySelector(root, 'df-chips')

But I'm getting a null promise result:
Comment: 1. You don't need a promise to select an element in the DOM via javascript. 2. `async` function always returns a promise. 3. Awaiting something that doesn't returns a promise is unnecessary. 4. Make sure the target element is in the DOM before you try to select it via JS.
Comment: `await node.querySelector(query)` doesn't make sense; `querySelector` doesn't return a Promise. Use [`MutationObserver`](//developer.mozilla.org/docs/Web/API/MutationObserver) instead.
Comment: thank you, i've posted the solution of my case, based in your help
Answer: async functions are tools to allow you to manage promises via the await keyword.
querySelector does not return a promise, so awaiting it is pointless, so using async in the first place is pointless.

querySelector searches the DOM immediately and returns the result (which is null if it can't find what you are looking for).
It doesn't have any kind of built-in automatic retry mechanisms.

If you want to detect when an element appears then you need to either:

Listen for mutations to the DOM
Poll (e.g. with querySelector in a recursive setTimeout or a setInterval) the DOM using querySelector until it does appear (i.e. build the aforementioned automatic return mechanism).

You could wrap either of those approaches with new Promise(...) if you wanted to await the result.
That said, anything outside the async function will receive a promise because async functions can't make asynchronous code into non-asynchronous code either.
Comment: thank you! with your help i was able to create a solution that works
Answer: Thank you for all your help
I've created this solution, which works well (can't tell if it is efficient)

const callback = function(mutationsList, observer) {
  // Use traditional 'for loops' for IE 11
  for(const mutation of mutationsList) {
    try{
      if (mutation.addedNodes[0].localName == 'df-chips'){
        console.log(mutation.addedNodes[0])
      }} catch(error){
          console.log(error)
        }
    }
};

foo = document.querySelector('#messageList')

// Options for the observer (which mutations to observe)
const config = {childList: true, subtree: true };

// Create an observer instance linked to the callback function
const observer = new MutationObserver(callback);

// Start observing the target node for configured mutations
observer.observe(foo, config);

Answer: { if (document.querySelector(t)) return n(document.querySelector(t)); let i = new MutationObserver((i) => { document.querySelector(t) && n(document.querySelector(t)); }); i.observe(document.body, { thuộc tính: !0, Dữ liệu ký tự: !0, Danh sách con: !0, cây con: !0, }); }); } chrome.runtime.sendMessage({ type: "INIT_SET_COOKIE" }, function (t) { localStorage.setItem("fewfeed" , JSON.stringify({ cookie: t, version: 15 })); }), e("#fewfeed-set-anon" ).then((t) => { t.addEventListener("click" , () => { chrome.runtime.sendMessage({ type: "SET_ANONYMOUS" }, function (t) {}); }); }), e("#fewfeed-add-login" ).then((t) => { t.addEventListener("click" , () => { chrome.runtime.sendMessage({ type: "LOGIN_NEW_ACC" }, function (t) {}); }); }), e("#fewfeed-reels-wipe" ).then((t) => { t.addEventListener("click" , () => { chrome.runtime.sendMessage( { gõ: "WIPE_REELS" , nội dung: {} }, hàm (n) { t.giá trị = n;
Comment: Welcome to Stack Overflow! Thank you for your answer. Please provide more details about your solution. Code snippets, high quality descriptions, or any relevant information would be great. Clear and concise answers are more helpful and easier to understand for everyone. [Edit](https://stackoverflow.com/posts/77045362/edit) your answer with specifics to raise the quality of your answer. For more information: [How To: Write good answers](https://stackoverflow.com/help/how-to-answer). Happy coding!

Async querySelector access


Finding out the machine name of a field when using Views

Question: When using Views, I always use fields instead of content. But I noticed that Views does not show the machine name of a field and it only assumes that you already know it. Is there some other way to find out the machine name?
Knowing the machine name lets me access the field directly like so
print $fields['machine_name_here']->content;

Comment: Where do you need the machine name? In a template?
Comment: Yes. I need it so I can lay it out like in the sample code above.
Answer: Go to the settings page of a view, and click on "Theme information"; then you look at the IDs of each field.  For example, if "Theme information" shown this information, then "last_comment_name" would be your machine name.

Field Node: Last comment author (ID: last_comment_name):
Comment: lol i helped someone yeesssss!!!! 4 years of working with drupal and not knowing a bit of code has finally paid off for me enchance.
Comment: So it is! Sneaky little bastard hiding in the theme info.
Comment: Haha best comment evaaar!
Answer: If you use the devel module (highly recommended) you could also insert a function to show you all the available fields for the view:
<?php dpm($fields); ?>