text:
Q: Find all rational solutions of $x^2(x+1)(x^2+1)(x-1)=2(y+1)(y-1)$ Find all rational solutions of
$$x^2(x+1)(x^2+1)(x-1)=2(y+1)(y-1).$$
Clearly the following six solutions hold:
$$(x,y)=(1,1),(-1,-1),(-1,1),(1,-1),(0,1),(0,-1)$$
But how to find all rational solutions?

A: This is no complete answer yet, but may get expanded to one in due course.
First we search for points on the curve, which is isomorphic to
$$C \colon y^2 = 2(x^6 - x^2 + 2);$$
this produces points with $x \in \{-3, -1, -4/7, 0, 4/7, 1, 3\}$ as already
mentioned in the comments. It was also mentioned that the rank of the
Mordell-Weil group of the Jacobian variety of $C$ is 3, so that we cannot
apply Chabauty's method directly. What we can try to do is to use a
covering collection plus Elliptic Curve Chabauty.
Let $K = \mathbb Q(a)$ with $a^3 - a + 2 = 0$; then
$$2(x^6 - x^2 + 2) = 2 (x^2 - a) (x^4 + a x^2 + a^2 - 1).$$
We can compute the 2-Selmer set of $C$ and find that it has three
elements that are all images of known rational points on $C$.
If my quick computation is correct, then we obtain two coverings of $C$
of the form
$$D_j \colon u^2 = \delta_j (x^2 - a), \quad
  v^2 = 2 \delta_j (x^4 + a x^2 + a^2 - 1)$$
with $\delta_1 = 1 - a$ and $\delta_2 = -a$, such that each rational
point on $C$ lifts to a $K$-point on $D_1$ or $D_2$ (with the same
$x$-coordinate). Forgetting the first
equation, we get morphisms $D_j \to E_j$, where $E_j$ is an elliptic
curve given by the second equation. We are interested in points in $E_j(K)$
whose $x$-coordinate is in $\mathbb Q$; this is the setting for
Elliptic Curve Chabauty. According to Magma, the Mordell-Weil ranks
of $E_1$ and $E_2$ over $K$ are 2 and 1, so the relevant Chabauty
condition (rank is smaller than degree of $K$) is satisfied.
It remains to actually do the computation, which right now I have no
time to do. Almost certainly the result will be that $C$ only has the
known rational points.
EDIT: I have now done the computation (with Magma), and the result
is as expected: the rational points on $C$ lifting to a $K$-rational
point on $D_1$ have $x$-coordinate in $\{-3, -1, 1, 3\}$ and the
rational points on $C$ lifting to a $K$-rational point on $D_2$ have
$x$-coordinate in $\{-4/7, 0, 4/7\}$. So there are no unknown rational
points on $C$.
Here is Magma code for the computations (it can be run in the
Magma online calculator):
P<x> := PolynomialRing(Rationals());
f := x^2*(x+1)*(x^2+1)*(x-1) + 2;
C := HyperellipticCurve(2*f);
K<a> := NumberField(x^3-x+2);
f1 := ExactQuotient(PolynomialRing(K)!f, Polynomial([-a, 0, 1]));
// compute 2-Selmer set of C
deltas, m := TwoCoverDescent(C);
A<th> := Domain(m);
// find the possible square classes of x(P)^2 - a in K, for P in C(Q)
invol := hom<A -> A | -th>;
ndeltas := [d*invol(d) where d := dd @@ m : dd in deltas];
assert Set(ndeltas) eq {1-th^2, -th^2}; // note that a = th^2, so this is {1-a, -a}
// set up the two elliptic quotients as hyperelliptic curves
D1 := HyperellipticCurve(2*(1-a)*f1);
D2 := HyperellipticCurve(2*(-a)*f1);
// find isomorphic elliptic curve, given by integral Weierstrass model
E1, D1toE1 := EllipticCurve(D1, Points(D1, 1)[1]);
E1i, toE1i := IntegralModel(E1);
// determine E1(K)
MWE1, mMWE1 := MordellWeilGroup(E1i);
P1 := ProjectiveSpace(Rationals(), 1);
// set up x-coordinate map in terms of E1i
E1itoP1 := Expand(Inverse(toE1i)*Inverse(D1toE1)*map<D1 -> P1 | [D1.1, D1.3]>);
// run Elliptic Curve Chabauty
ptsMWE1, N1 := Chabauty(map<MWE1 -> E1i | a :-> &+[Eltseq(a)[i]*mMWE1(MWE1.i) : i in [1..Ngens(MWE1)]]>, E1itoP1);
// make sure known subgroup of E1(K) is saturated at the primes dividing N1
newgens := Saturation([mMWE1(g) : g in OrderedGenerators(MWE1)], Max(PrimeDivisors(N1)));
assert newgens eq [mMWE1(g) : g in OrderedGenerators(MWE1)];
// find the x-coordinates of the points
{E1itoP1(mMWE1(pt)) : pt in ptsMWE1};
// ==> { (3 : 1), (1 : 1), (-1 : 1), (-3 : 1) }
// do the same for the other covering curve
E2 := EllipticCurve(D2, Points(D2, 0)[1]);
E2, D2toE2 := EllipticCurve(D2, Points(D2, 0)[1]);
E2i, toE2i := IntegralModel(E2);
E2itoP1 := Expand(Inverse(toE2i)*Inverse(D2toE2)*map<D2 -> P1 | [D2.1, D2.3]>);
MWE2, mMWE2 := MordellWeilGroup(E2i);
ptsMWE2, N2 := Chabauty(map<MWE2 -> E2i | a :-> &+[Eltseq(a)[i]*mMWE2(MWE2.i) : i in [1..Ngens(MWE2)]]>, E2itoP1);
newgens := Saturation([mMWE2(g) : g in OrderedGenerators(MWE2)], Max(PrimeDivisors(N2)));
assert newgens eq [mMWE2(g) : g in OrderedGenerators(MWE2)];
{E2itoP1(mMWE2(pt)) : pt in ptsMWE2};
// ==> { (0 : 1), (4/7 : 1), (-4/7 : 1) }


text:
Q: Behavior of Java Postincrementor     public static void main(String[] args) {
    int a = 1;
    int b = a++;

    System.out.println(b);
}

Why does the code above print 1? I was told that a++ means you would get the value of a. then increment it. But the code above never incremented a and just printed 1. Could someone please explain what is going on here?

A: It works as expected; Here is the code explained:
public static void main(String[] args) {
    // a is assigned the value 1
    int a = 1;
    // b is assigned the value of a (1) and THEN a is incremented.
    // b is now 1 and a is 2.
    int b = a++;

    System.out.println(b);
    // if you had printed a here it would have been 2
}

This is the same code but with pre-increment of a:
public static void main(String[] args) {
    // a is assigned the value 1
    int a = 1;
    // a is incremented (now 2) and THEN b is assigned the value of a (2)
    // b is now 2 and so is a.
    int b = ++a;

    System.out.println(b);
    // if you had printed a here it would have been 2 so is b.
}

A: int b = a++ is equivalent to int b = a; a += 1.  When you print b, a==2 && b==1

A: a++  is like saying a-then increment a by 1. So after you say b = a++, b = 1 and a = 2.
If you were to preincrement b = ++a, you would get b = 2 Preincrement increases before it assigns value.
Conclustion

a++ assign value before incrementing
  ++a increments, then assigns value.

A: The reason is is as follow.

If it is i++, then equalent code is like this.

result = i;
i = i+1;
return result

If it is ++i. then the equlent code is like this.
i=i+1;
result =i;
return i

So considering your case, even though the value of i is incremented, the returned value is old value. (Post increment)

A: Post Increment Meaning = First complete assignment then Increment.
Pre Increment Meaning = First Increment then assign .
ex:
int a=0,b;
b=a++; // ie. Step1(First complete assignment): b=0, then a++ ie a=a+1; so a=1 now.
System.out.println(b); // prints 0
System.out.println(a); // prints 1

if
int a=0,b;
b=++a; // ie. Step1(First Increment ): a++ ie a=a+1; so a=1 now, b=a , ie b=1.
System.out.println(b); // prints 1
System.out.println(a); // prints 1

redpajama_set_name: RedPajamaStackExchange


text:
Q: List all the functions of a class by order of writing How can I have a list with all the functions of a class but not alphabetically reordered ?
Because actually I have that :

[ foo.__dict__.get(a) for a in dir(foo) if isinstance(foo.__dict__.get(a), types.FunctionType) ]

And it return me a list but reordered ...
I've also tried with a decorator:

def decorator ():
    listing = []
    def wrapped (func):
        listing.append(func)
        return func
    wrapped.listing = listing
    return wrapped

That's fine but, I need to add a decorator on each function of my class ... May be you have some tricks ?

