text:
Q: Android ExpandableListView with buttons not working I have implemented expandable list view in my application.in my xml,i have some buttons in below of the expandable list view.so when i run my application expandable list view working fine,but my buttons below that list are not working.nothing happening when i click on my buttons,those buttons are not related to expand list view. i set all child views of list to focusable false also.but my button clicks not working..any one help me please?
here is my code,

<include
    android:id="@+id/headerID"
    layout="@layout/ds_header" />

<include layout="@layout/postadeal_menufooter" />

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/headerID" >

    <ExpandableListView
        android:id="@+id/postadeal_ExpandListID"
        android:layout_width="match_parent"
        android:layout_height="500dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true" >
    </ExpandableListView>
</LinearLayout>

Here "postadeal_menufooter" layout contains my buttons,which is below my expandable list view

A: How are you setting up your xml layout? Do you have them in a RelativeLayout? Make sure that your ExpandableListview is not "on top" of your buttons, otherwise your clicks would be intercepted before it has the chance to propagate to the associated buttons. Also, if you overrode onTouchListeners, check to not intercept clicks that are meant for the buttons. Without any code from you it's rather hard to go further into specifics. Hope this helps.
<include
    android:id="@+id/headerID"
    layout="@layout/ds_header" />

<LinearLayout
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:layout_below="@+id/headerID" >

    <ExpandableListView
        android:id="@+id/postadeal_ExpandListID"
        android:layout_width="match_parent"
        android:layout_height="500dp"
        android:layout_alignParentLeft="true"
        android:layout_centerVertical="true" >
    </ExpandableListView>
</LinearLayout>

<include layout="@layout/postadeal_menufooter" />

A: Add your footer after the listview.