A: See inspect module docs. Function objects have  func_code attr, and (according to docs - didn't test it yet), func_code should have co_firstlineno attribute, which will be the number of the first line of code in source file.
So please try something like:
def getListOfClassFunctions(foo):
    '''foo - a class object'''
    funcList = [ foo.__dict__.get(a) for a in dir(foo) if isinstance(foo.__dict__.get(a), types.FunctionType)]
    funcList = filter(lambda x: x.func_code.co_filename == foo.__module__, funcList)  # Thanks Martijn Pieters for a hint!
    return sorted(key=lambda x: x.func_code.co_firstlineno, funcList)

Edited to wrap the whole snippet in a function and to return only functions defined in the same module as class.


text:
Q: Enforcing searching before creating I have a requirement where clients will search for customer data owned by my team and if they don't find, they can create a new customer.
For example, clients can search by organization name in a particular zip code and if they don't find any results, they create a new organization as a customer at that zip code.
We'd like to ensure our clients are strictly doing a "search" before they do a create to avoid duplicates. For this, I was thinking that we hash specific fields of the search request and return that as part of the search response. The client would have to pass this hash value for the create request and we would hash the same fields of the input and compare the hash.
The create happens only if the hashes match.
I'm not sure what this is called and what is the industry standard  for this. Please guide.
Thanks,
Arun


text:
Q: JavaScript Sort by Date on table not working Hi I cannot get sort function working on date. It changes order of the rows but it doesn't sort properly and dates are all over the place.
I would like upcoming events to future events.
See my code below.

$('tr.Entries').sort(function(a,b){
  return new Date(jQuery(a).find('td.event-date > a').text()).getTime() <
    new Date(jQuery(b).find('td.event-date > a').text()).getTime()
}).appendTo('tbody');

      Date
      Event
      Location
      Ticket

        25/08/2017

        Live N Local Winter Music Festival

        Pause Bar, Balaclava

        BUY TICKET

        15/04/2017

        Reggae, Seggae & Sega Night

        Bar Open, Fitzroy Melbourne

        BUY TICKET

        06/05/2016

        The Sunraysia Multicultural Festival

        Nowingi Place, Mildura Victoria

        BUY TICKET

Thanks!
UPDATE
I have seemed to add dates into an array then sorted them - now I just too append them back to the body? Thanks
var dates = jQuery('tr.Entries').find('td.event-date > a').map(function() {
             return jQuery(this).text();
          }).get();
dates.sort(function(a,b){
var dateA = a;
dateA = dateA.replace(/(..)\/(..)\/(....)/, '$2-$1-$3');
var dateB = b;
dateB = dateB.replace(/(..)\/(..)\/(....)/, '$2-$1-$3');

return new Date(dateA).getTime() - new Date(dateB).getTime();
});
jQuery.each(dates, function (index, value) {
     //how to append back to tbody?
     console.log(value);
});

A: new Date() doesn't know how to parse dates that have the day in the first section as opposed to the section. Date requires the format MM/DD/YYYY
If you take your first date 25/08/2017 and pass it into new Date() you will get an Invalid Date response.
If you want this to work you'll need to make sure the date is formatted into something Date understands so you can either do a swap programmatically or you can also pass in the parameters manually into the new Date function

A: Your date string is not in valid format. You can use string#replace() to change the date string to MM-DD-YYYY from DD\MM\YYYY and then covert to date and do the comparison.

$('tr.Entries').sort(function(a,b){

 var dateA = jQuery(a).find('td.event-date > a').text();
 dateA = dateA.replace(/(..)\/(..)\/(....)/, '$2-$1-$3');
 var dateB = jQuery(b).find('td.event-date > a').text();
 dateB = dateB.replace(/(..)\/(..)\/(....)/, '$2-$1-$3');

 return new Date(dateB).getTime() - new Date(dateA).getTime();;

}).appendTo('tbody');

      Date
      Event
      Location
      Ticket

        15/04/2017

        Reggae, Seggae & Sega Night

        Bar Open, Fitzroy Melbourne

        BUY TICKET

        06/05/2016

        The Sunraysia Multicultural Festival

        Nowingi Place, Mildura Victoria

        BUY TICKET

        25/08/2017

        Live N Local Winter Music Festival

        Pause Bar, Balaclava

        BUY TICKET

var dates = ['25/08/2017', '09/09/2017', '15/09/2017', '16/09/2017', '28/09/2017', '10/12/2017', '10/02/2018', '16/12/2017'];

dates.sort(function(a,b){
 var dateA = a;
 dateA = dateA.replace(/(..)\/(..)\/(....)/, '$2-$1-$3');
 var dateB = b;
 dateB = dateB.replace(/(..)\/(..)\/(....)/, '$2-$1-$3');

 return new Date(dateA).getTime() - new Date(dateB).getTime();
});

console.log(dates);


text:
Q: Propagating EF Core BaseContext to sub-classes via Dependancy Injection I've a fairly standard AspNet Core API solution which has the following in the ConfigureServices of its Startup.cs
services.AddContext<BaseContext>(Options => options.UseSqlServer(connectionString));
I can then use Dependency Injection to 'pass' the BaseContext to the controller.
What I would then like to do is use that same BaseContext in any classes that I new from methods within the controller (and then on to any classes I new from that class, and so on).
Do I need to just pass the BaseContext as a parameter to the constructor to each class (which seems a pain and means passing it to classes that don't directly need it but will just pass it on), or is it possible to pull the BaseContext out of the ServiceProvider somehow so I only have it available where it's actually needed?
I've read up on Constructor Injection etc. but I don't think they match what I'm trying to do.


text:
Q: LoadLibrary и ERROR_BAD_EXE_FORMAT Здравствуйте. Ситуация такая, нужно вызвать функцию beep из kernel32 с помощью как не удивительно loadlibrary. Сам kernel32 находится в папке с программой и имеет просто другое название (всё это, исключительно для примера подключения "типа" программной dll и работа с ней). Всё вроде-бы должно было бы идти как по маслу, но тут постоянно выскакивает ошибка в отладчике, попробовал по разному в программе прописать путь к библиотеке ("mylib","mylib.dll",""\mylib.dll"","E:\masm32\prog\mylib.dll"), но увы ни как программа не хочет конектится с dll и выводит такую ошибку:

000000C1 (ERROR_BAD_EXE_FORMAT)

Вот собственно сам код:
mov hDll, rv(LoadLibrary, chr$("E:\masm32\BugsFinder\mylib.dll"))

mov ptrInstr, rv(GetProcAddress, hDll, chr$("Beep"))

Что делать помогите пожалуйста :(
UPD:

A: Нельзя грузить из 32-битного процесса (а у вас на скрине именно он) 64-битную DLL. Грузите 32-битную DLL и будет вам счастье.


text:
Q: how to give admin password to solr admin panel I'm using solr search engine in my project. I want to protect solr's admin panel with username and password for any security issue. But I don't know how to do it. Is there any method for this?

A: You need to ask Solr to enable one of the available Authentication and Authorization plugin. Here is official doc to refer:- https://lucene.apache.org/solr/guide/8_2/authentication-and-authorization-plugins.html
One you have enabled your authentication/authorization plugins, you may also need to update all your clients to provide the required credentials(depends on type of the authentication plugin and your access control configurations).
For Example, If you have chosen Basic authentication plugin and if you are using SolrJ, you can do the following:-
SolrRequest req ;//create a new request object
req.setBasicAuthCredentials(userName, password);
solrClient.request(req);


text:
Q: Showing data in view files while sending mails Am trying to send mails to users upon registration, In view file i need to send the details submitted by users in the form. When i tried to send mails data is not getting passed. Please help me to solve out the issue
First i run the following command
php artisan make:mail WelcomeMail

After that under Mails/WelcomeMail.php i wrote following code
<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class WelcomeMail extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($user)
    {
        $this->user = $user;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        //return $this->from('xavierissac94@gmail.com')->subject('new customer registration')->view('emails.welcome');
       return $this->view('emails.welcome');
    }
}

Following is the code in my registration controller
public function storeUsers(Request $request)
{
    $this->validate($request, [
        'email' => 'required|email'
    ]);

    $postdata = $request->all();
    $user = new User;
    $hashedRandomPassword = Hash::make('password', [
        'rounds' => 12
    ]);
   $user = new User;
   $user->name=$postdata['user_name'];
   $user->email=$postdata['email'];
   $user->password= $hashedRandomPassword;
   $user->save();
    $data = array( 'email' => $postdata['email'], 'name' => $postdata['user_name'] );

    Mail::to($user->email)->send(new WelcomeMail($user));
   return back()->with('success','thanks for contacting us');
   exit(ok);
    //Mail::to($postdata['email'])->send(new WelcomeMail($user));
    return $user;
   //return redirect('users');
}

Following is the my code in view file, here am trying to get the data using {{$user['name']}}
<!DOCTYPE html>

    <title>Welcome Email</title>

Dear {{$user['name']}}

You have succesfully registerd as a valuable client of LifeLove and Other things. We are sending you a password to login.Please remeber to change your password after login.

Your Password for login is {{$user['password']}}

Kind Regards,

Team Life Love

But i am getting undefined variable  $user error. I need to send the password and usernames to user upon registration. Mails are sending succesfully but data is not passing.
Please help me

A: You're missing the public $user property in your mailable class:
class WelcomeMail extends Mailable
{
    use Queueable, SerializesModels;

    // ADD ME!!!!
    public $user;

    // ADD ME TOO!!!!
    public $password;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct($user, $password)
    {
        $this->user = $user;
        $this->password = $password;
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
       return $this->view('emails.welcome')->with(['password' => $this->password]);
    }
}

Typically, you will want to pass some data to your view that you can utilize when rendering the email's HTML. There are two ways you may make data available to your view. First, any public property defined on your mailable class will automatically be made available to the view. So, for example, you may pass data into your mailable class' constructor and set that data to public properties defined on the class

Mailable docs
You'll also need to update your mailable view file to use object accessor notation rather than array indices. For example:
// BAD

Dear {{$user['name']}}

// GOOD

Dear {{ $user->name }}


text:
Q: How to maximize function by picking rows to "median" in data frame in R? I have a number of columns in a data frame in R that are binary - all entries are either 0 or 1.  I have a function that takes the median value of each row of a data frame then runs that "median" number (also a 0 or 1) through a function and returns a value.
How I could write a function that would go through these columns and find the optimum column choices to maximize the function?


text:
Q: Question about n-simplex and its face I just started to read Elements of Algebraic Topology by Munkres and got question already. On page 5, (Let $\sigma$ be an n-simplex) since Bd $\sigma$ consists of all points $x\in\sigma$ s.t. at least one $t_i(x)=0$, and Int $\sigma$ consists of all pioints $x\in\sigma$ s.t. $t_i(x)>0, \forall i$, it follows:
Given $x\in\sigma$, then there is exactly one face $s$ of $\sigma$ s.t. $x\in$ Int $s$, for $s$ must be the face spanned by those $a_i$ for which $t_i(x)>0$.
My question is, what if $x$ is one of the vertices, say $a_0$. It is not an interior of any faces, so there can't exist a unique face s.t. x contained in the interior of that face. Or am I misunderstood something here. Can someone clarify this. Thanks!

A: Interior here means the interior with respect to the lowest-dimensional Euclidean space in which the simplex can be embedded. Technically, the standard-$n$-simplex $\Delta^n$ is the convex hull of the unit vectors $e_0,\dots,e_n$ in $\Bbb R^{n+1}$, with the subspace topology. That is
$$
\textstyle
\Delta^n = \{ (t_0,\dots,t_n) \mid t_i\ge0, \sum_i t_i = 1 \}.
$$
As this set, its interior is empty. However, $\Delta^n$ is also a subset of its affine hull
$$
\textstyle
\text{Aff}(\Delta^n) = \{ (t_0,\dots,t_n) \mid \sum_i t_i = 1 \},
$$
which is a coset of an $n$-dimensional linear subspace of $\Bbb R^{n+1}$ and thus homeomorphic to $\Bbb R^n$. Regarded as a subset of $\Bbb R^n$, $\Delta^n$'s interior is
$$
\textstyle
\mathring\Delta^n = \{ (t_0,\dots,t_n) \mid t_i>0, \sum_i t_i = 1 \}.
$$
That's why we take the interior of a simplex to be the set of all points whose every coordinate is strictly larger than $0$.
If you go down to dimension $0$, then $\Delta^0$ is the subset $\{t_0 \mid t_0=1\}$ of $\Bbb R^1$, and its affine hull is $\Delta^0$ itself, so it is open in there. And this is indeed the set of all elements of the $0$-simplex where every coordinate is $>0$.


text:
Q: I stupidly moved AppData, now I can't put the files back (Win 7) I was trying to move the AppData folder (or at least Roaming) off of my SSD so I could make a symbolic link, but I couldn't move everything due to some of the files being in use. After a restart, I have missing icons, missing desktop background, and missing settings in some programs (e.g. saved passwords in Chrome). I keep trying to move everything back, but when I restart, those moved files have been deleted.
I tried a system restore point from before the experiment, but it did not help.
I also tried changing the location of AppData/Roaming in it's Properties dialog, but the location was changed back to C drive and the Location tab was removed from its Properties even before I restarted...

A: It would probably be safer and reliable if you booted that device into ubuntu from a live cd or usbmemory stick and move the appdata folder back while the operating system is not hooked into that folder.
Just make sure you have a backup of that data and the file system has been checked for errors first otherwise you could run into a problem trying to mount the file system in ubuntu and incur file corruption.
P.S I dont know how well a symbolic link will work with an appdata folder its dependent on a direct file structure

A: I was able to kind of "lock the files in place" once I moved them back by creating a new System Restore Point before restarting.
(I also found the main source of disk space usage in AppData for me: Adobe's Media Cache. I could have sworn I set it up to put those somewhere else, but at least now I can fix it without messing with /AppData or any other Windows file structure...)


text:
Q: Why does the evaluation of "Catch[Break[],\$Failed]" not return "\$Failed"? Under normal conditions, evaluating something that emits a Message eg the evaluation of
1/0

that produces a Message Power::infy with text

Power: Infinite expression 1/0 encountered.

can be dealt with an expression like
Quiet[Check[1/0, $Failed]]

which returns $Failed and invokes no Message.
When evaluating Break[] 'naked' (outside any flow control loop) the front end issues a message Break::nofwd with a text

Break: No enclosing For, While, or Do found for Break[]

and returns
Hold[Break[]]

I was expecting that after evaluating
Quiet[Check[Break[],$Failed]]

I'd obtain $Failed (without any messages generated in the process).
Instead, I get the same message Break::nofwd as before and the same output as before ie Hold[Break[]].
It is as if Check doesn't do anything when Break is its first argument.
Could someone please explain why I get this counter-intuitive result?
PS. I'm trying to pass Break[] or a function that has Break[] in its body as an argument to another function with a While loop in its body. The former function would ideally force the later function to exit the loop without any messages.
f[___]:=Break[]
SetAttributes[g, HoldAll]
g[func_] := Module[{res = Quiet[Check[func, $Failed]], j = 0},
  While[
    FailureQ[res] && j < 10,
    res = Quiet[Check[func, $Failed]];
    j++
  ];
  j
 ]

Evaluating g[f[]] returns the familiar Break::nofwd and returns Hold[Break[]]; I understand that this happens because res = Quiet[Check[func, $Failed]] gets evaluated during the initialization of Module.


text:
Q: Возможно ли определить на устройстве программно включен ли режим разработчика? Подскажите, пожалуйста, есть ли возможно программно, с помощью приложения, определить включен ли режим разработчика на устройстве или нет?
Например какой нибудь запрос возвращающий булевую переменную похожий на android.os.Build.devModeEnable()?

A: пробуй это
int adb = Settings.Secure.getInt(this.getContentResolver(),
                Settings.Global.DEVELOPMENT_SETTINGS_ENABLED , 0);

для API 16 можешь юзать так: Settings.Secure.DEVELOPMENT_SETTINGS_ENABLED
статьи одна  и вторая


text:
Q: How to force chrome to open links in system browser I'm running a 'desktop web app' for Fastmail and for reasons that I can't recall, I could only get this to run in Google Chrome (chromium or FF didn't work).
Unfortunately this means that any links I click in my email open in a new Fastmail app window (a normal tabbed Google Chrome window), instead of opening in my preferred Firefox, which is set as the default browser.
Is there any way around this?
Here's the desktop entry, SingleMainWindow doesn't appear to have any effect:
[Desktop Entry]
Version=1.0
Terminal=false
Type=Application
Name=FastMail
Exec=/opt/google/chrome-unstable/chrome --disable-extensions --force-device-scale-factor=2 --app=https://www.fastmail.com/mail/Inbox/
TryExec=/opt/google/chrome-unstable/chrome
Icon=~/.local/share/applications/fastmail-icon.svg
StartupWMClass=www.fastmail.com__mail_Inbox
X-Desktop-File-Install-Version=0.23
SingleMainWindow=true


text:
Q: What do you thing about "In France, there is a Chinese proverb that says ..."? What do you think about:

In France, there is a Chinese proverb that says "..."?

Is it just a joke or something serious?

A: If there is a Chinese Proverb that is only used by the subgroup of chinese speakers in france, this could be totally serious.
Otherwise, at least in Germany I know people saying "Old chinese proverb!" jokingly, often for some kind of common sense-based proverb-like thing they just made up.


text:
Q: How to get style sheet property value by webdriver? I want to know whether content menu of drop down is displayed or none. I want to click on that menu if it's display none. and keep as it is if blocked. the property value is like this:
div id="section_content_23" class="thread-content" style="display: none;" i have xpath of title is like ex 'section_title_23'. i just want to know the style is  "display: none;" or style = "display: blocked";
I have write code for this like:
else if (str.contains("section_title_"))
            {
            //String xpath;
            String[] retval = str.split("_", 3);
            String no = retval[2];
        //

            displaylinkhandler = QuickCap.driver.findElement(By.id("section_content_" + no)).getAttribute("style");

            //displaylinkhandler = QuickCap.driver.findElement(By.id("section_content_" + no)).getAttribute("section_content_"+no);
            //displaylinkhandler = QuickCap.driver.findElement(By.xpath(xpath)).getText();
            //boolean show = displaylinkhandler.contains("display: none;");
            if(displaylinkhandler == null){
                QuickCap.driver.findElement(By.xpath(str)).click();
            }
            indexBoolean = TitleCheck.validate();

        }

here str is xpath & displaylinkhandler is like string.
Thanks in advance.

A: did you tried getCssValue from webelement.
for instance: ele.getCssValue("propname")
By the way to check element is displayed or not you should user isDisplayed method of webelement

A: In webdriver we use
WebElement element = driver.findElement(By.name("elementName"));

and then
String attributeValue = element.getAttribute("attributeName");

So in your case it will
String styleValue = element.getAttribute("style");


text:
Q: summations with unusual notation,as interpreted? I have seen here and in many places summations that do not follow a standard notation, I put some of them below:
For example how to interpret these.
Some bibliography with this type of notation? I can't find anything other than usual

A: The first does not appear to be a sum at all unless interpreted as on the right. The others also appear to be coded by people without a strong background in standard notation.
These are just educated guesses about what the coders intended.
\begin{align*}
\sum_{\large{r_1+r_2+\cdots+r_n = t,\space r_k \in\mathbb{N}}}
\frac{t!}{r_1!r_2!\cdots r_n!}
\\ \longrightarrow\space
\sum_{\Large{t=r_1}}^{\Large{r_n,\space  r_k\in\mathbb{N}}}
\frac{t!}{r_1!r_2!\cdots r_n!}
\end{align*}
\begin{align*}
\sum_{\large{1<t<k\le n}}
\ln\left(\ln\left(\sqrt[\huge{n}]{\frac{3n-2k}{3n+2k}}\right)\right)
\\\longrightarrow\space
\sum_{\large{k>t>1}}^{\Large{n}}
\ln\left(\ln\left(\sqrt[\huge{n}]{\frac{3n-2k}{3n+2k}}\right)\right)
\end{align*}
\begin{align*}
\sum_{\large{k\ge0} }
(tk)^{k-1}\frac{z^k}{k!}
\quad\longrightarrow\quad
\sum_{\large{k=0} }^{\Large{\infty}}
(tk)^{k-1}\frac{z^k}{k!}
\end{align*}
\begin{align*}
\sum_{\large{d|n}} g(d)
\quad\longrightarrow\quad
\sum_{\large{\frac{n}{d}=1}}^{\Large{\infty},
\space \frac{n}{d}\in\mathbb{N}}
\space
g(d)
\end{align*}


text:
Q: What is the "horseshoe effect" and/or the "arch effect" in PCA / correspondence analysis? There are many techniques in ecological statistics for exploratory data analysis of multidimensional data.  These are called 'ordination' techniques.  Many are the same or closely related to common techniques elsewhere in statistics.  Perhaps the prototypical example would be principal components analysis (PCA).  Ecologists might use PCA, and related techniques, to explore 'gradients' (I am not entirely clear what a gradient is, but I've been reading a little bit about it.)
On this page, the last item under Principal Components Analysis (PCA) reads:

*

*PCA has a serious problem for vegetation data: the horseshoe effect. This is caused by the curvilinearity of species distributions along gradients. Since species response curves are typically unimodal (i.e. very strongly curvilinear), horseshoe effects are common.

Further down the page, under Correspondence Analysis or Reciprocal Averaging (RA), it refers to "the arch effect":

*

*RA has a problem: the arch effect. It is also caused by nonlinearity of distributions along gradients.

*The arch is not as serious as the horseshoe effect of PCA, because the ends of the gradient are not convoluted.

Can someone explain this?  I have recently seen this phenomenon in plots that re-represent data in a lower dimensional space (viz., correspondence analysis and factor analysis).

*

*What would a "gradient" correspond to more generally (i.e., in a non-ecological context)?

*If this happens with your data, is it a "problem" ("serious problem")?  For what?

*How should one interpret output where a horseshoe / arch shows up?

*Does a remedy need to be applied?  What?  Would transformations of the original data help?  What if the data are ordinal ratings?

The answers may exist in other pages on that site (e.g., for PCA, CA, and DCA).  I have been trying to work through those.  But the discussions are couched in sufficiently unfamiliar ecological terminology and examples that it is harder to understand the issue.

A: Q1
Ecologists talk of gradients all the time. There are lots of kinds of gradients, but it may be best to think of them as some combination of whatever variable(s) you want or are important for the response. So a gradient could be time, or space, or soil acidity, or nutrients, or something more complex such as a linear combination of a range of variables required by the response in some way.
We talk about gradients because we observe species in space or time and a whole host of things vary with that space or time.
Q2
I have come to the conclusion that in many cases the horseshoe in PCA is not a serious problem if you understand how it arises and don't do silly things like take PC1 when the "gradient" is actually represented by PC1 and PC2 (well it is also split into higher PCs too, but hopefully a 2-d representation is OK).
In CA I guess I think the same (now having been forced to think a bit about it). The solution can form an arch when there is no strong 2nd dimension in the data such that a folded version of the first axis, which satisfies the orthogonality requirement of the CA axes, explains more "inertia" than another direction in the data. This may be more serious as this is made up structure where with PCA the arch is just a way to represent species abundances at sites along a single dominant gradient.
I've never quite understood why people worry so much about the wrong ordering along PC1 with a strong horseshoe. I would counter that you shouldn't take just PC1 in such cases, and then the problem goes away; the pairs of coordinates on PC1 and PC2 get rid of the reversals on any one of those two axes.
Q3
If I saw the horseshoe in a PCA biplot, I would interpret the data as having a single dominant gradient or direction of variation.
If I saw the arch, I would probably conclude the same, but I would be very wary of trying to explain CA axis 2 at all.
I would not apply DCA - it just twists the arch away (in the best circumstances) such that you don't see to oddities in 2-d plots, but in many cases it produces other spurious structures such as diamonds or trumpet shapes to the arrangement of samples in the DCA space. For example:
library("vegan")
data(BCI)
plot(decorana(BCI), display = "sites", type = "p") ## does DCA

We see a typical fanning out of sample points towards the left of the plot.
Q4
I would suggest that the answer to this question depends on the aims of your analysis. If the arch/horseshoe was due to a single dominant gradient, then rather than have to represent this as $m$ PCA axes, it would be beneficial if we could estimate a single variable that represents the positions of sites/samples along the gradient.
This would suggest finding a nonlinear direction in the high-dimensional space of the data. One such method is the principal curve of Hastie & Stuezel, but other non-linear manifold methods are available which might suffice.
For example, for some pathological data

We see a strong horseshoe. The principal curve tries to recover this underlying gradient or arrangement/ordering of samples via a smooth curve in the m dimensions of the data. The figure below shows how the iterative algorithm converges on something approximating the underlying gradient. (I think it wanders away from the data at the top of the plot so as to be closer to the data in higher dimensions, and partly because of the self-consistency criterion for a curve to be declared a principal curve.)

I have more details including code on my blog post from which I took those images. But the main point here is the the principal curves easily recovers the known ordering of samples whereas PC1 or PC2 on its own does not.
In the PCA case, it is common to apply transformations in ecology. Popular transformations are those that can be thought of returning some non-Euclidean distance when the Euclidean distance is computed on the transformed data. For example, the Hellinger distance is
$$D_{\mathrm{Hellinger}}(x1, x2) = \sqrt{\sum_{j=1}^p \left [ \sqrt{\frac{y_{1j}}{y_{1+}}} - \sqrt{\frac{y_{2j}}{y_{2+}}} \right ]^2}$$
Where $y_{ij}$ is the abundance of the $j$th species in sample $i$, $y_{i+}$ is the sum of the abundances of all species in the $i$th sample. If we convert the data to proportions and apply a square-root transformation, then the Euclidean distance-preserving PCA will represent the Hellinger distances in the original data.
The horseshoe has been known and studied for a long time in ecology; some of the early literature (plus a more modern look) is

*

*Goodall D.W. et al. (1954) Objective methods for the classification of vegetation. III. An essay in the use of factor analysis. Australian Journal of Botany 2, 304–324.

*Noy-Meir I. & Austin M.P. et al. (1970) Principal Component Ordination and Simulated Vegetational Data. Ecology 51, 551–552.

*Podani J. & Miklós I. et al. (2002) Resemblance Coefficients and the Horseshoe Effect in Principal Coordinates Analysis. Ecology 83, 3331–3343.

*Swan J.M.A. et al. (1970) An Examination of Some Ordination Problems By Use of Simulated Vegetational Data. Ecology 51, 89–102.

The main principal curve references are

*

*De'ath G. et al. (1999) Principal Curves: a new technique for indirect and direct gradient analysis. Ecology 80, 2237–2253.

*Hastie T. & Stuetzle W. et al. (1989) Principal Curves. Journal of the American Statistical Association 84, 502–516.

With the former being a very ecological presentation.


text:
Q: Whats the best way to implement global constants in java between multiple public classes? I've just started learning Java after getting the hang of C++, and I'm wondering if there is a way that I can have global constants the same way in C you can have a Header file with a list of constants that you can just include in any class files that need to use them. Right now, in my Java project, I am achieving this effect by using a Java interface with the constants defined as final variables.
public interface Constants {
    public int constant1 = 36;
    public String projectName = "Project Name";
    public float ratio = 4.716f;
    // ... more parameters
}

To access them in my class files that they are used in, I just use the implements keyword in the class files.
public class Class1 implements Constants {
    // Members
    // ...
    // Methods
    // ...
}

It's not that this isn't working, I'm just wondering if this is the best way to get this effect. I'm not formally trained in Java, I'm just teaching myself from some books I've gotten and online forums. I've looked around and I haven't found much discussion on this specific topic, more just about declaring constants within classes, so I'm just trying to figure out from some more experienced Java programmers with formal training if there is a more standard/conventional way to do this. Any advice would be helpful, thank you!

A: Usually constants placed in a subject-related class as a class field. Here are examples from Java's Math class and Android's View
public final class Math {
    public static final double PI = 3.14159265358979323846;

public class View
    public static final int VISIBLE = 0x00000000;
    public static final int INVISIBLE = 0x00000004;

Then they can be used in any other classes with the class name prefixed or statically imported
double radius = 2 * r * Math.PI;

import static android.view.View.VISIBLE;
view.setVisibility(VISIBLE);

Interface constants is an anti-pattern and should be avoided. I'm not very experienced Java developer but haven't seen so far a class specifically dedicated to hold constants (except when dealing with resource bundles like Android's R classes).

Besides that, Java provides such a functionality as enums. There is the Item 34 Use enums instead of int constants in Effective Java by Joshua Bloch who is a designer and implementer of numerous Java platform features. So cannot add something new to this topic.

A: Create separate class like below
public final class Constants{
    public static final int CONSTANT_1 = 36;
    public static final String PROJECT_NAME = "Project Name";
}

Use like below in the code
 Constants.CONSTANT_1;


text:
Q: Spring data Mongo. Spatial Queries with @Query I am using a query in the repo.
findByStatusAndLocPtNear(String status, Point loc1, Distance dist1)

*

*How can I write this query with @Query annotation ?

*How can I  add another clause: findByStatusAndLocPtNear And name starts with A or B ? Is it possible to have AND and OR both in the method name ?


text:
Q: PHP decision making based on MySQL query output I would like to use a query output in if statement in MySQL. Script should run a query, which counts specified rows in database table and depends on this number make decision, which another query should run which parameters.
A sample query, which gives back a number:
SELECT count(case when studentid='$studentid' AND classid='$classid' AND endsig is NULL then 1 end) as p
FROM signature

How can I handle query output p variable in PHP script or use it up in if statements?

A: Take a look at mysql_result() function.

A: You could reformat it to:
$q = mysqli_query($conn, "SELECT * FROM signature WHERE studentid='$studentid' AND classid'$classid' AND endsig is NULL");
$p = mysqli_num_rows($q);

Then you can use $p as your number, for instance
if($p == 1) {
    echo "Hello World!";
}


text:
Q: Perform action in android app via Google Assistant I am developing a video Streaming android app. I want to play/pause the video using the Google Assistant. Like if user tells the google assistant to pause the video, i want to perform that action in my app.
I have read Google Assistant documents. There was options to have a conversation within the Google Assistant using DialogFlow and Action SDk. But there was nothing that can peroform any action in my app.
is there any way of do it.


text:
Q: Legend; text/description before key/colour? By default MATLAB puts the text part of a legend entry after the sample of what is used in the plot. Is there any way to reverse this? For example, using the below code the first entry in the legend is a dark blue rectangle followed by the text I'm; I'd like it to be the other way around (i.e. the text I'm followed by a dark blue rectangle). I am using R2017b
Example code:
test_values = [ 12, 232, 22, 44, 67, 72, 123, 35, 98 ];
test_text   = [ "I'm", "sorry", "Dave", "I'm", "afraid", "I", "can't", "do", "that" ];

Pie = pie( test_values );

legend( test_text );

A: Here is another option using some undocumented features:
test_values = [ 12, 232, 22, 44, 67, 72, 123, 35, 98 ];
test_text   = {'I''m'; 'sorry'; 'Dave'; 'I''m';'afraid';'I';'can''t';'do';'that'};
Pie = pie( test_values );
leg = legend(test_text,'Location','eastoutside');
drawnow % without this you can't accsses the legend entries
icons = [leg.EntryContainer.NodeChildren.Icon]; % an array with all the legend icons
leg.ItemTokenSize(1) = 0; % set the relative position of the text in the legend to x=0

% the following will probably need some fine tuning for a specific
% figure. It shifts the icons positions horizontally (i.e. only the first
% row has values other than zeros):
shift = [10    10     17     17
         0     0     0     0
         0     0     0     0];
for k = 1:numel(icons)
    % move the icon (patch) border:
    icons(k).Transform.Children.Children(1).VertexData = ...
    icons(k).Transform.Children.Children(1).VertexData+shift;
    % move the icon (patch) fill:
    icons(k).Transform.Children.Children(2).VertexData = ...
    icons(k).Transform.Children.Children(2).VertexData+shift;
end

% the following will probably need some fine tuning for a specific
% figure. It expands the legend box horizontally:
shift = [0    0     1     1
         0     0     0     0
         0     0     0     0];
leg.BoxEdge.VertexData = leg.BoxEdge.VertexData+shift; % the box border
leg.BoxFace.VertexData = leg.BoxFace.VertexData+shift; % the box face

A: I don't think it is possible, but you can workaround to get there if you give legend empty text and then display text outside, something like this:
figure;
Pie = pie( test_values );
emptyLegend = repmat({''},9,1);
h = legend( emptyLegend );
text(repmat(0.8,9,1),[0.8:-0.1:0]',test_text)
set(h,'Position',[0.9 0.5 0.05 0.35])

A: This is an alternative solution based on the approach used by EBH in his solution.
I hope it will not be considered a plagiarism, in case I apologise, please, put a comment and I'll delete my answer.
The solution I propose does not use any undocumented feature and has been tested on R2015b; I do not know if it will work on later Releases.
The idea is:

*

*call the legend function by requiring all the output paramentes

*work on the second output parameter

*the first half of data in this parameter are the ones of the text of the legend

*the second half are the adta of the patch of the legend (the boxes)

*loop over this parameter

*Get the original position of the text item

*Get the original coordinated of the Vertices of the patch

*Set the position of the text to the original coordinate of the first X of the patch

*Set the "X" coordinates of the patch to the original "X" position of the text and scale it

The last step contains a drawbak, because it requires to scale the size of the patchs to hold them inside the legend box.
Also, I've modified the definition of the text of the legend since R2015b does not handle the string as per in the question.
test_values = [ 12, 232, 22, 44, 67, 72, 123, 35, 98 ];
test_text   = { 'I''m', 'sorry', 'Dave', 'I''m', 'afraid', 'I' 'can''t', 'do', 'that' };

Pie = pie( test_values );
% get all the output from the legend function
[lgd,icons,plots,txt]=legend( test_text );
% Get the number of elements in the legend
n_items=length(icons)/2
% Loop over the legend's items
for i=1:n_items
   % Get the original position of the text item
   orig_txt=icons(i).Position
   % Get the original coordinated of the Vertices of the patch
   orig_mark=icons(i+n_items).Vertices
   % Set the position of the text to the original coordinate of the first
   % "X" of the patch
   icons(i).Position=[orig_mark(1) orig_txt(2)]
   % Set the "X" coordinates of the patch to the original "X" position of
   % the text and scale it
   icons(i+n_items).Vertices(:,1)=icons(i+n_items).Vertices(:,1)+orig_txt(1)*.7
end


text: Q: React development with multiple .env files I have a ReactJs application that was created using Create-React-App and I am looking for an option to work with multiple .env files with custom environment variables for various environments, like env.local, env.qa, env.development, env.stage, and env.production. I understand how to use env-cmd (which seems like the widely suggested solution for my case). However, it has not been updated in a long while and I am not too certain if that is an ideal choice for my case now. Can anyone please suggest an alternative or advise on this regard? Thank you.


text:
Q: jqGrid PHP Suite: how to get last inserted id we are using jqGrid Suite PHP from Guriddo.
I'm using authomatic add feature, using form editing.
After the add operation I would need to get the last inserted id of the record to use it to perform an insert in another table.
If I understood well, looking at some other posts, the following code works only if I disable authomatic CRUD, and I perform manual add:
$lastpid = jqGridDB::lastInsertId($conn, 'qb_profiles', 'ProfileId', 'mysql');

Instead is there any way to get the last inserted id, using authomatic add feature by integrated form?
kind regards,
Matt


text:
Q: mapping a texture on a square (Android) Im new to openGL, and im trying to map an texture to a square. I followed NeHe's tutorial on texture mapping here:
http://insanitydesign.com/wp/wp-content/uploads/lesson06.zip
Right now i see my image...but its not mapping correctly. Heres the original image:
http://ge.tt/2FzsdIx
...and heres what im seeing.
http://ge.tt/6y3cdIu
I used the vertices and texture arrays from this great iphone tutorial (link below) so im hoping they have been mapped correctly. Below is the link to my code in Square.java, thanks!
public class Square {
// Our vertices.
private float vertices[] = {
          -1.0f,  1.0f, 0.0f,  // 0, Top Left
          -1.0f, -1.0f, 0.0f,  // 1, Bottom Left
           1.0f, -1.0f, 0.0f,  // 2, Bottom Right
           1.0f,  1.0f, 0.0f,  // 3, Top Right
    };

// The order we like to connect them.
private short[] indices = { 0, 1, 2, 0, 2, 3 };

// Our vertex buffer.
private FloatBuffer vertexBuffer;

// Our index buffer.
private ShortBuffer indexBuffer;

/** The buffer holding the texture coordinates */
private FloatBuffer textureBuffer;

//the texture pointer, holds the texture name which is actually a number.
private int[] textures = new int[1];

public Square() {
    // a float is 4 bytes, therefore we multiply the number if
    // vertices with 4.
    ByteBuffer vbb = ByteBuffer.allocateDirect(vertices.length * 4);
    vbb.order(ByteOrder.nativeOrder());
    vertexBuffer = vbb.asFloatBuffer();
    vertexBuffer.put(vertices);
    vertexBuffer.position(0);

    // short is 2 bytes, therefore we multiply the number if
    // vertices with 2.
    ByteBuffer ibb = ByteBuffer.allocateDirect(indices.length * 2);
    ibb.order(ByteOrder.nativeOrder());
    indexBuffer = ibb.asShortBuffer();
    indexBuffer.put(indices);
    indexBuffer.position(0);

    //plot our texture
    float textCoords[]={
            //Mapping coordinates for the vertices
            0.0f, 1.0f,
            1.0f, 1.0f,
            0.0f, 0.0f,
            1.0f, 0.0f

                                };
    ByteBuffer tbb = ByteBuffer.allocateDirect(textCoords.length * 4); tbb.order(ByteOrder.nativeOrder());
    textureBuffer = tbb.asFloatBuffer(); textureBuffer.put(textCoords);
    textureBuffer.position(0);

}

//load our texture(s)
static void loadTexture(GL10 gl, Context context, int resource) {
    Bitmap bmp = BitmapFactory.decodeResource(context.getResources(),resource);
    GLUtils.texImage2D(GL10.GL_TEXTURE_2D, 0, bmp, 0);
    gl.glTexParameterx(GL10.GL_TEXTURE_2D,
    GL10.GL_TEXTURE_MIN_FILTER, GL10.GL_LINEAR);
    gl.glTexParameterx(GL10.GL_TEXTURE_2D,
    GL10.GL_TEXTURE_MAG_FILTER, GL10.GL_LINEAR);
    bmp.recycle();
}

/**
 * This function draws our square on screen.
 * @param gl
 */
public void draw(GL10 gl) {
    //use our textures
    gl.glEnable(GL10.GL_TEXTURE_2D); // workaround bug 3623
    gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, textureBuffer);

    // Counter-clockwise winding.
    gl.glFrontFace(GL10.GL_CCW); // OpenGL docs
    // Enable face culling.
    gl.glEnable(GL10.GL_CULL_FACE); // OpenGL docs
    // What faces to remove with the face culling.
    gl.glCullFace(GL10.GL_BACK); // OpenGL docs

    // Enabled the vertices buffer for writing and to be used during
    // rendering.
    gl.glEnableClientState(GL10.GL_VERTEX_ARRAY);// OpenGL docs.
    // Specifies the location and data format of an array of vertex
    // coordinates to use when rendering.
    gl.glVertexPointer(3, GL10.GL_FLOAT, 0, // OpenGL docs
                             vertexBuffer);

    gl.glDrawElements(GL10.GL_TRIANGLES, indices.length,// OpenGL docs
              GL10.GL_UNSIGNED_SHORT, indexBuffer);

    // Disable the vertices buffer.
    gl.glDisableClientState(GL10.GL_VERTEX_ARRAY); // OpenGL docs
    // Disable face culling.
    gl.glDisable(GL10.GL_CULL_FACE); // OpenGL docs

    }

}

iPhone tutorial:
http://www.iphonemobilephones.com/opengl-es-from-the-ground-up-part-6-textures-and-texture-mapping.html

A: You can draw faster using a triangle fan, in the following order in your indices, faster.
01
32

Then you don't need to use drawElements or indices, you can just feed it to drawArrays and only need 4 elements.
Your bug is that the , the tex coords are wrong
tl is 0,0
bl is 0,1
br is 1,1
tr is 1,0

You have
        0.0f, 1.0f,
        1.0f, 1.0f,
        0.0f, 0.0f,
        1.0f, 0.0f

So your UV is wrong.

A: Normally the rendering of a square in OpenGL looks something like this
gl.glLoadIdentity();
gl.glBindTexture(GL.GL_TEXTURE_2D,0);
gl.glBegin(GL_QUADS)
   glVertex(x,y,z);
   glTexcoord2f(s,t);
   glVertex(-x,y,z);
   glTexcoord2f(-s,t);
   glVertex(-x,-y,z);
   glTexcoord2f(-s,-t);
   glVertex(x,-y,z);
   glTexcoord2f(s,-t);
gl.glEnd();

I don't see anything like that, but I have never done GLES on Android before so I may be too old.
see https://github.com/ChrisLundquist/Asteroids/blob/master/src/ScenePanel.java#L277


text:
Q: modified .htaccess file doesn't work with BrowserMatchNoCase The servers (Ubuntu Server) it's going down because a 360Spider it's running too many request per seconds, I am trying to resolve this using this configuration in the .htaccess file:
BrowserMatchNoCase "360Spider" bots
BrowserMatchNoCase ^360Spider bots

Order Allow,Deny
Allow from ALL
Deny from env=bots

And works partially because the error.log logs some of this events:
[Sun Jul 20 23:30:15 2014] [error] [client 10.183.200.5] client denied by server configuration: /var/www/view, referer: http://www.mysite.org/

But the access.log it's still saving information about the 360Spider:
10.183.200.5 - - [20/Jul/2014:23:31:33 -0400] "GET /view/article/154967 HTTP/1.1" 403 536 "http://www.mysite.org/view/article/154967/" "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0); 360Spider"

I want to block all that have the word 360Spider.
PD: I can't block the bot using the ip because all the traffic come with the same ip. I just can work with the .htaccess file.

A: Any IP Address, or bot going to a url/website will most likely make a GET request — Apache logs it. Just because you see it in the log does not mean it isn't blocked; Your access.log clearly shows that it is.
When the bot tried to GET /view/article/154967 it was denied (403 Forbidden).


text:
Q: Laravel Eloquent, how do I start listing data from the middle of a result set? I have a table (model name: Data):
Id  Data1  Data2
1   A      ...
2   B      ...
3   C      ...
...
...
...
24  X      ...
25  Y      ...
26  Z      ...

And a query in Eloquent to retrieve the data:
$datum = Data::orderBy("data1")->paginate(10);

Right now the query always starts at the top with "A" and goes through all 3 pages to "Z", which is fine when the user initially hits the screen.  If the user edits id=15 data1="o", how do I restart the list At id 15 or page 2 instead of going back to the top of the list?

A: You can use fourth parameter
$datum = Data::orderBy("data1")->paginate(10, ['*'], 'page', 2);

2 - page number

A: I would suggest using the skip/take Laravel methods:
Quick answer:
$count = 26;
$skip = 15;
$limit = $count - $skip;
$datum = Data::orderBy("data1")->skip($skip)->take($limit)->get();

Explanation:
1) First, count the rows:
$count = Data::count();
// OR
$count = 26; // In your case (alphabet letters) you can set $count directly to 26

2) Then set a number of rows to skip (or get it from the query parameters, so users can edit a form)
$skip = 15;
// OR
$skip = $request->input('id'); // get it from a query parameter set by the user

3) Calculate the amount of rows remaining (all the ones that you are going to fetch)
$limit = $count - $skip;

4) Finally, collect the data, skipping the 15 first ones
$datum = Data::orderBy("data1")->skip($skip)->take($limit)->get();
// be aware that you can not paginate when using skip/take

A: According to Laravel Documentation you can use page query string in your URL to point on a specific page.

A: Thank you to Dry7, Giorgio.dev and PhilMarc.  You all gave me a piece of the answer.  The final solution is going to be a lot more complex.  This is due to changes to the page calculation because of sort order for the table (any of four columns) and how many records I'm filtering out (any of three columns).  In addition to clearing the filter if a new or edited record falls outside the filter.  The latest copy of the table and my code (which let me keep the paging provided by Laravel) is as follows;
mysql> show columns from mailing_classes;
+--------------------+---------------------+------+-----+---------+----------------+
| Field              | Type                | Null | Key | Default | Extra          |
+--------------------+---------------------+------+-----+---------+----------------+
| id                 | bigint(20) unsigned | NO   | PRI | NULL    | auto_increment |
| mailing_class_code | char(2)             | NO   | UNI | NULL    |                |
| description        | varchar(255)        | NO   |     | NULL    |                |
| created_by_id      | bigint(20) unsigned | NO   | MUL | NULL    |                |
| last_editted_by_id | bigint(20) unsigned | NO   | MUL | NULL    |                |
| created_at         | timestamp           | YES  |     | NULL    |                |
| updated_at         | timestamp           | YES  |     | NULL    |                |
+--------------------+---------------------+------+-----+---------+----------------+

public function index()
{

    $mailingClassSortOrder = session('mailingClassSortOrder');
    $mailingClassRestartValue = session('mailingClassRestartValue');
    $mailingClassSearchLeft = session('mailingClassSearchLeft');
    $mailingClassSearchRight = session('mailingClassSearchRight');
    $rows = 1;
    $page = 0;
    $restart = 0;
    $mcCode = '';
    $mcDescription = '';
    $mcUpdatedAt = '';

    if ($mailingClassRestartValue > 0) {
        $restartRows = MailingClass::where('id', '=', $mailingClassRestartValue)->get();
        foreach ($restartRows as $restartRow) {
            $mcCode = $restartRow->mailing_class_code;
            $mcDescription = $restartRow->description;
        }
        // if restart value does not appear in the filter then clear the filter
        // {deleted for sake of space}
        // find row position based on sort order
        if ($mailingClassSortOrder === "mailing_class_code") {
            // sorted by mailing_class_code column
            $rows = MailingClass::where('mailing_class_code', '<=', $restartRow->mailing_class_code)->count();
        } elseif ($mailingClassSortOrder === "id") {
            // sorted by id column
            $rows = MailingClass::where('id', '<=', $restartRow->id)->count();
        } elseif ($mailingClassSortOrder === "description") {
            // sorted by description column
            $rows = MailingClass::where('description', '<=', $restartRow->description)->count();
        } elseif ($mailingClassSortOrder === "updated_at") {
            // sorted by updated_at column
            $rows = MailingClass::where('updated_at', '<=', $restartRow->updated_at)->count();
        }
    }
    // calculate what should be the current page
    $page = intval($rows / 10) + 1;

    $searchText = '';
    $mailingClasses = [];
    if ($mailingClassSearchLeft === '') {
        if ($mailingClassRestartValue <= 0) {
            $mailingClasses = MailingClass::orderBy($mailingClassSortOrder)->paginate(10);
        } else {
            $mailingClasses = MailingClass::orderBy($mailingClassSortOrder)->paginate(10, ['*'], 'page', $page);
        }

    } elseif ($mailingClassSearchLeft === 'id') {
        // {deleted for sake of space}
    } elseif ($mailingClassSearchLeft === 'mailing_class_code') {
        // {deleted for sake of space}
    } elseif (session('mailingClassSearchLeft') === 'mailing_class_description') {
        // {deleted for sake of space}
    } else {
        // {deleted for sake of space}
    }

    return view(
        'maintenance.mailingclass.index',
        compact('mailingClasses', 'mmsGlobal', 'searchText')
    );
}

I took out a lot of code that had to do with creating filters to try and make it as concise.  Hope I didn't delete too much.  Now the question is how do I optimize it.


text:
Q: Send window to back when activated I found the answer to this question in here.
that solution works great when you call the method just once (don't call it from the event window activated). I am creating a gadget and I want the window to always be in the back. if the user clicks on the gadget I don't want it to come to the front which is the default behavior of windows. so what I did in order to solve that problem was to create this event:
    private void Window_Activated(object sender, EventArgs e)
    {
        SendWpfWindowBack(this);
    }

so every time the window is activate it call the method founded on the first link that I provided. the problem is that the system tray gets sent to the back. let me show you what I mean.
that is my gadget on visual studio.

when I run it it get's sent to the back: (I open notepad and outlook to illustrate my point)

now when I click on it the event window_Activated fires and it gets send to the back:

But note how the system tray (windows start up menu window) get's sent to the back!!!!
it still is behind everything exept the most important window wich is the windows start up menu. How can I resolve this. why is it going in front of the system tray !?

A: After 2 hours of stubbornness I figured it out... Since the window was so big for some reason that happen (gadget was bigger than entire desktop). I made it smaller and it worked.


text:
Q: How to pass system properties to gradle tests with kotlin DSL I am trying to pass system properties to my gradle tests. With standard gradle, I would use
test {
    //... Other configurations ...
    systemProperties = System.properties
}

With kotlin DSL, this won't run:
tasks.withType<Test> {
    useJUnitPlatform()
    options {
        systemProperties(System.getProperties())
    }
}

The problem is that properties is HashTable and expected type is Map<String, String>.
Right now, I use following workaround:
tasks.withType<Test> {
    useJUnitPlatform()
    val props = mutableMapOf<String, String>()
    System.getProperties().forEach {
        val key = it.key
        val value = it.value

        if (key is String && value is String) {
            props[key] = value
        }
    }
    options {
        systemProperties(props)
    }
}

Any clue? Thank you.

A: This works for me:
systemProperties = System.getProperties().map { e -> Pair(e.key as String, e.value) }.toMap()

To pass a single system property:
systemProperty("property.name", System.getProperty("property.name"))


text:
Q: How can I pass data from nested JSON parsed in an each function within an each function? So I'm trying to parse some nested json and the way I'm trying to access it is confusing me on how I can add it back to its own individual 'item'.  Each item contains an image, a caption, and possibly tags.  The image source and caption are nested on the same level together so they can be accessed within the same each function, however the tags object (which is also on the same level as the image source and caption) includes an array, that needs to be accessed using a second each function to get each tag.  I'm able to parse each tag using the following code, but I'm not sure how I can pass the tags object data back to the initial each function.  Any help would be greatly appreciated!
JSON Structure:

{
"data": [
  {
     "source": "http://example.com/picture1.jpg",
     "caption": "First caption",
     "tags": {
        "data": [
           {

              "name": "Cats One"
           },
           {
              "name": "Dogs One"
           }
        ]
     }
   }
   {
     "source": "http://example.com/picture2.jpg",
     "caption": "Second caption",
     "tags": {
        "data": [
           {

              "name": "Cats Two"
           },
           {
              "name": "Dogs Two"
           }
        ]
     }
   }
 ]
}

jQuery used to access JSON data
$(document).ready(function(){

  var url = "http://example.com";

  $.getJSON(url, function(json) {
      $('#wrapper').prepend('

');
      $.each(json.data, function(i, data) {
          //Adds each entry to container
          $("#container").append('
' + '

' + '
' + data.caption + '
' + '
');
          //Checks if tags exist for each element
          if (typeof(this.tags) === 'object') {
              $.each(this.tags.data, function() {
                  //console.log(this.name);
                              //not sure what to add here to append these tags in a li tag above
              });
          }

  });
});

A: Concatenate all the names and then append them to the container.
...
var names = "";
$.each(this.tags.data, function(idx) {
  if(idx > 0) names += ",";
  names += this.name;
});
$("#container").append($("

").append(names));
...


text:
Q: Как подставить в CURL свою переменную из bash Всем привет, нужно автоматизировать заполнение заявок на 5 схожих сервисах, сделал через баш скрипт ввод необходимых значение, и как бы подставить их в тело запроса, дам небольшую вырезку
--data-binary $'------WebKitFormBoundary358DzhBEThSvxSfb\r\nContent-Disposition: form-data;
name="sessid"\r\n\r\nc72598fa151fe6ddaae89efe476270bb\r\n------WebKitFormBoundary358DzhBEThSvxSfb\r\nContent-Disposition: form-data;
name="Update"\r\n\r\nY\r\n------WebKitFormBoundary358DzhBEThSvxSfb\r\nContent-Disposition: form-data;
name="COPY_ID"\r\n\r\n0\r\n------WebKitFormBoundary358DzhBEThSvxSfb\r\nContent-Disposition: form-data;
name="ACTIVE"\r\n\r\nY\r\n------WebKitFormBoundary358DzhBEThSvxSfb\r\nContent-Disposition: form-data;
name="NAME"\r\n\r\nTEST_NAME\r\n------WebKitFormBoundary358DzhBEThSvxSfb\r\nContent-Disposition: form-data;
name="LAST_NAME"\r\n\r\nTEST_FAMILY\r\n------WebKitFormBoundary358DzhBEThSvxSfb\r\nContent-Disposition: form-data;
name="SECOND_NAME"\r\n\r\nTEST_PATROM\r\n------WebKitFormBoundary358DzhBEThSvxSfb\r\nContent-Disposition: form-data;
name="EMAIL"\r\n\r\nTEST_EMAIL@testmail.ru\r\n------WebKitFormBoundary358DzhBEThSvxSfb\r\nContent-Disposition: form-data;
name="LOGIN"\r\n\r\nTest\r\n------WebKitFormBoundary358DzhBEThSvxSfb\r\nContent-Disposition: form-data;
name="NEW_PASSWORD"\r\n\r\nTEST_PASS\r\n------WebKitFormBoundary358DzhBEThSvxSfb\r\nContent-Disposition: form-data;
name="NEW_PASSWORD_CONFIRM"\r\n\r\nTEST_PASS\r\n------WebKitFormBoundary358DzhBEThSvxSfb\r\nContent-Disposition: form-data;
name="LID"\r\n\r\ncp\r\n------WebKitFormBoundary358DzhBEThSvxSfb\r\nContent-Disposition: form-data;
name="GROUP_ID_0"\r\n\r\n131\r\n------WebKitFormBoundary358DzhBEThSvxSfb\r\nContent-Disposition: form-data;
name="GROUP_ID_FROM_0"\r\n\r\n\r\n------WebKitFormBoundary358DzhBEThSvxSfb\r\nContent-Disposition: form-data;
name="GROUP_ID_TO_0"\r\n\r\n\r\n------WebKitFormBoundary358DzhBEThSvxSfb\r\nContent-Disposition: form-data;
name="GROUP_ID_1"\r\n\r\n130\r\n------WebKitFormBoundary358DzhBE

Хочу обратить внимание на
name="NAME"\r\n\r\nTEST_NAME\r\n------WebKitFormBoundary358DzhBEThSvxSfb`\r\nContent-Disposition: form-data;

Если указываю TEST_NAME, то все работает идеально, если подставляю переменную $User_Name, с таким же значением, то она просто не работает, это понятно, потому что запрос в одинарных кавычках, если написать:
name="NAME"\r\n\r\n'$User_Name'\r\n------WebKitFormBoundary358DzhBEThSvxSfb`\r\nContent-Disposition: form-data;

То все что после, отрежется, и вставится только это поле.
Как это исправить?

A: в параметре, передаваемом программе curl, используется специальный синтаксис для строки: $'строка'. он поддерживается в популярных оболочках (например, bash и zsh), но, насколько я знаю, не входит в стандарт posix.
внутри такой строки происходит подмена строк типа \n на символы. например, строка \n преобразуется в символ перевода строки, имеющий шестнадцатиричное значение 0a).

покажу на примере, что у вас «пошло не так».
пусть у нас имеется строка, содержащая \n. при её интерпретации оболочкой происходят преобразования:
$ echo $'a\nb\nc'
a
b
c

если же не использовать этот синтаксис, то преобразований не происходит:
$ echo 'a\nb\nc'
a\nb\nc

разорвав строку на две части и подставив вместо, например, символа b вывод переменной, мы получим:
$ var=zzz; echo $'a\n'$var'\nc'
a
zzz\nc

т.е., во второй части ('\nc') не было произведено описанных преобразований. чтобы они произошли и там, вторую часть тоже надо записать, используя тот же специальный синтаксис ($'\nc'):
$ var=zzz; echo $'a\n'$var$'\nc'
a
zzz
c


text:
Q: curl with nodejs express - POST data I'm trying to simulate a POST request to a server app based in Express for nodeJS.  It's running on localhost:3000 (JS Fiddle: http://jsfiddle.net/63SC7/)
I use the following CURL line:
 curl -X POST -d "{\"name\": \"Jack\", \"text\": \"HULLO\"}" -H "Content-Type: application/json" http://localhost:3000/api

but get the error message:
Cannot read property 'text' of undefined

Any ideas what I'm doing wrong?
Note: I can make a successful GET request using this line:
curl http://localhost:3000/api

A: Assuming you're trying req.body.text,
Have you used bodyParser?
app.use(express.bodyParser());

A: The answer by josh3736 is outdated. Express no longer ships with the body-parser middleware. To use it you must install it first:
npm install --save body-parser

Then require and use:
let bodyParser = require('body-parser');
app.use(bodyParser());

A: Just to update Thordarson's answer (which is now deprecated), the currently recommended way is:
app.use(bodyParser.urlencoded({extended: true}));
app.use(bodyParser.json());

See also https://stackoverflow.com/a/24330353/3810493


text:
Q: .remove not removing the given String tweets = api.search(q="@mytwitter",count=100,include_entities=True)
t = ['@mytwitter', '@MyTwitter']

for s in tweets:
    sn = s.user.screen_name
    m = "@%s message" % (sn)
    s = api.update_status(m, s.id)
    #print(dir(s))

for result in tweets:
    print str(result.text)

for userName in result.text:
    if userName == "@mytwitter":
        result.text.remove(userName)
        print (userName)
    else:
        print("No username")

Not sure why userName isn't removing my Twitter name from result.text. Am I missing something? The output I'm getting is "No username" repeated a bunch of times.
If it helps the orginal output for result.text is "@mytwitter their message" I'm trying to remove the @mytwitter.

A: Your problem is that the condition
if userName == "@mytwitter":

Is never true, so .remove() never called. If you want to search for your name inside the result.text, try this:
tweets = api.search(q="@mytwitter",count=100,include_entities=True)

for s in tweets:
    sn = s.user.screen_name
    m = "@%s message" % (sn)
    s = api.update_status(m, s.id)

for tweeet in tweets:
    if "@mytwitter" in tweeet.text:
        tweeet.text = tweeet.text.replace("@mytwitter", "")
        print(tweeet.text)
    else:
        print("No username")

p.s. The str object doesn't have .remove() method, try .replace() with empty string instead, as listed above.

A: Strings are immutable in Python so you have to assign your new string to another variable:
for tweet_text in tweets:
    if "@mytwitter" in tweet_text:
        new_str = tweet_text.replace("@mytwitter", "") # assigning new string wothout "@mytwitter" to another variable
        print(new_str)
    else:
        print("No username")

Example:
tweets = ["@mytwitter","1234","0987@mytwitter","@mytwitter145236","  @mytwitter12"]

for tweet_text in tweets:
    if "@mytwitter" in tweet_text:
        new_str = tweet_text.replace("@mytwitter", "") # assigning new string wothout "@mytwitter" to another variable
        print(new_str)
    else:
        print("No username")

Output:
No username

0987
145236
  12


text:
Q: Steiner symmetrization of Lebesgue measurable set I'm reading a proof in "Evans / Gariepy: Measure theory and fine properties of functions" of the following statemant:

Theorem: Let $A \subset \mathbb R^n$ be $\lambda^n$-measurable, $a \in \mathbb R^n$ with $\Vert a \Vert = 1$. Then $S_a(A)$ is $\lambda^n$-measurable and $\lambda^n(A) = \lambda^n(S_a(A))$.

Here $S_a(A)$ denotes the the Steiner symmetrization w.r.t the plane through $0 \in \mathbb R^n$ and perpendicular to $a$. This plane is denoted by $P_a$. We use the notation $L_b^a$ for the line through $b \in \mathbb R^n$ with direction $a$.
Now in the proof we set $a = (0, \ldots, 0, 1) \in \mathbb R^n$. Then we have $P_a = \mathbb R^{n-1}$. We define a function $f: \mathbb R^{n-1} \to \mathbb R$ by $$f(b) = \mathcal H^1(A \cap L_b^a) \; ,$$
where $\mathcal H^1$ denotes the "one-dimensional" Hausdorff measure. We know that $\mathcal H^1 = \lambda^1$ on $\mathbb R$. Now the author claims, that by Fubini the function $f$ is $\lambda^{n-1}$-measurable and $$\lambda^n(A) = \int_{\mathbb R^{n-1}} f(b) \; \mathrm db \; .$$ Why does this hold? Could maybe someone elaborate this?

A: Write points $x = (x_1,\ldots,x_n) \in \mathbb R^n$ as $x = (b,z)$ where $b = (x_1,\ldots x_{n-1}) \in \mathbb R^{n-1}$ and $z = x_n\in \mathbb R$. If $A \subset \mathbb R^n$ is measurable then Tonelli's theorem states that $$\lambda^n(A) = \int_{\mathbb R^n} \chi_A(x) \, dx = \int_{\mathbb R^{n-1}}\left(\int_{\mathbb R} \chi_A(b,z) \, dz \right) db,$$ where $z \mapsto \chi_A(b,z)$ is $\lambda^1$-measurable for $\lambda^{n-1}$ almost all $b \in \mathbb R^{n-1}$, and $b \mapsto \displaystyle \int_{\mathbb R} \chi_A(b,z) \, dz$ is $\lambda^{n-1}$ measurable.
Fix $b \in \mathbb R^{n-1}$. If $z \mapsto \chi_A(b,z)$ is $\lambda^1$-measurable then $$\int_{\mathbb R} \chi_A(b,z) \, dz = \lambda^1(\{z \in \mathbb R: (b,z) \in A\}) = {\cal H}^1(\{z \in \mathbb R: (b,z) \in A\}).$$
There is an (obvious?) isometry between the sets $\{z \in \mathbb R: (b,z) \in A\}$ and $\{(y,z) \in \mathbb R^n : y=b,\ (y,z) \in A\} = A \cap L_a^b$. Thus
$${\cal H}^1(\{z \in \mathbb R: (b,z) \in A\}) = {\cal H}^1(A \cap L_a^b),$$
meaning that
$$ \int_{\mathbb R} \chi_A(b,z) \, dz = {\cal H}^1(A \cap L_a^b)$$ for $\lambda^{n-1}$ almost every $b \in R^{n-1}$. It follows that $b \mapsto {\cal H}^1(A \cap L_a^b)$ is $\lambda^{n-1}$ measurable and that $$\lambda^n(A) = \int_{\mathbb R^{n-1}} {\cal H}^1(A \cap L_a^b) \, db.$$

A: $$
\lambda^n (A) = \int_{R^n} I_A (x_1,\ldots,x_n) d\lambda^n(x_1,\ldots,x_n)=\int_{R^{n-1}} \int_R I_A (x_1,\ldots,x_{n-1},x_n) d \lambda (x_n) d\lambda^{n-1} (x_1,\ldots,x_{n-1}) = \int_{R^{n-1}} f(x_1,\ldots,x_{n-1}) d\lambda^{n-1}(x_1,\ldots,x_{n-1}) = \int_{R^{n-1}} f(b) db.
$$


text:
Q: UIPickerView shows wrong titles My app is a converter with a multicomponent picker wheel. It is made for converting some variables. The numbers you can see is just for testing, nothing important really.
- (void)viewDidLoad
{
  [super viewDidLoad];
  _convertFrom = @[@"One (1)", @"Two (2)",
  @"Three (3)", @"Four (4)", @"Five (5)"];

  _convertRates = @[ @1.0f, @2.0f, @3.0f,
  @4.0f, @5.0f];

  _convertTo = @[@"One (1)", @"Two (2)",
  @"Three (3)", @"Four (4)", @"Five (5)"];

_convertRates = @[ @1.0f, @2.0f, @3.0f,
@4.0f, @5.0f];

}

I have a small problem with the numbers that is displayed when i test the app in the iOS 6 simulator. As you can see here:

http://imgur.com/q4uxm
When i try to go down the list, the numbers change. But the value of them does not.
If someone has got the time to check it out and maybe find a solution it would be very helpful:)
here is the rest of the code that might be important in this case:
#pragma mark -
#pragma mark PickerView DataSource

- (NSInteger)numberOfComponentsInPickerView:
 (UIPickerView *)pickerView
{
return 2;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:    (NSInteger)component
{
if (component == 0)  {
    return [_convertFrom count];
}
return [_convertTo count];
}

- (NSString *) pickerView: (UIPickerView *)pickerView
          titleForRow:(NSInteger)row
         forComponent:(NSInteger)component
{
if (component == 0) {
    return [_convertFrom objectAtIndex:[pickerView selectedRowInComponent:0]];
}
return [_convertTo objectAtIndex:[pickerView selectedRowInComponent:1]];
}

#pragma mark -
#pragma mark PickerView Delegate
-(void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row
  inComponent:(NSInteger)component
{
    float convertFrom = [[_convertRates objectAtIndex:[pickerView  selectedRowInComponent:0]] floatValue];
float convertTo = [[_convertRates objectAtIndex:[pickerView selectedRowInComponent:1]] floatValue];
float input = [dollarText.text floatValue];
float to = convertTo;
float from = convertFrom;
float dollars = input;
float result = to * from * dollars;
float mtpaTilMtpaFloat = dollars * 1;
NSString *resultString = [[NSString alloc] initWithFormat:
                          @"result = %.2f *  %.2f = %.2f", from, to, result];
resultLabel.text = resultString;

NSString *mtpaTilmtpa = [[NSString alloc ] initWithFormat:
                           @" %.2f MTPA = %.2f MTPA", dollars, mtpaTilMtpaFloat];

if (from == 1, to == 1) { resultLabel.text = mtpaTilmtpa;
}

And of course, tell me if I need to display more of the code so you can understand it. its my first time using this website btw:)

A: don't use selectedRowInComponent. You don't wan't to display the value that is selected in all your rows. Just use row
- (NSString *) pickerView: (UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
    if (component == 0) {
        return [_convertFrom objectAtIndex:row];
    }
    return [_convertTo objectAtIndex:row];
}


text:
Q: passing current state from one screen to another using mapDispatchToProps I am working with react native maps and react native geocoding, I want to pass the current user location to the redux store using mapDispatchToProps, and to be able to use that location on a different map component. I am roughly a newbie in the redux world and I am a bit confused. kindly make corrections to my code below. I have tried using the example implemented on the documentation, however, I do not fully understand
Location 1
    import React, { Component, Fragment } from 'react';
    import {
        View,
        Text,
        StyleSheet,
        TouchableOpacity,
      } from 'react-native';
    import { connect } from 'react-redux';
    import MapView from 'react-native-maps';
    import Geocoder from 'react-native-geocoding';

      Geocoder.init('XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX');

      const LONGITUDEDELTA = 0.0173;
      const LATITUDEDELTA = 0.0174;
      class Location1 extends Component {
        static navigationOptions = {
          header: null,
        }

        constructor(props) {
          super(props);
          this.state = {
            region: null,
          };
          this.handleBack = this.handleBack.bind(this);
        }

        async componentDidMount() {
          this.watchId = navigator.geolocation.watchPosition(
            async ({ coords: { latitude, longitude } }) => {
              const response = await Geocoder.from({ latitude, longitude });
              const address = response.results[0].formatted_address;
              const location = address.substring(0, address.indexOf(','));

              this.setState({
                location,
                region: {
                  latitude,
                  longitude,
                  title: location,
                  latitudeDelta: LATITUDEDELTA,
                  longitudeDelta: LONGITUDEDELTA,
                },
              });
            }, //sucesso

            () => {}, //erro
            {
              timeout: 2000,
              enableHighAccuracy: true,
              maximumAge: 1000
            }
          );
        }

        componentWillUnmount() {
          navigator.geolocation.clearWatch(this.watchId);
        }

        render() {
          const { region } = this.state;
          const { container, map, } = styles;

          return (
              <View style={container}>
                <MapView
                  style={map}
                  region={region}
                  loadingEnabled
                  showsCompass
                  showsTraffic
                  showsBuildings
                  showsIndoors
                >

                </MapView>

              </View>
          );
        }
      }

      const styles = StyleSheet.create({
        container: {
          flex: 1,
        },
        map: {
          ...StyleSheet.absoluteFill,
        },
      });

      function mapDispatchToProps(dispatch) {
        return {
          region: () => {
            dispatch(this.state.region);
          },
          location: () => {
            dispatch(this.state.location); // address name
          }
        }
      }

      export default connect(mapDispatchToProps) (Location1);

Location2
    import React, { Component, Fragment } from 'react';
    import {
        View,
        Text,
        StyleSheet,
        TouchableOpacity,
      } from 'react-native';
    import { connect } from 'react-redux';
    import MapView from 'react-native-maps';
    import Geocoder from 'react-native-geocoding';

      const LONGITUDEDELTA = 0.0173;
      const LATITUDEDELTA = 0.0174;
      class Location2 extends Component {
        static navigationOptions = {
          header: null,
        }

        constructor(props) {
          super(props);
          this.state = {
            region: null,
          };
        }

        render() {
          const { container, map, } = styles;

          return (
              <View style={container}>
                <MapView
                  style={map}
                  region={this.props.region}
                  loadingEnabled
                  showsCompass
                  showsTraffic
                  showsBuildings
                  showsIndoors
                >
                </MapView>
                  <View><Text>{this.props.location}</Text></View>

              </View>
          );
        }
      }

      const styles = StyleSheet.create({
        container: {
          flex: 1,
        },
        map: {
          ...StyleSheet.absoluteFill,
        },
      });

      function mapStateToProps(state) {
        return {
          region: state.region,
          location: state.location
        }
      }

      export default connect(mapStateToProps) (Location2);

Reducer
import { CURRENT_LOCATION, LOCATION_NAME } from '../actions/types';

            const initialState = {
              region: null,
              location: ''
            };

            const Reducer = (state = initialState, action) => {
              switch (action.type) {
                case CURRENT_LOCATION:
                  return {
                    ...state,
                    region: action.region
                  };
                case LOCATION_NAME:
                  return {
                    ...state,
                    location: action.location
                  };
                default:
                  return state;

              }
            };

            export default Reducer;

A: Firstly in the first code here
function mapDispatchToProps(dispatch) {
    return {
      region: () => {
        dispatch(this.state.region);
      },
      location: () => {
        dispatch(this.state.location); // address name
      }
    }
  }

  export default connect(mapDispatchToProps) (Location1);

you need to pass the first argument to connect wich is the mapStateToProps but if you don't wanna use it pass null instead
export default connect(mapStateToProps, mapDispatchToProps)(Location1);

and also you dispatch actions in redux by passing and actionType(required) and a actionPayload(optional)
 function mapDispatchToProps(dispatch) {
    return {
      region: (regionVal) => {
        dispatch({type: 'LOCATION_NAME',payload: regionVal});
      },
      location: (locationVal) => {
        dispatch({type: 'CURRENT_LOCATION',payload: locationVal}); // address name
      }
    }}

and call it inside the componentDidMount like
async componentDidMount() {
.
.
.
  this.props.region(regionVal);
  this.props.locatio(locationVal);
}

and in the reducer you should fix this
            case CURRENT_LOCATION:
              return {
                ...state,
                region: action.region
              };

to something like this
            case CURRENT_LOCATION:
              return {
                ...state,
                region: action.payload // you should call the payload from the action
              };


text:
Q: What is minimum trace width for "advanced" fab shops and what are possible manufacturing/reliability issues? One of fab houses suggested stackup with 2mil traces.  Given that this is their stackup so they must be feeling comfortable with it and SI performance aside - are there any reliability/manufacturability issues that arise at such narrow geometry?  I can think that maintaining consistent width (thus impedance) might be more challenging due to relative error being higher.
Any thoughts?

A: If they are Sierra Ccts or "ProtoExpress", then they are a high quality, competent shop with adequate yields that always degrade if you do not have what it takes.
Track and gap is only 1 of dozens of metrics for quality & capability on fabrication.
Acid etching rate with not only sensitive to copper thickness but also temperature, fluid agitation rate, surface oxidation, density of nearby etching but also copper content dissolved in acid and more.
It used to be 10 mil track/space was std then 3/3 for advanced but now it's;
Min   Trace and Space  (aka track and gap)
-----  ------------
4 mil  Std
3 mil  Advanced
2 mil  Micro

Sierra Ccts. was my "goto" shop when I needed highest quality boards in the fastest delivery time and they never let me down.


text:
Q: folder picker in jquery In my html5 webapp using jquery, I want the user to choose a local directory name.
The <input  type="file"> element is close, but I want to choose a folder instead of a file.
fwiw, I need the path too, which I'm guessing may not be possible.

A: It may be possible with the new FileSystem Api but the browser support is currently pretty bad. Seems like the only supported browsers are using the webkit engine. Everything else including Firefox won't work. So i would go with "No it isn't possible yet."


text:
Q: Reportlab no Heroku - Erro de palavras com acento Estou gerando relatorios com reportlab
Mas quando tem palavras com acentuação, estou tomando 500
Internal Server Error no Heroku.
Localhost funciona perfeitamente.
Tentei o seguinte  não deu certo
reports.py
# -*- coding: utf-8 -*-
Erro LOG HEROKU
    [ERROR] Error handling request /laudo/16/paciente/5/imprimir/
    Traceback (most recent call last):
    File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/workers/sync.py", line 135, in handle
        self.handle_request(listener, req, client, addr)
    File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/workers/sync.py", line 182, in handle_request
        resp.write(item)
    File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/http/wsgi.py", line 342, in write
        self.send_headers()
    File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/http/wsgi.py", line 338, in send_headers
        util.write(self.sock, util.to_bytestring(header_str, "ascii"))
    File "/app/.heroku/python/lib/python3.5/site-packages/gunicorn/util.py", line 511, in to_bytestring
        return value.encode(encoding)
    UnicodeEncodeError: 'ascii' codec can't encode character '\xf3' in position 220: ordinal not in range(128)

Django 1.10+
Python 3.5.1

A: Encontrei a resposta
O erro estava no filename ou seja, é como vai "chamar" o arquivo que voce vai baixar em PDF
ANTES
def gerar_laudo(request, laudo_id, paciente_id):

    filename = "laudo_{}".format(paciente.nome)
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="{}.pdf"'.format(filename)

    c.setTitle("Laudo de {}".format(paciente.nome))
    c.showPage()
    c.save()

DEPOIS
Importar o normalize e criar um metodo para tirar os acentos
from unicodedata import normalize

def gerar_laudo(request, laudo_id, paciente_id):

    # nova variavel para guardar o nome sem acento
    nome_sem_acento = remover_acentos(paciente.nome)
    filename = "laudo_{}".format(nome_sem_acento)
    response = HttpResponse(content_type='application/pdf')
    response['Content-Disposition'] = 'attachment; filename="{}.pdf"'.format(filename)

    c.setTitle("Laudo de {}".format(paciente.nome))
    c.showPage()
    c.save()

def remover_acentos(txt):
    """ metodo que remove os acento das palavras """
    return normalize('NFKD', txt).encode('ASCII','ignore').decode('ASCII')


text:
Q: Removing Hebrew vowels / niqqud using php I found this solution: here
but its in javascript, I try to do it with PHP and I got a warning.
Here is my code:
$dynamicstring = 'שָׁמַיִם';
$newstring2 = preg_replace('[\u0591-\u05C7]', '', $dynamicstring);

The warning I have got:
Warning: preg_replace(): Compilation failed: PCRE does not support \L, \l, \N{name}, \U, or \u at offset 1 in

What is it mean? so if it not support what can I use?
Edit:
I was able to do this by the following code:
preg_replace('/[^\w$\x-\x]+/u', '', $dynamicstring);

But this code remove spaces between words in the string, how to fix that?
Second Edit:
the solution is to do this:
preg_replace('/[^\w$\x-s-\x]+/u', '', $dynamicstring);

I added -s- between the \xs

A: These are non-spacing marks, so (assuming the string is in UTF-8) they can be stripped using the Unicode character property syntax:
<?php

$dynamicstring = 'שָׁמַיִם';
$newstring2 = preg_replace('/\p{Mn}/u', '', $dynamicstring);
var_dump($newstring2); // results in string(8) "שמים"

Demo: https://ideone.com/KpsZM3


text:
Q: Best approach to save user id in phone memory(or cache) once authenticated What is the best approach to save user ID in phone's memory once authenticated so that user don't need to login again once the app is terminated.Should i use user Shared preferences plugin in dart??
Also, I am using firebase phone auth in my flutter app and all i want is user don't have to put phone number again and again.Once authenticated the user should bypass phone auth screen, if he/she opens app again.

A: SharedPreference plugin is a good plugin for a situation like this, but since you are working with firebase, You don't really need it. Once you log in with firebase, the current user remains available until you logout, so there is no need to save the details in sharedPreference.
 You can check for the user by doing this:
FirebaseAuth  _auth = FirebaseAuth.instance;
FirebaseUser currentUser = await _auth.currentUser();
        if(currentUser != null){
           print(currentUser.uid);
        }else{
            //go to phone login page or something like that
        }

Use this to signout
_auth.signOut();


text:
Q: Values displayed after realloc are weird I called malloc and then I want to cut size in half using realloc when i  display values of relocated malloc few numbers shows as 0, is that normal or I messed something up?
double main()
{
    double *test;
    int size = 10;
    int sizes;
    int i = 0;
    double value;
    test = (double*)malloc(size*sizeof(double));
    if(test == NULL)
    {
        printf("ERROR");
        return 0;
    }
    else
    {
        printf("\nInsert values : \n");
        for(i=0;i<=size;)
        {
            scanf("%lf",&*(test+i));
            if(*(test+i)==0.0)
            {
                break;
            }
            if(i>=size)
            {
                size=size+2;
                test = realloc(test, size*sizeof(double));
            }
            i++;
        }
    }
    sizes=size/2;
    test = realloc(test, sizes*sizeof(double));
    printf("\nSaved values : \n");
    for(i=0;i<size;i++)
    {
        printf("%lf\n",*(test+i));
    }

}

I want to learn some coding so please tell me if and what I am doing wrong.

A: Two issues here:

*

*This
for(i=0;i<=size;)

makes this
  scanf("%lf",&*(test+i));

scan into memory one element beyond the allocated memory on the last iteration before reallocating. Doing so invokes undefined behaviour. Already from now on anything may happen.

*Those two lines
sizes=size/2;
test = realloc(test, sizes*sizeof(double));

shrink the valid memory to the half of its size, and then this loop
for(i=0;i<size;i++)
{
  printf("%lf\n",*(test+i));
}

tries to read out the second half's value which just had been shrinked away. This half's memory is not valid any more. Trying to read it invokes undefined behaviour as well.
So to answer your question:

or i messed something up

Yes you did, namely by invoking undefined behaviour. Do not do that.

A: If I well understand you stop to read value at EOF or when the read value is 0, and 0 is not memorized, and when the read is done you want to reduce the allocates vector to the minimal size, in that case :
#include <stdlib.h>
#include <stdio.h>

int main()
{
    int size = 10;
    double *test = malloc(size*sizeof(double));

    if(test == NULL)
    {
        printf("ERROR");
        return 0;
    }
    else
    {
      int i = 0;
      double value;

      printf("\nInsert values : \n");
      while ((scanf("%lf",&value) == 1) && (value != 0))
      {
          if (i >= size) /* == is enough */
          {
            size += 2; /* I add 2 entries as you */
            test = realloc(test, size*sizeof(double));
          }
          test[i++] = value;
      }

      /* remove possible extra entry at the end */
      if (i != size)
          test = realloc(test, i*sizeof(double));

      size = i;

      printf("\nSaved values : \n");
      for(i=0 ;i<size; ++i)
      {
        printf("%lf\n",test[i]);
      }

      free(test);
    }

    return 0;
}


text:
Q: Representation of trigonometric functions in terms of a cross product Let us say that I define a vector in 3D given by
$$ \vec{u}=(\sin\theta \cos\phi, \sin\theta\sin\phi,\cos\theta)$$
I can write $\sin\theta$ in terms of a cross product of the derivatives of the vector (verified by hand and with Mathematica):
$$\vec{u}\cdot \frac{\partial \vec{u}}{\partial \theta}\times \frac{\partial \vec{u}}{\partial \phi} =\sin\theta$$
Is there a similar way to write other trigonometric functions; i.e., $\cos\theta$ or $\tan\theta$? In other words, how can I write these trigonometric functions in terms of a cross product of derivatives of $\vec{u}$ with respect to $\theta$ and $\phi$? Can I do the same for $\sin\phi$, $\cos\phi$, or $\tan\phi$?

A: $\vec{u}$ is a unit vector consisting of a rotation of $\phi$ around the $z$ axis, with $\phi=0$ corresponding to the $y$ axis, resulting in a unit vector $u'$ in the $xy$ plane, followed by a rotation $\theta$ of $u'$ about the axis perpendicular to the $z-u'$ plane resulting in the unit vector $u$.
$$
\vec{a}\equiv
\frac{\partial \vec{u}}{\partial \phi}=
\begin{pmatrix}
-\sin\theta\sin\phi
&
\sin\theta\cos\phi
&
0
\end{pmatrix}
$$ is a vector of length $\Vert \vec{a}\Vert=\sin\theta$ in the $xy$ plane perpendicular to $u$
$$
\vec{u}\cdot\frac{\partial \vec{u}}{\partial \phi}=0
$$
and $$
\vec{b}\equiv
\frac{\partial \vec{u}}{\partial \theta}
=
\begin{pmatrix}
\cos\theta\cos\phi
&
\cos\theta\sin\phi
&
-\sin\theta
\end{pmatrix}
$$ is a vector perpendicular to $\vec{a}$ of length $\Vert \vec{b}\Vert=1$. When you take the cross product of these vectors, you get a vector
$$
\vec{c}=\vec{a}\times\vec{b}=\frac{\partial \vec{u}}{\partial \theta}\times\frac{\partial \vec{u}}{\partial \phi}\\
=
\begin{pmatrix}
\sin^2\theta\cos\phi
&
\sin^2\theta\sin\phi
&
\sin\theta\cos\theta
\end{pmatrix}
\equiv
\sin\theta \vec{u}
$$
which is perpendicular to both of the derivatives, hence must be in the same direction as $\vec{u}$, and has length $\Vert\vec{c}\Vert=\sin\theta$. When you take the dot product of that vector with $u$, because $\vec{b}$ and $\vec{u}$ are unit vectors, and $\vec{a}$ has length $\sin\theta$, the result comes out to $\sin\theta$.
So to answer your question, of course you have a formula for $\sin\theta$ so you can get $\cos\theta=\sqrt{1-\sin^2\theta}$ and so on, but you can't get $\phi$. Vectors $\vec{a}$ and $\vec{b}$ and $\vec{u}$ are all orthogonal, and  the only angle which occurs is the angle from the length of $\vec{a}$, $\theta$.


text:
Q: Why are my background transitions not working? I'm trying to create my first css-transitions, but it doesn't work. I have tried using shortcode, putting the transitions in .btn-zen-inverse:hover instead. Why isn't it working? (testing in the latest version of chrome)

    .btn {
     color: white;
     font-family: 'ZLight';
     border: 2px solid white !important;
     box-shadow: 0 0 6px rgba( 12, 41, 63, 0.3);
     text-shadow: none;
     background: -moz-linear-gradient(top, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.21) 100%);
     /* FF3.6+ */

     background: -webkit-linear-gradient(top, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.21) 100%);
     /* Chrome10+,Safari5.1+ */

     background: -o-linear-gradient(top, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.21) 100%);
     /* Opera 11.10+ */

     background: -ms-linear-gradient(top, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.21) 100%);
     /* IE10+ */

     background: linear-gradient(to bottom, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 0.21) 100%);
     /* W3C */

     filter: progid: DXImageTransform.Microsoft.gradient( startColorstr='#00ffffff', endColorstr='#6bffffff', GradientType=0);
     /* IE6-9 */

     padding: 3px;
 }
 .btn:hover {
     transition: background-image 0.5s;
     transition: background-color 0.5s;
     -moz-transition: background-image 0.5s;
     /* Firefox 4 */

     -webkit-transition: background-image 0.5s;
     /* Safari and Chrome */

     -webkit-transition: background-color 0.5s;
     /* Safari and Chrome */

     -o-transition: background-image 0.5s;
     /* Opera */

     color: white;
 }
 .btn-zen-inverse {
     background-color: #273032;
 }
 .btn-zen-inverse:hover {
     background-image: none;
     background-color: #273032;
 }

    Prova Zenconomy Gratis

A: First of all, your transition definition needs to be a part of the base class definition
ie:
div {
   transition: background-color 0.5s;
}

instead of:
/* this is wrong */
div:hover {
   transition: background-color: 0.5s;
}

and the actual change "effect", if you will, is placed in the hover pseudo-class
like this:
div:hover {
    background-color: red;
}

and your base class definition:
div {
    background-color: white;
}

That being said, I'm 99.7% sure you cannot break-apart the background "short-hand" style.  Try seperating the individual styles you are attempting to transition (ie: background-color and background-image) in both the base class and the pseudo-class definitions.
EDIT: Apparently you CAN transition gradients, just not to "none".