text:
Q: is there any way for partial payment with booking Drupal? I am using rooms Module and I need to implement a way user can pay some amount while booking and pending after the trip/booking completed or user going for checkout . So I try different ways but nothing get fit to the requirement . Is there any way in drupal 7 rooms module we can implement the first some percentage and then pending payment after the trip over.
Please give your suggestions.
Thanks

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using System.Threading.Tasks.Parallel create new thread in the thread pool? Maybe I did not understand it right ... all the Parallel class issue   :(
But from what I am reading now, I understand that when I use the Parallel I actually mobilize all the threads that exists in the threadPool for some task/mission.
For example:
  var arrayStrings = new string[1000];
  Parallel.ForEach<string>(arrayStrings, someString =>
  {
       DoSomething(someString);
  });

So the Parallel.ForEach in this case is mobilizing all the threads that exists in the threadPool for the 'DoSomething' task/mission.
But does the call Parallel.ForEach will create any new thread at all?
Its clear that there will be no 1000 new threads. But lets assume that there are 1000 new threads, some case that the threadPool release all the thread that it hold so, in this case ... the Parallel.ForEach will create any new thread?

A: Short answer: Parallel.ForEach() does not "mobilize all the threads". And any operation that schedules some work on the ThreadPool (which Parallel.ForEach() does) can cause creation of new thread in the pool.
Long answer: To understand this properly, you need to know how three levels of abstraction work: Parallel.ForEach(), TaskScheduler and ThreadPool:

*

*Parallel.ForEach() (and Parallel.For()) schedule their work on a TaskScheduler. If you don't specify a scheduler explicitly, the current one will be used.
Parallel.ForEach() splits the work between several Tasks. Each Task will process a part of the input sequence, and when it's done, it will request another part if one is available, and so on.
How many Tasks will Parallel.ForEach() create? As many as the TaskScheduler will let it run. The way this is done is that each Task first enqueues a copy of itself when it starts executing (unless doing so would violate MaxDegreeOfParallelism, if you set it). This way, the actual concurrency level is up to the TaskScheduler.
Also, the first Task will actually execute on the current thread, if the TaskScheduler supports it (this is done using RunSynchronously()).

*The default TaskScheduler simply enqueues each Task to the ThreadPool queue. (Actually, it's more complicated if you start a Task from another Task, but that's not relevant here.) Other TaskSchedulers can do completely different things and some of them (like TaskScheduler.FromCurrentSynchronizationContext()) are completely unsuitable for use with Parallel.ForEach().

*The ThreadPool uses quite a complex algorithm to decide exactly how many threads should be running at any given time. But the most important thing here is that scheduling new work item can cause the creating of a new thread (although not necessarily immediately). And because with Parallel.ForEach(), there is always some item queued to be executed, it's completely up to the internal algorithm of ThreadPool to decide the number of threads.
Put together, it's pretty much impossible to decide how many threads will be used by a Parallel.ForEach(), because it depends on many variables. Both extremes are possible: that the loop will run completely synchronously on the current thread and that each item will be run on its own, newly created thread.
But generally, is should be close to optimal efficiency and you probably don't have to worry about all those details.

A: Parallel.Foreach does not create new threads, nor does it "mobilize all the threads". It uses a limited number of threads from the threadpool and submits tasks to them for parallel execution. In the current implementation the default is to use one thread per core.

A: I think you have this the wrong way round.
From PATTERNS OF PARALLEL PROGRAMMING you'll see that Parallel.ForEach is just really syntactic sugar.
The Parallel.ForEach is largely boiled down to something like this,
for (int p = 0; p < arrayStrings.Count(); p++)
{
    ThreadPool.QueueUserWorkItem(DoSomething(arrayStrings[p]);
}

The ThreadPool takes care of the scheduling.  There are some excellent articles around how the ThreadPool's scheduler behaves to some degree if you're interested, but that's nothing to do with TPL.

A: Parallel does not deal with threads at all - it schedules TASKS to the task framework. THat then has a scheduler and the default scheduler goes to the threadpool. This one will try to find a goo number of threads (better in 4.5 than 4.0) and the Threadpool may slowly spin up new threads.
But that is not a functoin of parallel.foreach ;)

the Parallel.ForEach will create any new thread ???

It never will. As I said - it has 1000 foreach, then it queues 10.000 tasks, Point. THe Task factory scheduler will do what it is programmed to do ((you can replace it). Generally, default - yes, slowly new threads will spring up WITHIN REASON.


text:
Q: Add textfield to canvas HTML5 I am creating a browser game with JavaScript and I want for the user to type his nickname before the game starts.
How it is possible to add a textfield to the canvas? I tried with an overlay to the canvas. But I can not remove it with javascript.
Thank you in advande for your advices.

A: Ok guys I found a solution for my question.
I am using the createjs framework that offers me the possibility to create DOM Elemets and place them on the canvas.
So I have done it like this:
        var domElement = new createjs.DOMElement(document.getElementById('nickname'));
        domElement.x = 650;
        domElement.y = - domElement.height;
        this.stage.addChild(domElement);

My HTML code is this:

<form id="myForm" style="visibility: hidden">
    <input id="nickname" value="Your nickname!" size="10">
</form>

<canvas id="display" width="1280" height="800"></canvas>


text:
Q: How to change the default shell in iTerm? I'm having some difficulties in changing the value of $SHELL in OSX's iTerm app. iTerm is starting in /bin/zsh, but the value of $SHELL doesn't seem to change.
What I've done:

*

*Changed "command" as /bin/zsh in iTerm's configuration window.

*Executed chsh to change the shell to /bin/zsh.

*Confirmed iTerm is started in /bin/zsh
NOTE #1: In OSX's stock terminal app, "Terminal.app":
echo $SHELL
/bin/zsh

NOTE #2: In OSX's popular terminal app, "iTerm.app":
$ echo $SHELL
/bin/bash

$ echo $USER
$ melvkim

$ chsh -s /bin/zsh
Changing shell for melvkim.
Password for melvkim:
chsh: no changes made

A: I had a similar issue but I resolved it by executing the command chsh -s /bin/zsh in the terminal,then navigated to

Terminal -> Preferences -> General window

and changed the Shells open with: option to Default login shell while the command (complete path) set to /bin/zsh.This should solve your problem.

A: Look here for the excellent explanation and solution posted by @mklement0 [in relation to a bash upgrade problem.
I had a similar problem in doing the opposite on my system (OS X 10.10.1): making bash the default login shell again after I had installed oh-my-zsh, which made zsh the default, and then upgrading bash from 3.2.53 to 4.3.30 using Homebrew (why is Apple shipping Yosemite with an old bash version?).
I think the SHELL environment variable reflects but does not control the actual default login shell for the user.  For example, if, say, bash was your default and you open a new bash shell window from terminal then $ export SHELL="/bin/zsh"; echo "$SHELL" would show /bin/zsh but no actual change will occur because if you open a new shell window from terminal and do $ echo $0 then you would see -bash ($0 contains the name and path of the command that started the shell window, in this case bash, and the - next to it indicates that it is a login shell).
As @mklement0 pointed out the actual default login shell for the user is controlled by the UserShell property in the user's record in the system's internal database - this can be queried and updated using the command line utility dscl.  This information will passed to your terminal app when you open a shell window.
What chsh -s /bin/zsh does is change this UserShell property to set it to zsh - you can check this by doing dscl . -read /Users/$USER/ UserShell immediately afterwards, and you will see UserShell: /bin/zsh.  But the change is not effected in the current window, until you do something like exec su - $USER as suggested by @mklement0, or until you close and open a shell window.

A: The problem was the "iTerm" app's conflicting settings with the shell. To resolve, I've reset "login shell" command in iTerm preference window:

iTerm.app -> Preferences -> Profiles -> General -> Command -> Click on "Login shell"

Then, I executed chsh to modify it as /bin/zsh.
To reproduce the problem (having $SHELL set as /bin/bash/, even though the login shell is /bin/zsh), I just had to change "iTerm" setting back to "Command: /bin/zsh/".

A: The -s flag for chsh only attempts to change the shell, and probably fails due to Open Directory:  The usual UNIX system 'chsh' would modify the /etc/passwd entry.   However, I was able to run chsh with no arguments, which gave me an editor, and the following information:
# Changing user information for nevin.
# Use "passwd" to change the password.
##
# Open Directory: /Local/Default
##
Shell: /bin/tcsh
Full Name: Nevin Williams
Office Location:
Office Phone:
Home Phone:

I was able to edit the "Shell:" entry to /bin/zsh, and subsequent Terminal windows opened with a Z-shell prompt.

A: Try executing the command: chsh -s /bin/zsh from the default Mac terminal.

A: I had a similar issue.  The Terminal would open into bash.  csh -s /bin/zsh would fail with an error.  Examining the default shell in System Preferences->Users by control-clicking on my user showed /bin/zsh was set.  dscl showed /bin/zsh was set.  I tried resetting Terminal->Preferences to /bin/zsh.  That also failed.
Ultimately, it turned out there was a lockfile.  Going to ~/Library/Preferences, I deleted com.apple.Terminal.plist.lockfile and com.apple.Terminal.plist.  That fixed the problem.  On the next startup, zsh loaded correctly in the terminal.


text:
Q: Proving the exponential derivative with limited information Can you prove the derivative of $e^x$ given the definition of $e$, which is $\lim_{x\to\infty}\left(1+\dfrac{1}{x}\right)^x$ without using l'hospital's rule?
e.g. I got to the point where I got $\lim_{x\to0}e^x\left(\dfrac{e^c-1}{c}\right)$, but since our teacher doesn't allow us to use l'hospital's rule or fractional expansion, I'm completely stuck.

A: $$\lim_{h\to 0} {e^{x+h}-e^x \over h} = {e^x}\lim_{h\to 0} {e^h-1\over h}$$
Then, set $n = \frac{1}{e^h - 1}$. This means ${1\over n} = e^h - 1$ and thus ${1 \over n} + 1 = e^h$, so $h = \ln\left({1\over n}+1\right)$. It also means as $h \to 0$, $n \to \infty$ so you can rewrite:
$$\lim_{n \to \infty} {{1\over n} \over \ln\left({1\over n}+1\right)} = \lim_{n \to \infty} {1\over n\ln\left({1\over n}+1\right)} = \lim_{n \to \infty} {1\over \ln\left(\color{red}{\left({1\over n}+1\right)^{n}}\right)}$$
Notice that you have the given limit in the denominator:
$$\lim_{n \to \infty}\, \left({1\over n}+1\right)^{n} = e$$
Thus:
$$\lim_{n \to \infty} {1\over \ln\left({1\over n}+1\right)^{n}} = {1\over \ln(e)} = 1$$
Bringing it all together with our original limit:
$$\lim_{h\to 0} {e^h-1\over h} = 1$$
$${e^x}\lim_{h\to 0} {e^h-1\over h} = 1 \cdot e^x = e^x$$


text:
Q: Having trouble installing archived packages for R 3.6.0 I can't seem to find a work around to install old packages archived.
I am currently using this
install.packages("https://cran.r-
project.org/src/contrib/Archive/RGtk2Extras/RGtk2Extras_0.6.1.tar.gz",
                 repos=NULL, method="libcurl")

However get a
Installing package into 'C:/Users/Daimen/Documents/R/win-library/3.6'
(as 'lib' is unspecified)
trying URL 'https://cran.r-
project.org/src/contrib/Archive/RGtk2Extras/RGtk2Extras_0.6.1.tar.gz'
Content length 88734 bytes (86 KB)
downloaded 86 KB

* installing *source* package 'RGtk2Extras' ...
** package 'RGtk2Extras' successfully unpacked and MD5 sums checked
** using staged installation
** libs
Warning in system(cmd) : 'make' not found
ERROR: compilation failed for package 'RGtk2Extras'
* removing 'C:/Users/Daimen/Documents/R/win-library/3.6/RGtk2Extras'
Warning message:
In install.packages("https://cran.r-
project.org/src/contrib/Archive/RGtk2Extras/RGtk2Extras_0.6.1.tar.gz",  :
installation of package
In install.packages("https://cran.r-
project.org/src/contrib/Archive/RGtk2Extras/RGtk2Extras_0.6.1.tar.gz",  :
installation of package
'C:/Users/Daimen/AppData/Local/Temp/RtmpMXJ3Pi/downloaded_packages
/RGtk2Extras_0.6.1.tar.gz' had non-zero exit status

I've tried to install this by means of downloading and importing it locally.. Still same error. I understand that this package is not available for this particular version of R however; is there a work around for this?


text:
Q: Deadlock in the semaphore function Question 1:
I was reading into Hard-core Multi-threading in Java and did bump up into the semaphore example below.
package com.dswgroup.conferences.borcon.threading;

public class ResourceGovernor {
    private int count;
    private int max;

    public ResourceGovernor(int max) {
        count = 0;
        this.max = max;
    }

    public synchronized void getResource(int numberof) {
        while (true) {
            if ((count + numberof) <= max) {
                count += numberof;
                break;
            }
            try {
                wait();
            } catch (Exception ignored) {}
        }
    }

    public synchronized void freeResource(int numberof) {
        count -= numberof;
        notifyAll();
    }
}

I feel this can lead to deadlock in the below scenario :
All resources are being used and a new thread asks for resources that are not available.
Since it waits inside the synchronized function, the other threads that are using the resources are not able to free the resources as the freeResource function is also synchronized and that they can't enter the function as the waiting thread has taken the object level lock of ResourceGovernor
There is another issue that one has not validated if a thread is trying to release more no. of resources than it acquired. But this issue is secondary and can be easily fixed by having the synchronized map of thread name and resource count.
But can i safely say that i diagnosed the 1st problem correctly. (Need to doublecheck since its published for a long time on embarcadero.com)
Question 2:
Can i safely say that a semaphore with only 1 resource has the same behaviour as a mutex lock?

A:
All resources are being used and a new thread asks for resources that are not available. Since it waits inside the synchronized function, the other threads that are using the resources are not able to free the resources as the freeResource function is also synchronized and that they can't enter the function as the waiting thread has taken the object level lock of ResourceGovernor

You've missed the fact that calling wait() relinquishes the monitor, so other synchronized code is able to execute. From the docs for wait():

The current thread must own this object's monitor. The thread releases ownership of this monitor and waits until another thread notifies threads waiting on this object's monitor to wake up either through a call to the notify method or the notifyAll method. The thread then waits until it can re-obtain ownership of the monitor and resumes execution.

For your second question:

Can I safely say that a semaphore with only 1 resource has the same behaviour as a mutex lock?

I suspect so, although the implementation you've shown doesn't actually stop you from calling freeResource several times. It's a slightly odd implementation in that I normally see semaphores counting the number of resources remaining rather than the number of resources taken - although they're equivalent, of course.

A: Question 2 : Yes it is similar to mutex. But although mutexes and semaphores have similarities in their implementation, they should always be used differently.  Nice Explanation Here


text:
Q: Constructive Proof of Kronecker-Weber? This question is motivated by my attempt at solving Proving $2 ( \cos \frac{4\pi}{19} + \cos \frac{6\pi}{19}+\cos \frac{10\pi}{19} )$ is a root of$ \sqrt{ 4+ \sqrt{ 4 + \sqrt{ 4-x}}}=x$
Consider numbers expressible as exponential sums $$\sum_k a_k \exp(2 i \pi \theta_k),$$ with $a_k$,$\theta_k$ a finite list of rationals.
These numbers are algebraic and satisfy some polynomial whose Galois group is abelian. The Kronecker-Weber theorem says the converse also holds.
Given an abelian polynomial (especially quadratic or cubic), how can we solve it in terms of one of these sums?
Basically I am looking for a proof of the Kronecker-Weber theorem that is constructive enough that I can compute with it.

A: $\def\QQ{\mathbb{Q}}\def\ZZ{\mathbb{Z}}\def\Gal{\mathrm{Gal}}\def\char{\mathrm{char}}$I want to record here what can be done reasonably easily following the approach of my 2011 answer. I have a plan for a much larger blog post, but it is an ambitious one so it may be several months until I get to write it. The aim of this answer is to provide a concrete proof of the following:
Suppose that $K/\QQ$ is Galois with Galois group $\ZZ/p$, where $p$ is a regular prime. Then $K$ is contained in a cyclotomic field.
Making $p$ irregular seems to force more advanced methods, either involving ramification groups or the Stickelberger theorem. Working with prime powers rather than primes seems to only require more care (especially $2^t$), not more high power tools, but it is a lot of work.
The case $p=2$ was done in the other answer, so I assume $p$ odd.
Let $\zeta_p$ be a primitive $p$-th root of unity. We have $\mathrm{Gal}(\QQ(\zeta_p)/\QQ) \cong (\ZZ/p)^{\ast}$. Explicitly, for $a \in (\ZZ/p)^{\ast}$, let $\sigma_a$ be the element of $\mathrm{Gal}(\QQ(\zeta_p)/\QQ)$ with $\sigma_a(\zeta_p) = \zeta_p^a$.
Basic computations
Let $\beta \in \QQ(\zeta_p)$. We would like to know whether or not $\QQ(\zeta_p,\beta^{1/p})$ is Galois and abelian over $\QQ$.
Claim 1 $\QQ(\zeta_p,\beta^{1/p})$ is Galois and abelian over $\QQ$ if and only if, for all $a \in (\ZZ/p)^{\ast}$, we have
$$\sigma_a(\beta) = \beta^a f_a^p \quad (\ast)$$
for some $f_a \in \QQ(\zeta_p)$.
Proof: Suppose that $\QQ(\zeta_p,\beta^{1/p})$ is Galois and abelian over $\QQ$. Fix $a$ in $(\ZZ/p)^{\ast}$. Lift $\sigma_a$ to some automorphism $\sigma \in \Gal(\QQ(\zeta_p, \zeta^{1/p})/\QQ)$ and let $\tau \in \Gal(\QQ(\zeta_p, \zeta^{1/p})/\QQ(\zeta_p))$ be the automorphism $\tau(\beta^{1/p}) = \zeta_p \beta^{1/p}$.
Since $\sigma$ and $\tau$ commute, we compute
$$\tau(\sigma(\beta^{1/p}))= \sigma(\tau(\beta^{1/p})) = \sigma(\zeta_p \beta^{1/p}) = \zeta_p^a \sigma(\beta^{1/p}).$$
We also have
$$\tau(\beta^{a/p}) = \zeta_p^a \beta^{a/p}.$$
Therefore, $\sigma(\beta^{1/p})/\beta^{a/p}$ is fixed by $\tau$. Since $\tau$ generates $\Gal(\QQ(\zeta_p, \beta^{1/p})/\QQ(\zeta_p))$, we deduce that $\sigma(\beta^{1/p})/\beta^{a/p} = f_a$ for some $f_a \in \QQ(\zeta_p)$, and thus $\sigma_a(\beta) = \beta^a f_a^p$.
Conversely, suppose that $(\ast)$ holds. We can reverse the argument to show that $\QQ(\zeta_p, \beta^{1/p})/\QQ(\zeta_p)$ is Galois and
$$1 \to \Gal(\QQ(\zeta_p, \beta^{1/p})/\QQ(\zeta_p)) \to \Gal(\QQ(\zeta_p, \beta^{1/p})/\QQ) \to \Gal(\QQ(\zeta_p)/\QQ) \to 1$$
is a central extension. But $\Gal(\QQ(\zeta_p)/\QQ)$ is cyclic, so every central extension of it is abelian. $\square$
Let $\beta$ as above and let the ideal $(\beta)$ factor into primes as $(\beta) = \prod \pi^{v_{\pi}(\beta)}$. Note that, if $q$ is a prime of $\ZZ$ which is $1 \bmod p$, then $q$ splits completely in $\QQ(\zeta_p)$. Fix for convenience a particular $\pi_q$ lying over $q$ for each such $q$. For any prime $\pi$ of $\QQ(\zeta_p)$, let $\mathrm{char}(\pi)$ be the characteristic of the residue field.
Claim 2  With the above notation, there are constants $c_q$, one for each $q \equiv 1 \bmod p$ such that
$$v_{\pi}(\beta) \equiv \begin{cases} 0 \bmod p & \char(\pi) \not \equiv 1 \bmod p \\ c_q/a & \pi = \sigma_a(\pi_q),\ q \equiv 1 \bmod p \\ \end{cases}.$$
Proof If $\char(p) \not \equiv 1 \bmod p$, then there is some non-identity $a$ with $\sigma_a(\pi) = \pi$. (Here we use $p \neq 2$. Otherwise, $p=2$ and $\pi = (2)$ is a counterexample.) Then $(\ast)$ implies that $a v_{\pi}(\beta) \equiv v_{\pi}(\beta) \bmod p$, so $v_{\pi}(\beta) \equiv 0 \bmod p$.
If $\char(\pi) = q \equiv 1 \bmod p$, then $(\ast)$ implies that $v_{\pi_q}(\sigma_a^{-1}(\beta)) \equiv a^{-1} v_{\pi}(\beta) \bmod p$, so  $v_{\sigma_a(\pi_q)}(\beta) \equiv a^{-1} v_{\pi}(\beta) \bmod p$ and the result follows. $\square$
Before proceeding to the proof, we need a supply of $\gamma$'s for which $\QQ(\gamma^{1/p},\zeta_p)$ is cyclotomic.
If $q$ is a prime which is $1 \bmod p$, then $\Gal(\QQ(\zeta_q, \zeta_p)/\QQ) = (\ZZ/q)^{\ast} \times (\ZZ/p)^{\times}$ surjects onto $(\ZZ/p) \times (\ZZ/p)^{\times}$, so there is some field tower $K \supset \QQ(\zeta_p) \supset \QQ$ with $\Gal(K/\QQ) \cong (\ZZ/p) \times (\ZZ/p)^{\times}$. By Kummer theory, we must have $K = \QQ(\zeta_p, \gamma_q^{1/p})$ for some $\gamma_q$.
From the previous computations, we know that $v_{\pi}(\gamma_q) \equiv 0 \bmod p$ if $\char(\pi) \not \equiv 1 \bmod p$. Considering ramification, or computing with Gauss sums, we also have $v_{\pi}(\gamma_q) \equiv 0 \bmod p$ if $\char(\pi) = q' \neq q$ with $q' \equiv 1 \bmod p$, and there is some $b \in (\ZZ/p)^{\ast}$ such that $v_{\sigma_a(\pi_q)}(\gamma_q) \equiv b/a \bmod p$. We may (and do) replace $\gamma_q$ by $\gamma_q^{1/b \bmod p}$ so that $v_{\sigma_a(\pi_q)}(\gamma_q) \equiv 1/a \bmod p$. (Stickelberger's relation gives an explicit choice of $\gamma_q$ with this normalization.)
The proof
Now, suppose that $K/\QQ$ is Galois with Galois group $\ZZ/p$. Then, by Kummer theory, $K(\zeta_p) = \QQ(\beta^{1/p}, \zeta_p)$ for some $\beta$, and $\beta$ must obey condition $(\ast)$.
We will show that $\beta$ is in the group generated by $(\QQ(\zeta_p)^{\ast})^p$, by the $\gamma_q$ and by $\zeta_p$.
We first consider the factorization of $(\beta)$ into prime ideals: $(\beta) = \prod \pi^{v_{\pi}}$, which is described by Claim 2 above. We replace $\beta$ by $\beta \prod \gamma_q^{-c_q}$.
After making this replacement, we have $v_{\pi}(\beta) \equiv 0 \bmod p$ for all $\pi$.
Thus, we can assume that $(\beta)=I^p$ for some ideal $I$. Since $p$ is regular, we deduce that $(\beta) = (f^p)$ for some $f \in \QQ(\zeta_p)$. Replacing $\beta$ by $\beta f^{-p}$ does not change the extension, and we may now assume that $\beta$ is a unit.
We abbreviate $\sigma_{-1}(x)$ by $\bar{x}$, since in any complex embedding of $\QQ(\zeta_p)$, the element $\sigma_{-1}$ acts by complex conjugation. Taking $a=-1$ in $(\ast)$, we have
$$\beta \bar{\beta} = \theta^p$$
for some $\theta$ and, since $\beta$ is a unit, so is $\theta$. Hitting both sides of the equation with complex conjugation, we have $\theta^p = \bar{\theta}^p$.
Now, replace $\beta$ by
$$\beta' := \beta\cdot (\theta^{(p-1)/2}/\beta)^p.$$
(This is the second time we have used that $p \neq 2$, to make $(p-1)/2$ an integer.) Note that $\beta'$ is likewise a unit. We have
$$\beta' \bar{\beta'} = \frac{\beta \bar{\beta} \theta^{p(p-1)/2} \bar{\theta}^{p (p-1)/2}}{\beta^p \bar{\beta}^p} = \frac{\theta^p \theta^{p(p-1)/2} \theta^{p(p-1)/2}}{\theta^{p^2}} = 1.$$
We see that $\beta'$ is a unit of $\QQ(\zeta_p)$ such that $|\beta'|=1$ in every complex embedding. So, by a result of Kronecker, $\beta'$ is a root of unity.  We see that $\QQ(\beta'^{1/p}, \zeta_p)$ is cyclotomic, as promised.

A: $\def\QQ{\mathbb{Q}}$ As user8268 says, for quadratics, Gauss sums are enough. Let me make sure you understand that comment: Let $K = \QQ(\sqrt{D})$. For simplicity, I'll do the case the $D$ is a prime $p$ which is $1 \mod 4$ and leave you to make the necessary adjustments in the general case. Let $\zeta$ be a primitive $p$-th root of unity and let $\left( \frac{k}{p} \right)$ be the Legendre symbol. Set $g = \sum_{k=0}^{p-1} \left( \frac{k}{p} \right) \zeta^k$. Then $g^2 = p$. So this shows that $K$ is a subfield of $\mathbb{Q}(\zeta)$.
If $D$ is not prime, or not $1 \mod 4$, you can either multiply together formulas for its prime factors, or you can use the Kronecker symbol which will do it all for you in one swoop.

Now, let's look at cubics. Let the roots of your cubic be $\theta_1$, $\theta_2$, $\theta_3$, with the (abelian) Galois group acting cyclically. Let $K$ be  $\mathbb{Q}(\theta_1)$; because of the presumed Galois structure, $\theta_2$ and $\theta_3$ are also in $K$. Let $L = K(\omega)$, where $\omega$ is a primitive third root of unity.
Then $L/\QQ(\omega)$ is a Kummer extension: $L = \QQ(\omega)(\beta^{1/3})$. There is an almost explicit formula for $\beta$: We have $\beta = (\theta_1 + \omega \theta_2 + \omega^2 \theta_3)^3$. (Exercise: Check that $\beta$ is fixed by cyclically permuting the $\theta$'s, and thus lies in $\QQ(\omega)$.) Note that, if you expand this out, you get an expression for $\beta$ as various cyclically symmetric polynomials in the $\theta$'s times powers of $\omega$.
The ring of cyclically symmetric polynomials in three variables is generated by the elementary symmetric functions, which are the coefficients of the minimal polynomial of $\theta_1$, and by the discriminant $(\theta_1-\theta_2)(\theta_2-\theta_3)(\theta_3-\theta_1)$ so, if you know these quantities, you can compute $\beta$.
I say "almost" because this quantity could be $0$, if you are unlucky. In that case, replace $\theta_1$ by a different primitive element and try again. From now on, I'll assume you have found a $\beta$ that works. Moreover, we can multiply $\beta$ by cubes of elements in $\mathbb{Q}(\omega)$ without changing the fact that $L = \QQ(\omega)(\beta^{1/3})$. We use this freedom to assume that every prime divides $\beta$ with multiplicity between $0$ and $2$. (Recall that $\mathbb{Z}[\omega]$ is a UFD.) So
$$\beta = \epsilon \sqrt{-3}^k \prod_{p_i \equiv 1 \mod 3} \pi_i^{a_i} \overline{\pi_i}^{\overline{a}_i} \prod_{q_i \equiv 2 \mod 3} q_i^{b_i}$$
where $\epsilon$ is a unit, $p_i$ and $q_i$ are primes of $\mathbb{Q}$, the prime factorization of $p_i$ in $\mathbb{Z}[\omega]$ is $\pi_i \overline{\pi_i}$ and we have $0 \leq k, \ a_i,\  \overline{a_i}, \ b_i \leq 3$.
Let bar denote the symmetry which exchanges $\omega$ and $\omega^{-1}$, which preserving the $\theta_i$'s. (This is consisting with the notation $(\pi, \overline{\pi})$ introduced above.)  Let $N = \beta \overline{\beta}$. Observe that $N = M^3$, where $M = \sum \theta_i^2 - \sum_{i<j} \theta_i \theta_j$. So $M$ is rational, and you could extract $M$ directly from the minimial polynomial of $\theta$.
So we see that $\beta \overline{\beta} = M^3$ and so
$$(3)^{2k} \prod_{p_i \equiv 1 \mod 3} p_i^{a_i + \overline{a_i}} \prod_{q_i \equiv 2 \mod 3} q_i^{2 b_i}$$
is a cube. Together with the fact that the exponents are supposed to be between $0$ and $2$, we see that $k$ and $b_i$ are zero and that $(a_i, \overline{a_i})$ are $(0,0)$, $(1,2)$ or $(2,1)$. So $\beta$ must be of the form
$$\epsilon \prod \pi_i \overline{\pi_i}^2$$
where $\epsilon$ is a unit and we may have switched the names of $\pi_i$ and $\overline{\pi}_i$ in some places. We can extract the primes $p_i$ occurring above by factoring $M$; that's a quite reasonable computation. To figure out exactly which unit we get and to figure out which of the two factors of $p_i$ gets squared, I think you honestly need to work in the extension fields. Theoretically, though, everything I have said is constructive.
This is a good place to pause.

Our temporary goal is to show that $\beta^{1/3}$ is in a cyclotomic extension. (Just like before we wanted to show that $\sqrt{D}$ was in a cyclotomic extension, but this time we will have to do more work after that.) I will restrict to the case that $\beta = \pi \overline{\pi}^2$, just like I restricted myself before to the case that $D$ was a prime which was $1$ modulo $4$. I'll also want to assume that $\pi \equiv 1 \mod 3$; this tells you which of the six generators of the ideal $(\pi)$ I should focus on. (Analogously, I used the prime $p$, not $-p$, back in the quadratic case.) Removing these restrictions is further work, but it doesn't require too much new insight.
Let $\zeta$ be a $p$-th root of unity. Let $\chi: (\mathbb{Z}/p)^* \to \{ 1, \omega, \omega^2 \}$ be a multiplicative character, and extend it to $\mathbb{Z}/p$ by $\chi(0)=0$. Define
$$\gamma = \sum_{k=0}^{p-1} \chi(k) \zeta^k.$$
It is not too hard to show that $\gamma^3$ is fixed by $\mathrm{Gal}(\QQ(\omega, \zeta)/\QQ(\zeta)$, so $\gamma$ is in $\QQ(\omega)$.
Stickelberger's relation states that the ideal $(\gamma^3)$ is equal to the ideal $(\pi \overline{\pi}^2)$, after possibly switching $\pi$ and $\overline{\pi}$. I believe the right statement, if I choose $\pi$ to be $1 \mod 3$, should be that $\gamma^3 = \pi \overline{\pi}^2$, again up to the above switching, but I can't find a reference for this so be forewarned.
Unfortunately, the Wikipedia article on Stickelberger's theorem is very abstract. Try these notes from my colleague Kartik for a more down to earth presentation. Note that his $(m, l)$ are my $(3,p)$.
So, up to getting the details right here, $\gamma^3 = \pi \overline{\pi}^2 = \beta$. So $\beta^{1/3}$ is in $\QQ(\omega, \zeta)$. This is the hard part, now we have to clean up the details.

For simplicity, lets assume that $\beta = (\theta_1 + \omega \theta_2 + \omega^2 \theta_3)$ on the nose, without us having had to multiply or divide by any cubes. So
$$\gamma = \beta^{1/3} = \theta_1+ \omega \theta_2 + \omega^2 \theta_3.$$

Let bar act on $\QQ(\omega, \zeta)$ by switching $\omega$ and $\omega^{-1}$, while fixing $\zeta$. Then we have:
$$\overline{\gamma} = \theta_1 + \omega^2 \theta_2 + \omega \theta_3.$$
And, of course,
$$\mathrm{Tr}(\theta_1) = \theta_1 + \theta_2 + \theta_3,$$
and this is a rational number which can be computed from the minimial polynomial of $\theta_1$.
Solve these linear equations, and you get an expression for $\theta_1$ as an explicit element of $\QQ(\omega, \zeta)$, a cyclotomic field.

In summary, you need to perform a bunch of operations with symmetric polynomials to find out what $\beta$ is; you need to do factorization in $\mathbb{Z}[\omega]$ in order to find the $\pi_i$ (although you can turn it into a smaller factorization problem in $\mathbb{Z}$ by looking at $M$ instead), you need to write down a bunch of Gauss sums and you need to do some final linear algebra. Stickelberger's relation appears to save you at a miracle point.
This same outline will get you through $\mathbb{Z}/4$ extensions, and is a good exercise to make sure you understand the above. Once you get past there, life becomes much harder. There are two problems (1) you may not have unique factorization but, before that (2) the unit groups of your cyclotomic fields become infinite! I could leave dealing with units as an exercise as long as it was just a finite list to check off, but once the unit group gets infinite, the issue seems very hard to me. I tried to come up with a "brute force" proof of Kronecker-Weber a few years ago, and that is where I got stuck. I'd be curious to hear any ideas for how to get past this.


text:
Q: Centering an element within a footer? I'm fairly knew to this. A recent update has thrown my 'special recent posts pro' widget out of alignment in my footer. I've moved the item to an 'above footer' container. I was hoping to make it fixed width, say 1000px, and center it within the container.
www.richclarkimages.co.uk
Any ideas on how to achieve this?

A: There are several issues with the markup on your site. I see you are using WordPress, so I am guessing that you did not write all the code yourself.
As far as I can tell, the element with the class .srp-widget.container has its width set to 1000px, so to center that in the parent container, only a little CSS is required.
.srp-widget.container {
    margin-left: auto;
    margin-right: auto;
}


text:
Q: Excel VBA - Using Array to move through worksheets and then copy paste nth row I am a little new to VBA, I just started using it in excel recently and have reached a road block.
I am creating a crosswalk in order to upload my data to a business intelligence application. Unfortunately I do not have a connection to the database to run my reports so I have to do this with excel. The issue that I am running into is that there is a bug in our application where after the 1000th row in an excel document it will skip every 1000th line. Our development team is aware of this but there is no ETA to resolve the issue. As a work around I am trying to use VBA to copy the 1000th line (starting with 2000) to the end of the same sheet.
I currently have code wrote for this that works on a single worksheet, but I have several pages that have over 1000 rows, so I am trying to feed the names of those sheets into an array and cycle through each one and do the copy/pasting.
My working code for 1 worksheet:
Sub Test()

Dim WB As Workbook
Dim WS As Worksheet
Dim i As Integer
Dim x As Integer
Dim r As Range

Set WB = Workbooks("macrotesting.xlsm")
Set WS = Worksheets("Usage")

Set r = WS.UsedRange
k = r.Rows.Count
x = 2000
i = 2

Do While x < k

WS.Range(("A" & x) & (":L" & x)).Copy
WS.Rows.End(xlDown).Offset(1, 0).PasteSpecial xlPasteValues

i = i + 1
x = 1000 * i

Loop

End Sub

I was able to find some help with this here but it is failing. Code with the Array:
Sub Test()

Dim wsArray As Variant
Dim wsArrayCrnt As Variant
Dim i As Integer
Dim x As Integer
Dim r As Range

wsArray = Array("Usage", "Use")

For Each wsArrayCrnt In wsArray
With Worksheets(wsArrayCrnt)

    r = .UsedRange
    k = r.Rows.Count
    x = 2000
    i = 2

    Do While x < k

    .Range(("A" & x) & (":L" & x)).Copy
    .End(xlDown).Offset(1, 0).PasteSpecial xlPasteValues

    i = i + 1
    x = 1000 * i

    Loop
End With
Next wsArrayCrnt

End Sub

It seems to be failing at the
 k = r.Rows.Count

Though I am not sure if it will finish after this.
I have also tried to dimension the workbook and add it to the with statement and all the variables after.

A: Instead of manually typing in which sheets you want could you not just cycle through all the work sheets in the workbook?
Sub test()
Dim i As Integer
Dim x As Integer
Dim r As Range

For Each wsheet In ActiveWorkbook.worksheets

    Set r = wsheet.UsedRange
    k = r.Rows.Count
    x = 2000
    i = 2

    Do While x < k
        wsheet.Range(("A" & x) & (":L" & x)).Copy
        wsheet.Rows.End(xlDown).Offset(1, 0).PasteSpecial xlPasteValues

        i = i + 1
        x = 1000 * i
    Loop

Next wsheet

End Sub

This will cycle through each worksheet in the current workbook you are running the macro from and copy every 1000th row to the end of worksheet.
(Any sheet with less than 2000 rows will skip over the do while loop and be ignored)

A: you must type
Set r = .UsedRange

Since UsedRange is an object (namely a Range object)
You may also want to use a more compact code like follows:
Sub Test()

Dim wsArrayCrnt As Variant
Dim x As Long

For Each wsArrayCrnt In Array("Usage", "Use")
    With Worksheets(wsArrayCrnt)
        x = 2000
        Do While x < .UsedRange.Rows.Count
           .Range(("A" & x) & (":L" & x)).Copy
           .End(xlDown).Offset(1, 0).PasteSpecial xlPasteValues
           x = x + 1000
       Loop
    End With
Next wsArrayCrnt

End Sub


text:
Q: Display datepicker instead of list in JQueryUI's autocomplete's pop-widget For the search functionality of my webapp, instead of multiple input fields I'm giving my users a single field to enter their query, and they can use special syntax to make their queries more specific. To ease the process of writing these queries, I'm using the JQueryUI's autocomplete widget. As the user type, I'm parsing their query, determine the context of what they are currently typing, and give them relevnat autocomplete. For example - if the user is using the syntax for filtering by client, I give them a list of all the clients(filtered by the partial client name they have already written ofcourse).
That part I implemented and it works great. Now, some of the fields I'm filtering by are date fields. There is sense in giving a suggestion list for these, but I do want to allow my users to enter those dates using JQueryUI's datepicker widget. I've considered using _renderMenu, but as far as I understand I need to use widget factory for this(which seems like a overkill), and I can't tell how to call the normal behavior for regular list completions if I override _renderMenu.
I've managed to work out a hacky solution - open the pop-widget with a blank array and use the open event to add the datepicker. This works, but I have to pass the instruction to create a datepicker instead of using the regular widget via JQuery's in-DOM data storage, which just feels hacky...
Is there any proper way to do what I want?
UPDATE(a bit off-topic)
Zee Tee wanted to know in the comments how exactly I determine when to regular autocomplete list and when to open datepicker, since I'm using a single field for both. Well, the text in a field is actually a query, which I parse on client-side and therefore have full access to it's abstract sytnax tree in my JavaScript code. I made the syntax very relaxed, so I can parse half-queries and still get valid ASTs. When I do an autocomplete, I take the part of the query before the caret and parse it. Then I down-right in the syntax tree until I find something I can autocomplete.
For example - lets say I have a query client=jack date<, and the caret is at the end. I parse it to something like:
and:
  - equals:
    - field: client
    - text: jack
  - less-than:
    - field: date
    - text:

I can't provide autocompletion for and, so I have to go down-right in the AST, to less-than. This is a pattern that I recognize as datepicker pattern, so I display a datepicker. If the caret was at the middle of the word "jack", I would get this AST:
- equals:
  - field: client
  - text: ja

Which I would recognize as a pattern for displaying the list of clients, filtered by "ja".
So - determining what to display is easy - the problem is how.


text:
Q: Java File copy - how to inherit permissions of destination directory When I copy a file from source folder to destination folder the permissions of the destination folder are not inherited by newly copied file.
is there a way in Java where file copy to destination would inherit permissions of destination folder?

A: In java7 -  You can do the following
Files.copy(source, target, StandardCopyOption.COPY_ATTRIBUTES)
I have not tested this code. Hope it helps!!

A: Using Files.Copy works fine and I tested this code when renameTo() or FileInput/OutputStream code didn't work.
Try without the StandardCopyOption and the permissions of the destination folder are automatically inherited like this:
Files.copy(source.toPath(), destination.toPath());
Hope it can help.


text:
Q: My ethernet is not been detected in Ubuntu 12.04 I'm very new to Ubuntu, all of a sudden my internet is not working in my Ubuntu machine.
But fortunately the internet is working in my Windows machine. The ethernet cable is not even gets detected in my Ubuntu machine.
As a new user to Ubuntu, this is really frustrating. Are there any ways to use internet in Ubuntu?
Edit:
Doing ifconfig eth0:
eth0      Link encap:Ethernet  HWaddr 6c:f0:49:c4:7f:2d
          UP BROADCAST MULTICAST  MTU:1500  Metric:1
          RX packets:0 errors:0 dropped:0 overruns:0 frame:0
          TX packets:0 errors:0 dropped:0 overruns:0 carrier:0
          collisions:0 txqueuelen:1000
          RX bytes:0 (0.0 B)  TX bytes:0 (0.0 B)
          Interrupt:42

Doing lspci , gives me :
00:00.0 Host bridge: Intel Corporation 4 Series Chipset DRAM Controller (rev 03)
00:02.0 VGA compatible controller: Intel Corporation 4 Series Chipset Integrated Graphics Controller (rev 03)
00:1b.0 Audio device: Intel Corporation N10/ICH 7 Family High Definition Audio Controller (rev 01)
00:1c.0 PCI bridge: Intel Corporation N10/ICH 7 Family PCI Express Port 1 (rev 01)
00:1c.1 PCI bridge: Intel Corporation N10/ICH 7 Family PCI Express Port 2 (rev 01)
00:1d.0 USB controller: Intel Corporation N10/ICH 7 Family USB UHCI Controller #1 (rev 01)
00:1d.1 USB controller: Intel Corporation N10/ICH 7 Family USB UHCI Controller #2 (rev 01)
00:1d.2 USB controller: Intel Corporation N10/ICH 7 Family USB UHCI Controller #3 (rev 01)
00:1d.3 USB controller: Intel Corporation N10/ICH 7 Family USB UHCI Controller #4 (rev 01)
00:1d.7 USB controller: Intel Corporation N10/ICH 7 Family USB2 EHCI Controller (rev 01)
00:1e.0 PCI bridge: Intel Corporation 82801 PCI Bridge (rev e1)
00:1f.0 ISA bridge: Intel Corporation 82801GB/GR (ICH7 Family) LPC Interface Bridge (rev 01)
00:1f.1 IDE interface: Intel Corporation 82801G (ICH7 Family) IDE Controller (rev 01)
00:1f.2 IDE interface: Intel Corporation N10/ICH7 Family SATA Controller [IDE mode] (rev 01)
00:1f.3 SMBus: Intel Corporation N10/ICH 7 Family SMBus Controller (rev 01)
02:00.0 Ethernet controller: Realtek Semiconductor Co., Ltd. RTL8111/8168B PCI Express Gigabit Ethernet controller (rev 02)

In my windows machine I have the config like this:

I'm new to Ubuntu, I need some help in setting up my internet connection!! Thanks in advance.

A: Yep... you need a driver. The best plan is to get the driver on your windows machine, then boot to linux and compile it. You can follow the steps found in this guide at the Ubuntu Forums:

*

*Download the driver and expand it into a new directory. cd to the
top directory in the expanded directory.

*sudo make clean modules

*sudo make install

*Verify that a new file named r8168.ko exists in the directory
/lib/modules/3.2.0-24-generic/kernel/drivers/net/ethernet/realtek/.

*blacklist r8169.

*Edit /etc/initramfs-tools/modules and add a line with "r8168" in it.

*sudo depmod -a

*sudo update-initramfs -v -u -k uname -r

*Reboot

A: Ok it seems that your network card is recognized, so it should be a problem with your network. Try those steps:
sudo dhclient eth0

Check if you have internet now (without closing the terminal window). If it works you should create a new Wired connection in Network Manager(with Method as "Authomatic (DHCP)").
If you still dont have internet you should inspect your Windows network configuration. Probably you have a fixed IP address that you can gather from there, and supply it to Network Manager.
Edit
Looking at your configuration it seems your network is configured using DHCP. So, go to Network Manager, delete any Wired network you could have there, and create a new one.

Then select DHCP in IPv4 tab:

After that try to connect manually through the newly created connection. If it still don't work try to select "Automatic (DHCP) addresses only" (step 3) and add the information "DNS servers" you got in the Windows screenshot.

A: This is as a bug in Ubuntu 12.0.4 (bug: #145382 | broken 70-persistent-net.rules)
The fix is:

*

*look into your settings what is your NIC MAC address and remember it > $MAC

*nano /etc/udev/rules.d/70-persistent-net.rules

*Look up for:

SUBSYSTEM=="net", DRIVERS=="?*", ATTRS{address}=="$MAC",
  NAME="eth5"

*Rename it as NAME='eth0'

*Make sure your /etc/network/interfaces is correct

*Reboot


text:
Q: Keycloak option Sync LDAP roles/groups to Keycloak missing I have successfully configured Active Directory as a user federation LDAP provider in Keycloak.
Users get synced and authentication is working with basic username + password.
I have configured ldap-group-mapper to READ_ONLY mode and LOAD_GROUPS_BY_MEMBER_ATTRIBUTE but no groups ever get added to Keycloak. I have no error in the server log.
Screenshot of the group mapper config.

In some tutorials I found there is a button for syncing roles/groups when setting up the mapper but this is not available in the latest version as it seems, can it be triggered manually in some other way? Searching for users and or groups does not seem to trigger the groups to appear in Keycloak.

A: I had the same problem. After searching for a long time, I found the action button in the top right corner (see Screenshot), which lets you synchronize users.
Hope this helps!
enter image description here

A: The feature has been removed from the REST API with Keycloak 19.
If you compare the API documentation

*

*Keycloak 18: https://www.keycloak.org/docs-api/18.0/rest-api/ you will find "Trigger sync of mapper data related to ldap mapper".

*Keycloak 19: https://www.keycloak.org/docs-api/19.0.1/rest-api/ there is not much to find for "user-storage" which was an essential part of the request path.


text:
Q: Can't run crontask in django project I have django problem and I have problem with run the .sh file on server but not on local machine.
My .sh file:
#!/bin/bash

source $HOME/.profile
cd /home/myproject/test
source venv/bin/activate
cd www
python manage.py make_import

I want to run this .sh file and run import with this line in crontab (Ubuntu):
10 8 * * * /home/myproject/test/www/crontab/test/make_import.sh

But this isn't working.
When I do this on my local computer via python manage.py make_import everything is fine.
Thanks for any hint.


text:
Q: Join Query in laravel to avoid report abused users I'm trying to create a join between two tables to avoid report abuse uses in user listing what I'm doing is given below:
What I have
I've 2 tables which are
users Table
id |  name  |
1  |  testA |
2  |  testB |
3  |  testC |
4  |  testD |
5  |  testE |

report_abuse Table
id | reported_by|  reported_to
1  | 1          |  2
2  | 1          |  3

now what i need is when I query I should get only 2 records 4 and 5
What I did
I create a query to fetch the above records which is :
DB::table('users as U')
->select('U.id','U.name')
->where('U.id', '!=', auth()->user()->id)
->leftJoin('report_abuse as RA', 'RA.reported_by', '=', 'U.id')
->where('RA.reported_by', '=', auth()->user()->id)
->where('RA.reported_to', '!=', 'U.id')
->orderBy('U.id', 'desc')
->paginate(10);

I'm doing something wrong here that's why I'm not getting proper results.
Can you guys please help me out, much appreciated.
Thanks

A: If i understand, you need the list of users exluding the one's he reported and himself.
here's a solution
$authId = auth()->user()->id;
DB::table('users as U')
    ->select('U.id','U.name')
    ->where('U.id', '!=', $authId)
    ->leftJoin('report_abuse as RA', function ($report) use ($authId){
        $report->on('reported_to', '=', 'U.id')
            ->where('reported_by', '=', $authId);
    })
    ->whereNull('reported_to')
    ->orderBy('U.id', 'desc')
    ->paginate(10);


text:
Q: how to solve connection error issue for ec2, elastic beanstalk php application I have recently started working with amazons cloud specifically the elastic beanstalk and RDS components.
I have setup my EC2 SERVER
I have setup my RDS INSTANCE
I have also setup my elastic beanstalk app, a single page that needs to query a my database please see below
<?php
$servername = $_SERVER['RDS_HOSTNAME'];
$username = $_SERVER['RDS_USERNAME'];
$password = $_SERVER['RDS_PASSWORD'];
$dbname = $_SERVER['RDS_DB_NAME'];

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$sql = "SELECT * FROM users";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        echo "Email: " . $row["Email"]. " - Name: " . $row["fname"]. " " . $row["lname"]. "<br>";
    }
} else {
    echo "0 results";
}
$conn->close();
?>

I have also been able to access my mysql database created on RDS and accessed it with work bench.
the problem I am having presently with my application hosted using beanstalk is when I try accessing my application I am getting
Connection failed: Connection timed out error
please I need help about getting this solved I am new to this whole amazon cloud thing, but its really exciting I must say.
Thanks


text:
Q: Element with fixed position hides by half on scroll from mobile I want to fix an element's position (.topsection) while scrolling down. Desktop works fine, but from mobile it hides by half.
Screenshot
My website
Note: An element with class .topsection-container needs as wrapper for changing background-color on scroll event in js.
HTML

        `//some code...`

CSS
.topsection-container {
  position: fixed;
  width: 100vw;
  left: 0;
  z-index: 3;
  transition: all .3s ease 0s;
}

.topsection {
  position: fixed;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 1.5rem 10% 0 10%;
  position: relative;
}

A: position: fixed works well in your code, the only issue is body scroll down in mobile screen that's why, half of .topsection-container scrolled up. body having extra scroll things which let's them scroll.
Add following CSS and try:
html, body {
    overflow: auto;
}


text:
Q: Can't get templates to work in Django I'm following this tutorial (http://lightbird.net/dbe/cal1.html) to build a calendar app, but I can't get the templates to work correctly.
I made a directory named cal in project/templates and copied base.html there. Then I extended the template cal/main.html with the following:
{% extends "cal/base.html" %}

<< Prev
Next >>

    {% for year, months in years %}

{{ year }}

        {% for month in months %}

                {% if month.entry %}{% endif %}
                {{ month.name }}
                {% if month.entry %}{% endif %}

            {% if month.n == 6 %}
{% endif %}
        {% endfor %}
    {% endfor %}

In my project/urls.py I have the following configuration:
from django.conf.urls import patterns, include, url

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^cal/', include('cal.urls')),
    url(r'^admin/', include(admin.site.urls)),
)

In cal/urls.py I have the following configuration:
from django.conf.urls import patterns, include, url
from cal.views import main

urlpatterns = patterns('cal.views',
    (r'^(\d+)/$', main),
    (r'', main),
)

I'm not sure where I went wrong. All that is showing up right now when I run the app is a blank screen with a "Home" button on the top left corner that takes me to the admin page. If anyone could point me in the right direction, it would be greatly appreciated!

A: In base.html you must have something like that:
{% block content %}{% endblock %}

And in main.html:
{% extends "cal/base.html" %}

{% block content %}
<< Prev
Next >>

{% for year, months in years %}

{{ year }}

    {% for month in months %}

            {% if month.entry %}{% endif %}
            {{ month.name }}
            {% if month.entry %}{% endif %}

        {% if month.n == 6 %}
{% endif %}
    {% endfor %}
{% endfor %}
{% endblock %}


text:
Q: How to create a multiple choice inquirer? I am creating a program (using Python) that allows users to automatically generate a TXT file with sentences randomly selected from three files (one for each level: A, B, C). The user can select one or more of these three files and the total number of sentences he needs. I tried to use inquirer:
Select the level:

*

*A

*B

*C

However, it allows to select only one of the options. Is there a way to select both A and B for example?

A: Old question but I found it when googling, so here's the answer:
inquirer.Checkbox('multiples',
  message="Which modules do you need? (Press <space> to select, Enter when finished).",
  choices=['A', 'B', 'C', 'D', 'E', 'F'])

HTH someone else in the same situation.
Documentation: https://python-inquirer.readthedocs.io/en/latest/usage.html


text:
Q: Character Encoding? Site Migration to new Server after Upload of UI displaying full page of diamonds with ? marks inside So I have just completed a migration to a new server, after restoring the mysql dump the site was working fine, but as soon as I uploaded the front end I was faced with this '��}�v�8����9���HސI���#e����Mb' etc for the whole site. Have searched the web but there seems to be nothing relating to my problem. My new server is running CentOS with a LAMP stack and all the usuals. The site is Drupal 7.something
Any help or suggestions would be great.

A: (Too long for a comment.)
'Plüg' sounds German, but the sample text is not a simple transcoding of German text.  What was the intended text?  What language was the text in?  One character is Maldivian, but the rest does not fit.
The sample output makes it sound like you have two errors, so let's do some debugging...
SELECT col, HEX(col) FROM tbl WHERE ...

to display some cell that should have non-English text in it.  From that, we might be able to decide whether the text was damaged upon input, or is damaged coming back out.
This question may be a duplicate of utf8 all the way through.  And/or you may need utf8mb4.


text:
Q: Java convert SVG string into PNG file I have svg string which is svg from chart:
String svg = chart.getSVG();

String looks like <svg>...<g>...</g>...</svg> and so on.
Now i want to save it into Excel with method
Workbook wb = new HSSFWorkbook();
wb.addPicture(safeDataBytes, Workbook.PICTURE_TYPE_PNG);

The problem is I don't know how to create PNG from this SVG String...
I don't need to save this file.
Already i tryied:
byte[] safeDataBytes = new byte[0];
                            try {
                                safeDataBytes = new BASE64Decoder().decodeBuffer(svg);
                            } catch (IOException e) {
                                e.printStackTrace();
                            }

But it didn't work.


text:
Q: How to "jump" the frame of an arbitrary python generator running instance from pdb/pdbpp? Suppose you have this generator :
def gen():
  for i in range(10):
    yield i-5

And then you do that :
try :
  for a in gen():
    print(5 / a) # Obviously, it will crash on a=0
except:
  import pdb; pdb.xpm() # I'm using pdbpp actually

Once the debugger started (either vanilla pdb or pdbpp), is there a way to "enter" inside the generator (go to its execution frame), to inspect its internal variables, without interrupting the program (I mean, to just "observe" and being able to coninue the execution as if the debugger were never launched) ?
EDIT
If it could help, in real code, I still have a reference to the generator, so it "more" like this :
g = gen()
try :
  for a in g:
    print(5 / a) # Obviously, it will crash on a=0
except:
  import pdb; pdb.xpm() # I'm using pdbpp actually

A: With code like you originally posted, you can't inspect the generator.
The generator's already gone at the point you launch the debugger. The only reference to the generator was on the value stack of the frame object where the loop over the generator occurred, and that reference gets cleared as the exception propagates. Here's a program demonstrating this fact:
class DelPrintIterator:
    def __iter__(self):
        return self
    def __next__(self):
        return 1
    def __del__(self):
        print('Deleting iterator')

try:
    for i in DelPrintIterator():
        1/0
except ZeroDivisionError:
    print('Too late')

This prints
Deleting iterator
Too late

showing that the iterator becomes unreachable before any code in the except block runs.

Now, with a reference to the generator, something like
g = gen()
try:
    for a in gen():
        print(5 / a)
except ZeroDivisionError:
    ...

then... well, I don't know of any debuggers that would let you "step into" the generator's stack frame when it's not on the stack, but you can manually retrieve the frame with g.gi_frame and then start looking through the same attributes the debugger uses, like frame.f_locals or frame.f_lineno. (Frame object attributes are listed in the inspect module docs.) It'll be less convenient than the debugger's interface, but the same information is still there.


text:
Q: I can't seem to build my android application when I'm signing it I can build the application when it's not signed but every time I try to sign Android Studio says something along the lines of

"ERROR: Failed to resolve: com.android.support.cardview-v7:27.1.1"

I've checked this and verified it exists but it doesn't seem to work, it gives other dependency issues if I try to fix it.
"My build.gradle (app)"
apply plugin: 'com.android.application'

android {
    compileSdkVersion 27

    defaultConfig {
        applicationId "uk.org.cetma.llanellistandard"
        minSdkVersion 23
        targetSdkVersion 26
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner
"android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
        }
    }
}

repositories {
    mavenCentral() // jcenter() works as well because it pulls from Maven
Central
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.github.bumptech.glide:glide:3.7.0'
    implementation 'com.android.support:support-v7:27.1.0'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.squareup.picasso:picasso:2.71828'
    testImplementation 'junit:junit:4.12'
    //androidTestImplementation 'com.android.support.test:runner:1.0.2'
    //androidTestImplementation 'com.android.support.test.espresso:espresso-
   core:3.0.2'

    //Add Library
    implementation 'com.android.support.cardview-v7:27.1.1'
    implementation 'com.android.support:recyclerview-27.1.0'
    implementation 'com.google.code.gson:gson:2.8.2'

}

I want it to sign the application so I can make sure it still works.
Below is an example of the error I get:

ERROR: Failed to resolve: com.android.support.cardview-v7:27.1.1:
      Affected Modules: app

A: double dots are missing from your card view dependency use this -
implementation 'com.android.support:recyclerview-v7:27.1.1'
implementation 'com.android.support:cardview-v7:27.1.1'

A: try with

implementation 'com.android.support:cardview-v7:27.1.1'


text:
Q: Why I am get complex values in this integral? I would like to get the following integral:

$$\int -\frac{\log(a^2+x^2)}{(a^2+x^2)}dx \quad \text{or} \quad \int_{t}^{+\infty}-\frac{\log(a^2+x^2)}{(a^2+x^2)}dx$$

where $t>0$.
I used WolframAlpha to compute, and I got following expression:

I am just wondering why some complex value i appears? Any ideas of how to get the closed form of integral from t to +inf ? I guess I need to give more specification to wolframalpha to compute ?

A: For real $x$ and $a$ it is possible to rewrite the result using only real-valued functions. After copious use of the function relations
$$\arctan z=-\frac i2\log\frac{i-z}{i+z}$$
$$\operatorname{Li}_2(e^{it})=\frac{\pi^2}6-\frac{\pi t}2+\frac{t^2}4+i\operatorname{Cl}_2(t)$$
where $\operatorname{Cl}_2$ is the classical Clausen function, the simplified result is
$$\int_0^x\frac{\log(t^2+a^2)}{t^2+a^2}\,dt=\frac1a\left(2\log2a\arctan\frac xa-\operatorname{Cl}_2\left(\pi-2\arctan\frac xa\right)\right)$$
The integral over $[0,\infty)$ is $\frac{\pi\log2a}a$; cf. here.


text:
Q: Make "Add New User" redirect to user's profile I'm wondering if it's possible that when you create a new user user-new.php you're being redirect to the user's profile instead of to users.php
I'm having some custom fields who only show up when you edit a user, so to make the workflow more easy I would like that the admin gets redirect to the user's profile so he can add those custom fields instantly.

A: wp_redirect is filterable, so you could hook in to redirect after a user was successfully added. I tested the following, might need a few tweaks but it does the trick:
add_filter( 'wp_redirect', 'wp_redirect_after_user_new', 1, 1 );
function wp_redirect_after_user_new( $location )
{
    global $pagenow;

    if( is_admin() && 'user-new.php' == $pagenow )
    {
        $user_details = get_user_by( 'email', $_REQUEST[ 'email' ] );
        $user_id = $user_details->ID;

        if( $location == 'users.php?update=add&id=' . $user_id )
            return add_query_arg( array( 'user_id' => $user_id ), 'user-edit.php' );
    }

    return $location;
}


text:
Q: List Variables and Methods on DOM Object How would I find out what variables and methods are on a DOM Object? In the example below, how do I find out that div#main has a variable greeting, and a method greet?
(Preferably without using an external library.)

var main = document.querySelector('#main');

main.greeting = 'Hello Meep!';

main.greet = function() {
  alert(this.greeting);
}

main.greet();

  ...

A: On browsers that allow it with DOM elements, you can use Object.keys or for-in to get an array of the enumerable properties:
console.log(Object.keys(main));

That works on a wide range of modern browsers, but note that browsers are not required to allow you to introspect DOM elements that way, so if you rely on it, be sure to test in your target browsers.
If you want non-enumerable properties as well as enumerable ones, you could try Object.getOwnPropertyNames(main) rather than Object.keys(main).
Example:

var main = document.querySelector('#main');

main.greeting = 'Hello Meep!';

main.greet = function() {
  alert(this.greeting);
}

main.greet();

var p = document.createElement('p');
p.appendChild(document.createTextNode(
  Object.keys(main).join(", ")
));
document.body.appendChild(p);

  ...


text:
Q: Bootstrap clock picker outside iframe I am using bootstrap modal for showing modal window. For modal body I am using iframe so that if I submit form I can get response on the same modal window.
My iframe is like :

I am using ClockPicker plugin to pick the time. But when Clock Picker appears it hides behind the scroll. I have changed z-Index of clock picker but it doesn't seem to work.

Any help ?


text:
Q: Account balance system with Stripe For the past two days I've been trying to understand how Stripe works.. What I'm trying to build is a simple system that lets the user to add funds to his account on the site.
I followed a tutorial I found on the internet that uses Laravel Cashier but as I've read on the laravel documentation if I need to perform single charges I should use directly Stripe. The thing is, there are not many tutorials on how this should be done with laravel..
Here's what I have so far:
VIEW:
    <form class="app-form" style="margin-bottom: 0px;" action="/add-funds" method="POST">
      {{ csrf_field() }}

      <select id="funds-options" style="width: 20%; margin-bottom: 20px;" name="add-funds-select">
        <option value="30">$30</option>
        <option value="50">$50</option>
        <option value="100">$100</option>
        <option value="200">$200</option>
        <option value="300">$300</option>
        <option value="500">$500</option>
      </select>

      <p style="margin-bottom: 0px;">
        <script src="https://checkout.stripe.com/checkout.js"></script>

        <button id="customButton">Purchase</button>

        <script>
        var handler = StripeCheckout.configure({
          key: '{{ getenv('STRIPE_KEY') }}',
          image: 'https://stripe.com/img/documentation/checkout/marketplace.png',
          locale: 'auto',
          token: function(token) {
            // You can access the token ID with `token.id`.
            // Get the token ID to your server-side code for use.
          }
        });

        document.getElementById('customButton').addEventListener('click', function(e) {
          // Open Checkout with further options:
          var userAmount = $("#funds-options").val();

          handler.open({
            name: 'Demo Site',
            description: '2 widgets',
            amount: userAmount*100
          });
          e.preventDefault();
        });

        // Close Checkout on page navigation:
        window.addEventListener('popstate', function() {
          handler.close();
        });
        </script>
      </p>
    </form>

I have this select tag where the user can select the amount he wants to add to his account. Now, this opens the widget from Stripe but as soon as I hit pay, I'm getting that info: "You did not set a valid publishable key".
I tried this using the publishable key directly and I'm able to pass this but as soon as it gets into the controller it throws pretty much the same error, something like API key was not set.
I set the keys in the env file and I also reference them in the services.php..
ENV:
STRIPE_KEY=pk_test_....
STRIPE_SECRET=sk_test_...

SERVICES:
'stripe' => [
    'model' => App\User::class,
    'key' => env('STRIPE_KEY'),
    'secret' => env('STRIPE_SECRET'),
],

Anyway, even if I pass this "error" I'm still not sure if I'm doing this right.
Controller:
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Auth;

class WalletController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */

    public function index()
    {
        return view('user.wallet.index');
    }

     public function postPayWithStripe(Request $request)
     {
         return $this->chargeCustomer($request->input('add-funds-select'), $request->input('stripeToken'));
     }

     public function chargeCustomer($amount, $token)
     {
        \Stripe\Stripe::setApiKey(getenv('STRIPE_SECRET'));

         if (!$this->isStripeCustomer())
         {
             $customer = $this->createStripeCustomer($token);
         }
         else
         {
             $customer = \Stripe\Customer::retrieve(Auth::user()->stripe_id);
         }

         return $this->createStripeCharge($amount, $customer);
     }
     public function createStripeCharge($amount, $customer)
     {
         try {
             $charge = \Stripe\Charge::create(array(
                 "amount" => $amount,
                 "currency" => "brl",
                 "customer" => $customer->id,
                 "description" => "Add funds to your account"
             ));
         } catch(\Stripe\Error\Card $e) {
             return redirect()
                 ->route('index')
                 ->with('error', 'Your credit card was been declined. Please try again or contact us.');
     }

         return $this->postStoreAmount($amount);
     }

     public function createStripeCustomer($token)
     {
         \Stripe\Stripe::setApiKey(getenv('STRIPE_SECRET'));

         $customer = \Stripe\Customer::create(array(
             "description" => Auth::user()->email,
             "source" => $token
         ));

         Auth::user()->stripe_id = $customer->id;
         Auth::user()->save();

         return $customer;
     }

    /**
     * Check if the Stripe customer exists.
     *
     * @return boolean
     */
     public function isStripeCustomer()
     {
         return Auth::user() && \App\User::where('id', Auth::user()->id)->whereNotNull('stripe_id')->first();
     }

     public function postStoreAmount($amount)
     {
        $userBalance = Auth::user()->balance;
        $userBalance = $userBalance + $amount;

        Auth::user()->save();

        session()->flash('message', 'You just added funds to your account.');
        return redirect()->route('index');
     }
}

I have a field in the users table that holds the user balance.
As I mentioned, I followed a tutorial I found on the internet.. I'm not sure how this should work. Any suggestions?

A: You will follow this tutorial. I am integrated it in my cart functionality previous week. Its very easy to integrate ...have Fun :)
http://justlaravel.com/integrate-stripe-payment-gateway-laravel/

A: For anyone else looking for how to retrieve account balance with laravel cashier, I found it like this:
$user = App\User::first();
echo $user->asStripeCustomer()->account_balance;

This returns the account balance in cents.


text:
Q: How to transfer a photo from one viewcontroller to a UIImageView of another viewcontroller I have a tableview, when I click on a cell, I would like to transfer a photo to another ViewController and place it right away in UIImageView
Photo transfer
override func prepare(for segue: UIStoryboardSegue, sender: Any?)  {

    if segue.identifier == "segue" {

        if let detail = segue.destination as? DetailViewController  {

            detail.PhotoProfile = selectedImage

        }
    }
}

on the second view so
@IBOutlet weak var PhotoProfile: UIImageView!

A: Destination controller's view is not loaded in prepare(for:), It's not the best practice of passing data between controllers but you can make sure that view is loaded before touching any if it's subviews using outlets:
override func prepare(for segue: UIStoryboardSegue, sender: Any?)  {

    if segue.identifier == "segue" {

        if let detail = segue.destination as? DetailViewController  {
            detail.loadViewIfNeeded()
            detail.PhotoProfile = selectedImage
        }
    }
}


text:
Q: Expanding in terms of a function in Solve I am almost sure Mathematica has a way to do what I am looking for. I am trying to fit a quadratic T(x) = ax^2 + bx + c to three values of the function analytically. I proceed as follows:
T[x_] := c_0 + c_1 x + c_2 x^2;
Solve[T_w == T[x_w] && T_p == T[x_p] && T_e == T[x_e], {c_0, c_1, c_2}]

The output is:
{{}}

What am I doing incorrectly?
Edit: I am using display subscripts instead of underscores. If I replace the former the latter, it works fine. Why is this true? Is there a way to declare variables with subscripts from the start?

A: Do not use subscripts as variables, these are a display option. Also, don't start variables and function with capitol letters. This works fine:
t[x_] := c0 + c1 x + c2 x^2;
Solve[tw == t[xw] && tp == t[xp] && te == t[xe], {c0, c1, c2}]


text:
Q: How to call a builtin function (or method) from C code of a Python extension module? What I currently want to accomplish is to tweak Pythons itertools module  function combinations to sort the passed iterable before creating combinations out of it with the goal of having the returned combinations sorted.
I am working on a Python extension module for the first time and my only experience up to now was to write and compile a "Hello World" like Python extension module, but I hope that my overall programming experience in a couple of programming languages is a solid enough foundation I can build upon to succeed on this challenge.
I know that there is a builtin Python function sorted() which can sort the iterable passed to combinations but I don't know how to call it from within the C code of the extension module.
I have tried just to write iterable = sorted(iterable); but even if the module compiles (with a warning) the import of the compiled module fails with ImportError: cgitertools.cpython-36m-x86_64-linux-gnu.so: undefined symbol: sorted
My question is:

How to call the Pythons builtin method (using as example sorted()) from within C code of a Python extension module?

Below all the details of what I have tried and why it didn't work:
combinations_new(PyTypeObject *type, PyObject *args, PyObject *kwds)
{
    combinationsobject *co;
    Py_ssize_t n;
    Py_ssize_t r;
    PyObject *pool = NULL;
    PyObject *iterable = NULL;
    Py_ssize_t *indices = NULL;
    Py_ssize_t i;
    static char *kwargs[] = {"iterable", "r", NULL};

    if (!PyArg_ParseTupleAndKeywords(args, kwds, "On:combinations", kwargs,
                                     &iterable, &r))
        return NULL;

    // iterable.sort(); doesn't work ... cgitertoolsmodule.c:2398:13: error: request for member 'sort' in something not a structure or union
    // iterable.__sort__(); doesn't work either with same error
    // COMPILES, but gives ERROR on import in Python:
    iterable = sorted(iterable);

$ python3.6 cgitertoolsmodule-setup.py build
running build
running build_ext
building 'cgitertools' extension
gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/usr/local/include/python3.6m -c cgitertoolsmodule.c -o build/temp.linux-x86_64-3.6/cgitertoolsmodule.o
cgitertoolsmodule.c: In function 'combinations_new':
cgitertoolsmodule.c:2400:16: warning: implicit declaration of function 'sorted' [-Wimplicit-function-declaration]
     iterable = sorted(iterable);
                ^
cgitertoolsmodule.c:2400:14: warning: assignment makes pointer from integer without a cast [-Wint-conversion]
     iterable = sorted(iterable);
              ^
gcc -pthread -shared build/temp.linux-x86_64-3.6/cgitertoolsmodule.o -o build/lib.linux-x86_64-3.6/cgitertools.cpython-36m-x86_64-linux-gnu.so

$ python3.6
Python 3.6.1 (default, Apr 18 2017, 23:00:41)
[GCC 5.4.1 20160904] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> from cgitertools import combinations
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cgitertools.cpython-36m-x86_64-linux-gnu.so: undefined symbol: sorted

A: You should get the sorted function out of the builtins and than call it:
PyObject *builtins = PyEval_GetBuiltins();
PyObject *sorted = PyDict_GetItemString(builtins , "sorted");
PyObject *sorted_list = PyEval_CallFunction(sorted, "(O)", iterable);

//... do something with the sorted_list

Py_DECREF(sorted_list);


text:
Q: R ggplot function error My name is Venus , I am a beginner of data mining and use R. Right now, I need fill my datas to map and show it with different colours to see the different level.
I have install ggplot library and input my data with longtitue and latitude
My code like this
> ggplot(target_map, aes(long, lat, group = group, fill = Target.rate)) +
+   geom_polygon(colour = alpha("black", 1/2), size = 0.2) +
+   geom_polygon(data = needregion, colour ="white", fill = NA)+
+   scale_fill_brewer(palette = "PuRd")

I do this from an example, but I don't know why R always return this result:

Error: Aesthetics must be either length 1 or the same as the data (19584): x, y, group, fill

So, Could you give me some suggest what wrong with me? Thank you a lot


text:
Q: Counting Methods with Combinatorics Problems (2) I have a couple of problems with my attempts at them. I was wondering if I could get some verification/help if possible!

*

*A college sent a report saying that 119 students took Calc. I in a Fall Semester. The report says that during the next term, 96 of those students were in Calc. II, 53 of them took Discrete Mathematics, and 39 of them took Physics II. The report also says that 38 of the students took both Calc. II and Discrete Mathematics, 31 of the students took both Discrete Mathematics and Physics II, 32 of the students took both Calc. II and Physics II, and 22 of the students took all three courses. We examine the report and sense an error is present. Why?

119 students total from the Fall semester.
96-Calc II
53-Discrete Mathematics
39-Physics II
38-Calc II and Discrete
31-Discrete and Physics II
32-Calc II and Physics  II
22-Calc II, Discrete, and Physics II
My guess is that if 22 students took all three courses, that would leave a remainder of 74 that are taking Calc II, 31 taking Discrete Math, and 17 taking Physics II which adds up to 122 students. 122>119. Is that the error? Or am I approaching this wrong?

2. We are going to count banana splits: These are ice cream treats that have 3 scoops of ice cream (two or three of the scoops could be the same flavor), three toppings (two or three could be the same flavor), whipped cream (always), a choice of nuts or no nuts, and a choice of a cherry or no cherry, all placed atop two banana halves. If there are 18 different flavors of ice cream and 5 choices of toppings, how many different banana split orders are possible? Note that people do care which toppings end up on which scoops, so the positions of the scoops should be labeled.

So, we have to have 3 scoops of ice cream that have 18 different flavors and they can be repeated  3 toppings that have 5 different kinds and they can be repeated  always whipped cream  nuts or no nuts  and a cherry or no cherry.

I'm going to take a wild shot at this, and I'm probably overthinking it. Order matters and repetition is allowed for the toppings on the scoops. So, we have 18 flavors for our 3 scoops of ice cream. We would use $k^n= 18^3= 5,832$ different scoop & flavor combinations. Same approach with the toppings: $5^3=125$ different combinations.
I attempted to go further with this, but yielded an incredibly high number...so, I'm stopping here. I think I'm doing something wrong. Any suggestions are appreciated very much!

A:
A college sent a report saying that $119$ students took Calc. I in a Fall Semester. The report says that during the next term, $96$ of those students were in Calc. II, $53$ of them took Discrete Mathematics, and $39$ of them took Physics II. The report also says that $38$ of the students took both Calc. II and Discrete Mathematics, $31$ of the students took both Discrete Mathematics and Physics II, $32$ of the students took both Calc. II and Physics II, and $22$ of the students took all three courses. We examine the report and sense an error is present. Why?

We are told that $22$ students take all three courses, $31$ students take both Physics II and Discrete Mathematics, and $32$ students take both Physics II and Calculus II.  Since $22$ students take all three courses, that means $31 - 22 = 9$ students take Physics II and Discrete Mathematics but not Calculus II and that $32 - 22 = 10$ students take Physics II and Calculus II but not Discrete Mathematics.  If all these numbers are correct, there are at least $22 + 9 + 10 = 41$ students in Physics II.  However, we are also told that a total of $39$ students are enrolled in Physics II, which is a contradiction.

We are going to count banana splits: These are ice cream treats that have 3 scoops of ice cream (two or three of the scoops could be the same flavor), three toppings (two or three could be the same flavor), whipped cream (always), a choice of nuts or no nuts, and a choice of a cherry or no cherry, all placed atop two banana halves. If there are 18 different flavors of ice cream and 5 choices of toppings, how many different banana split orders are possible? Note that people do care which toppings end up on which scoops, so the positions of the scoops should be labeled.

What you have done thus far is correct.  Since whipped cream is automatically included, you have to multiply your result by the number of choices entailed in choosing whether or not to order nuts and whether or not to order a cherry on top.

A: For the banana split problem, one approach is to first create a compound item.
In this case, the compound item would would be a scoop with the flavor, toppings, nuts and cherries already pre-selected.
There are $18*5*2*2 = 360$ compound items.
So, the problem simplifies to selecting $3$ times with replacement from $360$ items.
If the order in which you select the compound items matter, there are $360^3$ ways.
If the order does not matter and all you care about is which $3$ items you end up with, then it gets a bit more complicated and you will have to split it up into cases.

A: First
Indeed an error is present.
Let's call $A$ the set of students who took Calculus I.
Let $C,D,P$ be three of its subsets. (for Calculus, Discrete and Physics)
(I notate the disjoint union $\sqcup$)
Provided information
$$|A|=119, ~~~~~~ |C|=96, ~~~~~~ |D| = 53, ~~~~~~ |P|=39$$
$$|P\cap C| = 32, ~~~~~~ |P\cap D|=31, ~~~~~~ |C\cap D| = 38, ~~~~~~ |C\cap D\cap P| = 22$$
But
$$\matrix{&P\cap D &= &(P\cap D \cap C) & \sqcup & (P\cap D\cap\bar C)\\
\Rightarrow & |P\cap D| & = & |P\cap D \cap C| & + & |P\cap D\cap\bar C|\\
\Leftrightarrow & |P\cap D| & - & |P\cap D \cap C| & = & |P\cap D\cap\bar C|\\
\Rightarrow & 31 & - & 22 & = & |P\cap D\cap\bar C|\\
\Rightarrow & &&|P\cap D\cap\bar C| & = & 9}$$
With a similar reasoning, we find that $~~|P\cap C\cap \bar D|= 10$
Finally,
$$\matrix{&P&=&(P\cap D \cap C)&\sqcup&(P\cap D \cap \bar C)&\sqcup&(P\cap \bar D \cap C)&\sqcup&(P\cap \bar D \cap \bar C)\\
\Rightarrow & |P| & \geqslant&|P\cap D \cap C|&+&|P\cap D \cap \bar C|&+&|P\cap \bar D \cap C|\\
\Rightarrow & 39 & \geqslant&22&+&9&+&10\\
\Leftrightarrow & 39 & \geqslant & 41}$$
Seems like we got ourselves a contradiction.
Solution
$$|P\cap C \cap D| \leftarrow 24$$
(I verified every possible relation and there is no contradiction)
Second

*

*The choice of scoop flavor is unordered with repetition so the possibilities are $\binom{n+k-1}{k}=\binom{18+3-1}{3}=1140$

*The choice of topping is ordered and with repetition, thous $5^3 = 125$ possibilities

*Nuts and cherries both multiply by 2

Total
We got a total of 570 000 possible banana splits !!


text:
Q: Configure Maximum Number of Requests in IIS Express How can I configure the maximum number of requests allowed in IIS Express?
I would like to change this to only allow a few requests to test what happens when it exceeds the limit.

A: IIS Express can be configured using applicationHost.config file.
It is located at %userprofile%\my documents\IISexpress\config
Open this file in text editor. You will find <sites> element in <system.applicationHost> section.  In that you will find a <site> element for each site hosted on IIS express. Find the element corresponding to your site. Add a <limits> element as shown below.
<sites>
  <!-- Other sites -->

  <site name="YourSiteName" id="YourSiteId">
    <!-- Existing elements -->

    <limits maxBandwidth="65536" maxConnections="1024" connectionTimeout="00:01:00" />
  </site>

  <!-- Remaining sites -->
</site>

You can set maxConnections parameter to desired number of requests.
This should work though I have not tested it.

A: Now this is a tough question to answer. The number of requests the server can handle depends on the Server, the CPU and the RAM on which it has been hosted. By default, IIS supports unlimited connections. However, you can perform stress testing to see how much load can that server take. Later use a load balancer to pass on the excessive load to another IIS server.
You can always do request filtering in IIS . See this


text:
Q: Connecting apachec to mysql data base As a part of assignment I am trying to connect my Apache server to MySql database.
I have verified that my Apache is working with following code:
<?php

class RedeemAPI {
    // Main method to redeem a code
    function redeem() {
        echo "Hello, PHP!";
    }
}

// This is the first thing that gets called when this page is loaded
// Creates a new instance of the RedeemAPI class and calls the redeem method
$api = new RedeemAPI;
$api->redeem();

?>

But when I replace this code to read from my database it gives me following error:
<?php

    class RedeemAPI {
        private $db;

        // Constructor - open DB connection
        function __construct() {
            $this->db = new mysqli('localhost', 'username', 'password', 'promos');
            $this->db->autocommit(FALSE);
        }

        // Destructor - close DB connection
        function __destruct() {
            $this->db->close();
        }

        // Main method to redeem a code
        function redeem() {
            // Print all codes in database
            $stmt = $this->db->prepare('SELECT id, code, unlock_code, uses_remaining FROM rw_promo_code');
            $stmt->execute();
            $stmt->bind_result($id, $code, $unlock_code, $uses_remaining);
            while ($stmt->fetch()) {
                echo "$code has $uses_remaining uses remaining!";
            }
            $stmt->close();
        }
    }

    // This is the first thing that gets called when this page is loaded
    // Creates a new instance of the RedeemAPI class and calls the redeem method
    $api = new RedeemAPI;
    $api->redeem();

    ?>

Error: Warning: mysqli::mysqli(): (HY000/2002): No such file or
  directory in /Library/WebServer/Documents/promos/index.php on line 8
Warning: mysqli::autocommit(): Couldn't fetch mysqli in
  /Library/WebServer/Documents/promos/index.php on line 9
Warning: mysqli::prepare(): Couldn't fetch mysqli in
  /Library/WebServer/Documents/promos/index.php on line 20
Fatal error: Call to a member function execute() on a non-object in
  /Library/WebServer/Documents/promos/index.php on line 21

Please let me know what is causing this and how can i resolve this.

A: To connect php to mysql, you need to place following code to check whether the connection is done -
/* check connection */
if (mysqli_connect_errno()) {
    printf("Connect failed: %s\n", mysqli_connect_error());
    exit();
}

Let me know what error coming now ?


text:
Q: login and signup tab does not work xml I am trying to create login and signup tab on the same page. so everytime I press signup on the login screen, it change to the signup screen as expected, so does the signup screen. On the signup screen, everytime I press the login tab, it works too. But on the login screen, everytime I press login, it goes to signup screen but I want it to stay on login screen. The weird thing is that everytime I press signup, it stays on the signup screen . Can anyone help? any help would be appreciated.
Android classes
SignUpScreen.java
 final Intent i = new Intent(SignUpScreen.this, LoginScreen.class);
    TextView b = (TextView) findViewById(R.id.text1);

    b.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {

            setContentView(R.layout.login_screen);
            SignUpScreen.this.startActivity(i);
        }
    });

my LoginScreen.java
final Intent i = new Intent(LoginScreen.this,SignUpScreen.class);
    TextView c = (TextView) findViewById(R.id.text4);

    c.setOnClickListener(new View.OnClickListener() {
        public void onClick(View arg0) {

            setContentView(R.layout.sign_up_screen);
            LoginScreen.this.startActivity(i);
        }
    });

A: Inside setOnClickListener, why you have given setContentView(R.layout.login_screen);
    Actually in onCreate only, setContentView should be present.
Better your full code will help to guide.

A: try above code for SignUpScreen.java
TextView b = (TextView) findViewById(R.id.text1);

b.setOnClickListener(new View.OnClickListener() {
    public void onClick(View arg0) {
        Intent i = new Intent(SignUpScreen.this, LoginScreen.class);
        startActivity(i);
    }
});

and for LoginScreen.java
TextView c = (TextView) findViewById(R.id.text4);

c.setOnClickListener(new View.OnClickListener() {
    public void onClick(View arg0) {

        Intent i = new Intent(LoginScreen.this,SignUpScreen.class);
        startActivity(i);
    }
});

A: You must call setContentView in onCreate method and do something like this :
protected void onCreate(Bundle savedInstanceState){

   if(forLoginScreen) {
     setContentView(R.layout.login_screen);
   }else {
    setContentView(R.layout.sign_up_screen);
   }

}

A: You just have to create two activity one for login and another for signup, in login activity you have to give login form and two button one for login and one for signup.
and make the login activity as your launcher activity. on clicking the signup button just call the signup activity by using intent
public class LoginActivity extends Activity {
private EditText mEmail;
private EditText mPassword;

Button btn_login,btn_signup;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_login);

    btn_login.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

                uid = mEmailView.getText().toString();
                pwd = mPasswordView.getText().toString();

                if(uid.equalsIgnoreCase("")){
                    mEmailView.setError("Please enter user id");
                }else if(pwd.equalsIgnoreCase("")){
                    mPasswordView.setError("Please enter password");
                }else  {
                    //do whaterver you want to do after login
                }

        }
    });

            btn_signup.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent i=new Intent(LoginActivity.this,Signup.class);
                    startActivity(i);
        }
    });
}

}
and in Signup page when you signup the user successfully redirect him to the login page by using  intent
Intent i=new Intent(Signup.this,LoginActivity.class);
                        startActivity(i);
or you can redirect him into the other activity


text:
Q: How to slice through two axis of an array simultaneously? Problem: x is an n-dimensional array with shape (100, 50, 50, 2). I would like to modify the elements of the array that have the same index in the 1st and 2nd axis in a vectorized way.
Without vectorizing, I could do it with:
for i in range(50):
   x[:, i, i, :] = 0

The problem is the same as accessing the elements of the diagonal defined by the 1st and 2nd axis.

This question was already asked in Modifying diagonals in multidimensional numpy arrays. However, the only answer there uses the function numpy.lib.stride_tricks. According to numpy documentation, this function "can point to invalid memory and can corrupt results or crash your program" and "it is advisable to avoid as_strided when possible". For these reasons, I wonder if there is a safer and easier way to achieve this problem.

A: You can use np.arange(50) as an indexer for both positions; it will give pairs (0, 0), (1, 1), ..., (49, 49) as the indexers for those 2 positions:
n = np.arange(x.shape[2])
x[:, n, n, :] = 0

sample:
>>> a = np.arange(150).reshape(3, 5, 5, 2)
>>> n = np.arange(a.shape[2])
>>> a[:, n, n, :] = 0
>>> a

array([[[[  0,   0],               # changed
         [  2,   3],
         [  4,   5],
         [  6,   7],
         [  8,   9]],

        [[ 10,  11],
         [  0,   0],               # changed
         [ 14,  15],
         [ 16,  17],
         [ 18,  19]],

        [[ 20,  21],
         [ 22,  23],
         [  0,   0],               # changed
         [ 26,  27],
         [ 28,  29]],

        [[ 30,  31],
         [ 32,  33],
         [ 34,  35],
         [  0,   0],               # changed
         [ 38,  39]],

        [[ 40,  41],
         [ 42,  43],
         [ 44,  45],
         [ 46,  47],
         [  0,   0]]],             # changed

       [[[  0,   0],               # changed
         [ 52,  53],
         [ 54,  55],
         [ 56,  57],
         [ 58,  59]],

        [[ 60,  61],
         [  0,   0],               # changed
         [ 64,  65],
         [ 66,  67],
         [ 68,  69]],

        [[ 70,  71],
         [ 72,  73],
         [  0,   0],               # changed
         [ 76,  77],
         [ 78,  79]],

        [[ 80,  81],
         [ 82,  83],
         [ 84,  85],
         [  0,   0],               # changed
         [ 88,  89]],

        [[ 90,  91],
         [ 92,  93],
         [ 94,  95],
         [ 96,  97],
         [  0,   0]]],             # changed

       [[[  0,   0],               # changed
         [102, 103],
         [104, 105],
         [106, 107],
         [108, 109]],

        [[110, 111],
         [  0,   0],               # changed
         [114, 115],
         [116, 117],
         [118, 119]],

        [[120, 121],
         [122, 123],
         [  0,   0],               # changed
         [126, 127],
         [128, 129]],

        [[130, 131],
         [132, 133],
         [134, 135],
         [  0,   0],               # changed
         [138, 139]],

        [[140, 141],
         [142, 143],
         [144, 145],
         [146, 147],
         [  0,   0]]]])            # changed


text:
Q: How can i pass function as argument to function in C++ I have method(void DE(...) that finds parameters of function y=f(x, a, b...) based on some data points. When I want to use function, that has other number of arguments, I need to comment first function, write second function, add (X.PAR[i][1],..., X.PAR[i][n]) arguments of this function every time I use func(y, x, param_1....param_n). How can I make function f(double x1, x2,...xn)to be an argument of function DE, so i wont need to change my program for every other function?
double f(double x1, x2,...xn){

}
void DE(int n){
 double A[n];
 fill(A) //some function that makes up values
 cout<<f(A[0], A[1],...A[n-1]);//if I change number of arguments in f, I also need to change it here
}

A: OK, some things:

*

*double A[n]; variable length arrays are not standard c++, if you really, really want to use c-array you have to do it in another way (costant size, new).

*But, you don't really want c-array, you just need a vector, it brings away all of your problems.

*If your needings are more complicated than your example and you are dure you want to use this approach, you could pass the function to be called at your method.

Here's an example with the solution for the second point and an hint to approach the solution at point 3:
#include <iostream>
#include <vector>
using namespace std;

void fill(vector<double> &vec)
{
    vec.push_back(12);
    vec.push_back(1.3);
    vec.push_back(4.7);
}

double f(const vector<double> &vec)
{
    double some_value = 1;
    for(double val:vec)
        some_value = some_value*val;
    return some_value;
}

double fn(double a1, double a2, double an)
{
    double some_value = 1;
    some_value = some_value*a1*a2*an;
    return some_value;
}
void DE()
{
   vector<double> A;
   fill(A); //some function that makes up values
   cout<<f(A)<<endl;
}
template<typename Func>
void DE2(Func func)
{
   double A[3];
   A[0] = 12;
   A[1] = 1.5;
   A[2] = 4.6;
   cout<<func(A[0], A[1], A[2])<<endl;
}

int main()
{
    DE();
    DE2(fn);
}


text:
Q: matlab code analyzer produces empty tooltips I'm running MATLAB (R2013b) on Ubuntu (results of ver command are pasted below).
I've just started working with this system, and I've realized that coding is seriously hard because the typical "tooltips" that show up in the editor are empty. Unfortunately I cannot paste screenshots, but here I describe the problem: the orange marks on the right margin of the editor should indicate a warning. Passing the cursor on them, one typically gets a tooltip with a short message, detailing the reason of the warning.
In my case, I still see the tooltip... but cannot read anything in there, it's just a gray rectangle. This is terribly annoying... Some idea on what may be the problem?
>> ver
MATLAB Version: 8.2.0.701 (R2013b)
Operating System: Linux 3.5.0-41-generic #64~precise1-Ubuntu SMP Thu Sep 12 16:50:04 UTC 2013 x86_64
Java Version: Java 1.7.0_11-b21 with Oracle Corporation Java HotSpot™ 64-Bit Server VM mixed mode

A: Are you using the Unity desktop (if you don't know, you probably are, since Unity is the default).
I've encountered your problem with multiple Matlab versions under Linux, and it always boiled down to using a "3D / fancy pants" window manager.
Try using the "Gnome Classic (no effects)", "Ubuntu 2D" or mate sessions and report back whether your problem still exists. Here's a screenshot of the standard desktop login screen in Ubuntu 12.04:

To see the available sessions, do a left-mouse click on the ubuntu logo next to the username (here test):

A: I had the same problem and solved it without disabling Unity.
Solution:
-open matlab
-go to Preferences->colors
-uncheck "use system colors" for desktop tool colors
-Apply
Now you should see text.
It seems likely that the problem is due to one of 3 scenarios:
1) The relevant default colors in Unity are grey text ion grey background.
2) Matlab Doesn't manage to read the default relevant colors from Unity
3) there is a bug in matlab where it not just greys out the color controls in the GUI but actually greys out the underlying colors.