Trying to draw Rotated text with CGAffineTransform and MakeRotation appears at wrong location

Question: I'm trying to draw some rotated texts by using the CGAffineTransform.MakeRotation method at specifc location. I also make use of the TranslateCTM, but something must be wrong as rotated texts do not appear aligned and at the correct x, y position where they should appear, here is simple the code I'm using, anyone know where the problem is? :
        public override void Draw (RectangleF rect)
    {
        DrawTextRotated("Hello1",10,100,30);
        DrawTextRotated("Hello2",50,100,60);
        SetNeedsDisplay();
    }

    static public float DegreesToRadians(float x)
    {
        return (float) (Math.PI * x / 180.0);
    }

    public void DrawTextRotated(string text,int x, int y, int rotDegree)
    {
        CGContext c = UIGraphics.GetCurrentContext();
        c.SaveState();

        c.TextMatrix = CGAffineTransform.MakeRotation((float)DegreesToRadians((float)(-rotDegree)));
        c.ConcatCTM(c.TextMatrix);

        float xxx = ((float)Math.Sin(DegreesToRadians((float)rotDegree))*y);
        float yyy = ((float)Math.Sin(DegreesToRadians((float)rotDegree))*x);

        // Move the context back into the view
        c.TranslateCTM(-xxx,yyy);

        c.SetTextDrawingMode(CGTextDrawingMode.Fill);
        c.SetShouldSmoothFonts(true);

        MonoTouch.Foundation.NSString str = new MonoTouch.Foundation.NSString(text);
        SizeF strSize = new SizeF();
        strSize = str.StringSize(UIFont.SystemFontOfSize(12));

        RectangleF tmpR = new RectangleF(x,y,strSize.Width,strSize.Height);

        str.DrawString(tmpR,UIFont.SystemFontOfSize(12),UILineBreakMode.WordWrap,UITextAlignment.Right);
        c.RestoreState();
    }

Thanks !
Answer: Here's some code that will draw text rotated properly about the top-left corner of the text. For the moment, I'm disregarding your use of text alignment.
First, a utility method to draw a marker where we expect the text to show up:
public void DrawMarker(float x, float y)
{
    float SZ = 20;

    CGContext c = UIGraphics.GetCurrentContext();

    c.BeginPath();
    c.AddLines( new [] { new PointF(x-SZ,y), new PointF(x+SZ,y) });
    c.AddLines( new [] { new PointF(x,y-SZ), new PointF(x,y+SZ) });
    c.StrokePath();
}

And the code to draw the text (note I've replaced all int rotations with float, and you may want negate your rotation):
public void DrawTextRotated(string text, float x, float y, float rotDegree)
{
    CGContext c = UIGraphics.GetCurrentContext();
    c.SaveState();

    DrawMarker(x,y);

    // Proper rotation about a point
    var m = CGAffineTransform.MakeTranslation(-x,-y);
    m.Multiply( CGAffineTransform.MakeRotation(DegreesToRadians(rotDegree)));
    m.Multiply( CGAffineTransform.MakeTranslation(x,y));
    c.ConcatCTM( m );

    // Draws text UNDER the point
    // "This point represents the top-left corner of the string's bounding box."
    //http://developer.apple.com/library/ios/#documentation/UIKit/Reference/NSString_UIKit_Additions/Reference/Reference.html
    NSString ns = new NSString(text);
    UIFont font = UIFont.SystemFontOfSize(12);
    SizeF sz = ns.StringSize(font);
    RectangleF rect = new RectangleF(x,y,sz.Width,sz.Height);
    ns.DrawString( rect, font);

    c.RestoreState();
}

Rotation about a point requires translation of the point to the origin followed by rotation, followed by rotation back to the original point. CGContext.TextMatrix has no effect on NSString.DrawString so you can just use ConcatCTM.
The alignment and line break modes don't have any effect. Since you're using NSString.StringSize, the bounding rectangle fits the entirety of the text, snug up against the left and right edges. If you make the width of the bounding rectangle wider and use UITextAlignment.Right, you'll get proper right alignment, but the text will still rotate around the top left corner of the entire bounding rectangle. Which is not, I'm guessing, what you're expecting.
If you want the text to rotate around the top right corner, let me know and I'll adjust the code accordingly.
Here's the code I used in my test:
DrawTextRotated("Hello 0",100, 50, 0);
DrawTextRotated("Hello 30",100,100,30);
DrawTextRotated("Hello 60",100,150,60);
DrawTextRotated("Hello 90",100,200,90);

Cheers.


Prove $ 1-\frac{\sum{(z_x - z_y)}^2}{2(n-1)} $ = $\frac{\sum{(z_x*z_y)}}{n-1}$

Question: I am trying to prove the following equality through algebraic means based on the textbook Applied multiple regression/correlation analysis or the behavioural sciences by Cohen et al. (pages 27-28) The formulas are supposedly for the Pearson Correlation Coefficient.
$$ 1-\frac{\sum{(z_x - z_y)}^2}{2(n-1)}  = \frac{\sum{(z_x*z_y)}}{n-1}$$
Here $z_x$ and $z_y$ represent z scores for (scores that have been transformed by subtracting the mean from them and dividing by the standard deviation) for two different variables. You are summing over the total number of pairs of scores.
I have tried by manipulating the left hand side of the equation by expanding the terms and converting the 1 to $\frac{n-1}{n-1}$ but I am having no success. Apparently the left hand side can be converted to the right hand side of the equation using only basic algebra. Can someone tell me what I am missing.
Thanks
Comment: You should provide more information about:
1) What do $z_x$ and $z_y$ represent.
2) What are we summing over.
Comment: $z_x$ and $z_y$ represent z scores. You are summing over the total number of pairs of scores. Does that help?
Comment: Not really. You need some condition on $z_i$, otherwise the equality is not necessarily true. Oh wait, you _did_ specify that already! Now, the mean of $z_i$ is 0 and the standard deviation is 1. What does that mean for a $\sum z_i^2$?
Comment: I know I should see it, but I can't see how knowing the mean and SD gives me the sum. Can you explain?
Answer: I'll use the notation from the book.
So, the z score is calculated as $z_X=\frac{X-M_X}{sd_X}=\frac x{sd_X}$, where $M_X$ is the sample mean of $X$, $x=X-M_X$ and $sd_X=\sqrt{\frac{\sum x^2}{n-1}}$ is the sample standard deviation.
First let's calculate the sum of squared z scores:
\begin{align}
\sum z_X^2&=\sum \left(\frac x{sd_X}\right)^2\\&=\frac1{(sd_X)^2}\sum x^2\\
&=\frac{n-1}{\sum x^2}\sum x^2\\&=n-1.
\end{align}
The same goes for $Y$, i.e. $\sum z_Y^2=n-1$. Then we easily see:
\begin{align}\sum(z_X-z_Y)^2&=\sum(z_X^2-2z_X*z_Y+z_Y^2)\\
&=\sum z_X^2 + \sum z_Y^2 -2\sum z_X*z_Y\\&=2(n-1)-2\sum z_X*z_Y\end{align}
Now the conclusion follows directly:
\begin{align}
1-\frac{\sum(z_X-z_Y)^2}{2(n-1)}&=1-\frac{2(n-1)-2\sum z_X*z_Y}{2(n-1)}\\
&=\frac{\sum z_X*z_Y}{n-1}.
\end{align}


import BeamMusicPlayer to my project

Question: I downloaded the BeamMusicPlayer from git and dragged the .xcodeproj into my project target and all that worked fine but when I try to import BeamMusicPlayerViewController.h to the existing project xcode says the file can't be found.
Screenshot of the library successfully added to my project:

I don't understand why I'm not able to import the BeamMusicPlayer header files to my project. Does anyone know why?
** EDIT **
I checked my library search paths and even added the BeamMusicPlayer folder explicity but it didn't help.
Comment: did you try using cocoapods ?
http://cocoapods.org
http://www.raywenderlich.com/64546/introduction-to-cocoapods-2

add the dependency pod 'BeamMusicPlayerViewController' in your podfile
run pod install
Comment: I've never used cocoapods before but it sounds like I'll have to give it a shot.
Answer: This worked once I used cocoapods to install the desired library. You can learn how to install cocoapods here. I'm still put-out that I couldn't figure out how to install this without cocoapods AND I'm finding out that uninstalling a library added with cocoapods is more of a pain than it's worth.

import BeamMusicPlayer to my project


HybridAuth has stopped working with FaceBook

Question: Before the weekend, I successfully set up the HybridAuth module. Upon returning to this project this week (July 1), Facebook logins no longer seem to respond.
Watchdog logs contained numerous of the following lines
<code>Exception: Authentication failed! Facebook returned an invalid user id. in Hybrid_Auth::initialize() (line 147 of xxxxxxxx/public_html/sites/all/libraries/hybridauth/hybridauth/Hybrid/Auth.php).
</code>

Now I have checked the FB AppID and AppSecret. They are correct.
Permission is set as follows....

Sand box is off

I'm using the latest library from HybridAuth. I've clone it using git
Comment: Please report bugs in issue queues.
Answer: Please check the issue already submitted in drupal.org https://drupal.org/node/1860618 . Especially check this comment. You have to use latest 7.x-2.x-dev release.


Como Aninhar um terceiro nested_form no rails

Question: Tenho os seguintes models:
Prova,
Questao,
Alternativa.
Estando os mesmos com as seguintes associações:
Prova has_many :questoes

Questao belongs_to :prova

Questao has_many :alternativas

Alternativa belongs_to :questao

Estou usando a gem nested_form para fazer o formulário aninhado, só que não estou conseguindo fazer o nested_form de alternativas, tendo em vista que não tenho o Controller de questão (pois eles serão apenas atributos dentro do controller de prova), como eu faria esse aninhamento?
Answer: Está faltando uma linha no seu models/questao.rb
accepts_nested_attributes_for :alternativas

Comment: Estava faltando um pouco mais que isso, mas deu pra resolver, obrigado!


Why does a PHP function with no parameters require parentheses?

Question: I just spent 3 hours wondering why I couldn't start a session, then realised that I used:
session_start;

when I should have used:
session_start();

I received no error messages at all!
Perhaps then, I thought, it's a lazy way to differentiate functions from variables - but then remembered that it can't be as variables require a $
Can anyone tell me why parentheses are required then, and also why no error is given when they aren't used?
Comment: Are your notice error messages active? // error_reporting(E_ALL);
Comment: Are you an ASP/VBScript programmer?
Comment: I mostly come from the Delphi/SQL world.
Answer: I get the notice (Having set error_reporting to E_ALL):

Notice: Use of undefined constant session_start - assumed 'session_start' in /t.php on line 5

A function always needs the parentheses as else (as you can see) you can't tell the difference between a function and a constant. As code should be written so it can be understood by the human reading it, not allowing the reader to see if it is a constant or function call makes it that bit harder to read and debug.
I assume it is a notice rather than an error error due to backwards compatibility in that some older code tends to access arrays using unquoted strings which PHP would treat as quoted strings if there wasn't a constant with that name.
$myArray[myString] = 25;

Comment: Thank you, it was to determine the difference between a function and a constant.
Answer: You can not make a difference between function and a constant if function doesn't have parantheses... But it is strange that it doesn't throw the errors...have you turned errors off in your php.ini file?
Answer: The parentheses are required because PHP's language specification says so (even though there appears to be no explicit formal specification of the language to be found).
What PHP does when it encounters an unknown identifier is output an E_NOTICE error to let you know that an unknown identifier was used, and then assumes that you meant to use that identifier as a string.
<?php
$foo = unknown_identifier;
echo 'Now printing: ' . $foo; // prints 'Now printing: unknown_identifier' (PHP 5.2.6)
?>

The reason you're not seeing any error is likely because E_NOTICE errors are below your error reporting threshold. You can change this threshold using the error_reporting directive:
<?php
error_reporting(E_ALL);

$foo = unknown_identifier;
echo 'Now printing: ' . $foo;
?>

This will output the "Notice" error message as posted above by Yacoby.
Note that, misleadingly, the E_ALL error reporting directive does not in fact include all reporting levels in PHP 5.x. In PHP 5, you need to use E_ALL | E_STRICT to enable all error messages.
-- edit: beaten to the punch by many people.
Answer: All the languages I know or have ever used use brackets to describe functions whether they take no parameters (void) or have a parameter list (optional or not).
You get used to it. Maybe it's a hangover from C with all it's function prototypes and all.
Having said that, the echo functon in PHP is a weird one as it's not quite a function but it's a statement - go figure.
Have a look at http://en.wikipedia.org/wiki/Function(computer_science)
Comment: Jujhar, that's because echo is *not* a function! It is a language construct, in fact writing `` is the same as ``

See http://php.net/manual/en/function.echo.php
Answer: () denotes that the function is to be called.  Without it, you are able to pass the reference around.  For example (PHP 5.3):
$callable = session_start;
$callable();

Comment: Strictly speaking, this is not true. `session_start` is considered to be the string `"session_start"`, and adding parentheses after a variable that contains a string causes the string to be used as a function name to be called.


How to wrap Datamapper to_json response in a object-key hash

Question: I'm working with a json parser that requires my response to be wrapped in an object-key hash.  When I use DataMapper's .to_json method(datamapper/dm-serializer) the repsone I get is correct
get '/plane/all' do
  @plane = Plane.all(:order => :id.desc).to_json(:relationships => {:pilots => {}, :passengers => {}, :cabin => {}})
  @plane
end

The response in JSON
[{"id":2,"name":"Plane 2","picture_url":"https://s3.amazonaws.com","pilots":[{"pilot_id":2,"header":"Bruce Wayne","details":"Bruce loves his batwing that flies at an average speed of 200 mph","picture_url":"www.marvel.com","plane_id":2}],"passengers":[{"passenger_id":2,"name":"Passenger 2","details":"These are the details for passenger 2","picture_url":"www.toobar.com/","plane_id":2}],"cabin":[{"cabin_id":2,"details":"Great Details for has been put in this cabin","picture_url":"www.seatingchart.com","video_link":"www.skyview.com","passenger_passenger_id":2}]},{"id":1,"name":"Plane 1","picture_url":"https://s3.amazonaws.com","pilots":[{"pilot_id":1,"header":"Jack Smith","details":"Jack Smith description","picture_url":"https://www.foobar.com","plane_id":1}],"passengers":[{"passenger_id":1,"name":"Passenger 1","details":"Passenger 1 details","picture_url":"www.toobar.com/","passenger_id":1}],"cabin":[{"cabin_id":1,"details":"Flight details","picture_url":"www.seatingchart.com","video_link":"www.skyview.com","passenger_passenger_id":1}]}]

To wrap this response as a key I used the 'json' gem which has it's own to_json method
get '/plane/all' do
  @plane = Plane.all(:order => :id.desc).to_json(:relationships => {:pilots => {}, :passengers => {}, :cabin => {}})
 { "planes" => @plane }.to_json
end

Here is the response
{"planes":"[{\"id\":2,\"name\":\"Plane 2\",\"picture_url\":\"https://s3.amazonaws.com\",\"pilots\":[{\"pilot_id\":2,\"header\":\"Bruce Wayne\",\"details\":\"Bruce loves his batwing that flies at an average speed of 200 mph\",\"picture_url\":\"www.marvel.com\",\"plane_id\":2}],\"passengers\":[{\"passenger_id\":2,\"name\":\"Passenger 2\",\"details\":\"These are the details for passenger 2\",\"picture_url\":\"www.toobar.com/\",\"plane_id\":2}],\"cabin\":[{\"cabin_id\":2,\"details\":\"Great Details for has been put in this cabin\",\"picture_url\":\"www.seatingchart.com\",\"video_link\":\"www.skyview.com\",\"passenger_passenger_id\":2}]},{\"id\":1,\"name\":\"Plane 1\",\"picture_url\":\"https://s3.amazonaws.com\",\"pilots\":[{\"pilot_id\":1,\"header\":\"Jack Smith\",\"details\":\"Jack Smith description\",\"picture_url\":\"https://www.foobar.com\",\"plane_id\":1}],\"passengers\":[{\"passenger_id\":1,\"name\":\"Passenger 1\",\"details\":\"Passenger 1 details\",\"picture_url\":\"www.toobar.com/\",\"plane_id\":1}],\"cabin\":[{\"cabin_id\":1,\"details\":\"Flight details\",\"picture_url\":\"www.seatingchart.com\",\"video_link\":\"www.skyview.com\",\"passenger_passenger_id\":1}]}]"}

Long story short, the JSON response I get has backslashes in it and JSON parser I'm using states it's only one object instead of the two I had previously.
Anyone who can help me out, it would be greatly appreciated.
Answer: Here is my workaround. If there is no view, then no need to use an instance variable.
def '/plane/all' do
    planes = Plane.all(:order => :id.desc).to_json(:relationships => {:pilots => {}, :passengers => {}, :cabin => {}})
    { "planes" => JSON.parse(planes) }.to_json
end


Clarification regarding proof: $ \langle x,2 \rangle$ is a maximal ideal of $\mathbb Z[x]$

Question: The question asked here mentions:

When the polynomial ring Z[x] is quotiented by the ideal (2,x) we get
a field as $\mathbb{Z}[x]/(x,2) \cong \mathbb Z/(2) \cong \mathbb{Z}_2$ which is a field.

I am not being able to flesh out my answer and connect the dots.
I know that $\frac{\mathbb Z[x]}{\langle x,2 \rangle }= \frac{\frac{\mathbb Z[x]}{\langle x \rangle }}{\frac{\langle 2,x \rangle}{\langle x \rangle}}$.
From here, I can individually show that: $\frac{\mathbb Z[x]}{\langle x \rangle} \cong \mathbb Z,$
and that, $\frac{\langle 2,x \rangle}{\langle x \rangle} \cong \langle 2 \rangle.$
How do I conclude that, $\frac{\frac{\mathbb Z[x]}{\langle x \rangle}}{\frac{\langle 2,x \rangle}{\langle x \rangle}}  \cong  \mathbb Z_{2}$?
It seems like I am trying to prove something in this format: $\frac{I}{J} \cong \frac{K}{H}$ because $I \cong K$ and $J \cong H.$ (I believe, this basic concept is essentially what my doubt is)
Am I thinking about this the wrong way?
Comment: See the first dupe for a general method (quotient reciprocity), and the 2nd dupe for the specific step you inquire about (which is linked in a comment in the first).
Answer: What you write works, but not the end. What you want to use is not "there is an isomorphism between $(x,2)/(x)$ and $(2)$" but "my isomorphism between $\mathbb Z[x]/(x)$ and $\mathbb Z$ identifies $(x,2)/(x)$ and $(2)$". It is this stronger statement that allows you to apply your isomorphism theorem:
$$\mathbb Z [x]/(x,2) \cong (\mathbb  Z[x]/(x))/((x,2)/(x)) \cong \mathbb Z/(2)$$
Comment: sorry this is the first time I'm coming across this so I want to clarify, I would have to use the same map then?
Comment: What the isomorphism theorem says is that if $I$ and $J$ are two ideals in a ring $A$, with $I \subset J$, then the canonical projection from $A/I$ onto $A/J$ induces an isomorphism $A/J \cong (A/I)/(J/I)$ (because the image $J/I$ of $J$ in $A/I$ is the kernel of the aforementioned projection). So if you have an isomorphism $A/I \cong B$, you need to use this isomorphism to identify $J/I$ with an ideal $K$ of $B$, and then the isomorphism $A/I \cong B$ clearly induces an isomorphism $(A/I)/(J/I) \cong B/K$.
Comment: But an abstract isomorphism between $J/I$ and some ideal of $B$ is useless for computing the quotient. Does that answer your question ? (With $A = \mathbb Z [x]$, $I = (x)$, $J = (2, x)$, $B= \mathbb Z$, and $K = (2)$, of course)
Answer: Here is an alternative method:
We have the substitution map $\mathbb Z[x]\to\mathbb Z:f(x)\mapsto f(0)$, which is clearly surjective. Composing with the canonical projection $\mathbb Z\to\mathbb Z_2$ gives us the subjective map $\mathbb Z[x]\to\mathbb Z_2:f(x)\mapsto\overline{f(0)}$. The kernel consists of polynomials with even constant terms, which is exactly the ideal $(x,2)$. Thus, the isomorphism theorem tells us that $\mathbb Z[x]/(x,2)\cong\mathbb Z_2$.
Answer: It's not the maximal ideal, there are others:  more generally $(x,p)$ is a maximal ideal and $\mathbb Z[x]/(x,p)\cong\mathbb Z_p$ is a field.
From what you did, the final step is merely that $\mathbb Z/(2)\cong\mathbb Z_2$.
In the linked answer there is a direct proof, which you can generalize, that this ideal is maximal.  It is also easy to prove that an ideal is maximal if and only if $\mathcal R/\mathscr I$ is a field.
Your last statement is false:  consider $\mathbb Z/(2)\cong \mathbb Z_4/(2)$.
Comment: It looks like the OP is trying to convince himself that $\mathbb Z[x]/(x,p)\cong \mathbb Z/(p)$ in the first place.


OxyPlot performance issue on larg data in WPF on InvalidatePlot

Question: I'm using OxyPlot in my wpf application as line recorder. It's like the LiveDemo example.
On a larg visible data set, I get some UI performance issues and may the whole application could freez. It seems to be PlotModel.InvalidatePlot which is called with to many points to often, but I didn't found a better way.
In deep:

Using OxyPlot 2.0.0
I code all in the PlotModel. The Xaml PlotView is only binding to the PlotModel.
I cyclical collect data in a thread an put them in a DataSource (List of List  which are ItemSoure for the LineSeries)
I have a class which calculates cyclical in a thread the presentation for x and y axis and a bit more. After all this stuff, it calls PlotModel.InvalidatePlot.

If I

have more than 100 k points on the display (no matter if in multiple LineSeries or not)
and add 1 DataPoint per LineSeries every 500 ms
and call PlotModel.InvalidatePlot every 200 ms

not only the PlotView has performance issues, also the window is very slow in reaction, even if I call PlotModel.InvalidatePlot (false).
My goal
My goal would be that the Windo / Application is working normally. It should not hang up because of a line recorder. The best would be if it has no performance issues, but I'm skeptical.
What I have found or tested
OxyPlot has Performance guidelines. I'm using ItemsSource with DataPoints. I have also tried adding them directly to the LineSeris.Points, but then the Plot doesn't refresh anyway (even with an ObservableCollection), so I have to call PlotModel.InvalidatePlot, what results in the same effect. I cannot bind to a defined LineSeries in Xaml because I don't know how much Lines will be there. Maybe I missed something on adding the points directly?
I have also found a Github issue 1286 which is describing a related problem, but this workaround is slower in my tests.
I have also checked the time which is elapsed on the call of PlotModel.InvalidatePlot, but the count of points does not affect it.
I have checked the UI thread and it seems it have trouble to handle this large set of points

If I zoom in to the plot and display under 20 k Points it looks so

Question:
Is there a way to handle this better, except to call PlotModel.InvalidatePlot much less?
Restrictions:
I also must Update Axis and Annotations. So, I think I will not come around to call PlotModel.InvalidatePlot.
Answer: I have found that using the OxyPlot Windows Forms implementation and then displaying it using Windows Form integration in WPF gives much better performance.
e.g.
var plotView = new OxyPlot.WindowsForms.PlotView();
plotView.Model = Plot;

var host = new System.Windows.Forms.Integration.WindowsFormsHost();
host.Child = plotView;

PlotContainer = host;

Where 'Plot' is the PlotModel you call InvalidatePlot() on.
And then in your XAML:
<ContentControl Content="{Binding PlotContainer}"/>

Or however else you want to use your WindowsFormsHost.
Answer: I have a similar problem and found that you can use a Decimator in LineSeries. It is documented in the examples: LineSeriesExamples.cs
The usage is like this:
public static PlotModel WithXDecimator()
{
  var model = new PlotModel { Title = "LineSeries with X Decimator" };
  var s1 = CreateSeriesSuitableForDecimation();
  s1.Decimator = Decimator.Decimate;
  model.Series.Add(s1);
  return model;
}

This may solve the problem on my side, and I hope it helps others too. Unfortunately it is not documented in the documentation
Answer: For the moment I ended up with calculating the time for calling InvalidatePlot for the next time. I calculate it with the method given in this answer, wich returns the number of visible points. This rededuce the performance issue, but dosent fix the block on the UI Thread on calling InvalidatePlot.


preciso arrumar meu if

Question: Estou fazendo um site de busca no banco e tenho o seguinte código
<?php
include("conexao.php");

$pesquisar = $_POST['pesquisar'];
$result_produtos = "SELECT * FROM produtos WHERE nome LIKE '%$pesquisar%' LIMIT 5";
$resultados_produtos = mysqli_query($conexao, $result_produtos);

if($pesquisar == ""){
    echo "1"
;}else if($pesquisar != $result_produtos){
    echo "2"
;}else{
    while($rows_produtos = mysqli_fetch_array($resultados_produtos)){
        echo "O produto: ".$rows_produtos['nome']."
"
        ;}
    ;}
?>

o $pesquisa vem de um input no formulário

quando estiver vazio tem que aparecer 1
se estiver errado aparece 2
se estiver no banco aparece o item

No banco só tem o campo arroz, porem quando eu escrevo arroz ele está aparecendo 2
Answer: ao invez de usar um = no if statment, tente usar um .contains ou .equals

preciso arrumar meu if


How can I use HTML in a field of paragraphs module

Question: I am using the paragraphs module. And I add a text field (plain,long). In this field I want to add e.g.

After rendering the output in browser is in quotation marks like this
""

How can I avoid it?
Comment: Plain text fields don't accept html.
Answer: Make it a body field, and then edit the source - put your HTML in there
Comment: I think this is for authors too complicated.
Comment: What do you mean @lesleyn.? Authors shouldn't use HTML?


EC2 - Connect to running instance by using the API

Question: I create an EC2 instance via the provided interface, and I am using the AWS API to connect to the existing running instance, but when I run the following code I get "You have 0 Amazon EC2 instance(s) running.":
DescribeAvailabilityZonesResult availabilityZonesResult = ec2.describeAvailabilityZones();
System.out.println("You have access to " + availabilityZonesResult.getAvailabilityZones().size() +
                " Availability Zones.");

DescribeInstancesResult describeInstancesRequest = ec2.describeInstances();
List<Reservation> reservations = describeInstancesRequest.getReservations();
Set<Instance> instances = new HashSet<Instance>();

for (Reservation reservation : reservations) {
    instances.addAll(reservation.getInstances());
}

System.out.println("You have " + instances.size() + " Amazon EC2 instance(s) running.");

Do you have any ideas about what might be the problem?
Answer: If you double checked that your instances are actually up and running, they most likely are not in the "us-east-1" instance region (which is the default one that the AWS SDK assumes).
So set your AmazonEC2Client instance to point to the correct endpoint and everything should be fine, e.g. for Europe (Ireland):
ec2.setEndpoint("ec2.eu-west-1.amazonaws.com");

More details, as well as links to where you can find the endpoint strings, in this SO answer.
Comment: Thanks a lot for this, it worked. Is there a way to automatically get this information?
Comment: I am at least not aware of any such method.


Find the least(smallest) natural number for (n)

Question: If for sets $A_1$,$A_2$ and $A_3$, we have :
$$A_1=\{2,3,4,..,200\}$$ $$A_2=\{5,6,7,...,199\}$$$$A_3=\{8,9,10,...,198\}$$then what's the smallest natural number $n$ , for which $(A_1∩A_2∩A_3∩...∩A_n) =∅$
Comment: This is a math olympiad question, please help me with it
Answer: Since each set is a subset of the preceding one, the intersection is just the last set.  How many elements are in set $A_i$?  When is it zero?
Comment: Nothing else is mentioned in the problem
Comment: You are clearly expected to extrapolate the sets $A_4, A_5 \ldots$ from the pattern.  The problem is very badly stated not to say that.
Answer: Note that any $A_n=\{3n−1,3n,..,201−n\}$.
$A_{n+1}$ will be a subset of $A_n$ for all n $\implies (A_1∩A_2∩A_3∩...∩A_i)=A_i$
Also, $A_n$ will be a null set when $3n-1>201-n\implies n>202/4\implies n=51$
Comment: But yet would you please explain why should 3n-1 be larger than 201-n so that An is going to be a null set?
Comment: @Prophet you're welcome. As I said, the set is $A_n=\{3n−1,3n,..,201−n\}$. If $3n-1<201-n$, my set will still have those elements. Even if $3n−1=201−n$,my set will have one element (it isn't possible in this case btw otherwise n won't be an integer). I hope it helps :)


List of machine learning classifiers that naturally assume data in normal distribution

Question: I have searched about this question but no answer really made it comprehensive. To my knowledge, linear regression and most clustering algorithms naturally have the assumption that data need to be in normal distribution for better outcomes. My question is about other classifiers like SVM, NN, KNN, ... etc. Can someone provide us a good answer or direct me to an existing post that elaborate this?
Thank you
Comment: Adding to stans' comment, Gaussian Naive Bayes (the most common NB classifier used for continuous features) also assumes normality of the features.
Comment: @stans: [do you want to post your comments as an answer?](https://stats.meta.stackexchange.com/a/5326/1352)
Comment: @Stephan Kolassa: sure, if you think they are exhaustive enough to qualify as an answer.
Answer: Cannot agree to this. Linear regression is statistically efficient if the residuals are Gaussian. The whole data do not have to be Gaussian. Even that condition (normality of residuals) is unnecessary if the sample size is big... Except for a few degenerate cases, most popular clustering algorithms do not require normality.
Regarding classification: to the best of my knowledge, only Linear Discriminant Analysis and Quadratic Discriminant Analysis are derived under the assumption of normality. Still, they perform quite well in many other settings.
Comment: Thank you! Better to have a short answer than no answer at all. Anyone who has a better answer can post it.


Barra de progresso só aparece quando o download termina

Question: Galera é o seguinte, eu estava fazendo uma barra de progresso para um download de um arquivo na web, mas não funciona. Quando executo o código, a janela do tkinter fica travada e só retorna quando o download termina. Alguém sabe em que estou errando? Já estou há 2 dias nesse problema. Segue a parte do código abaixo:
def read_bytes(self):
with open(file_name, "wb") as f:
    response = requests.get(linkd, stream=True)
    total_length = response.headers.get('content-length')
    if total_length is None:
        f.write(response.content)
    else:
        dl = 0
        total_length = int(total_length)
        for data in response.iter_content(chunk_size=4096):
            dl += len(data)
            f.write(data)
            self.bytes = dl
            self.progress["value"] = self.bytes
            if self.bytes < self.maxbytes:
                self.after(100)
            elif self.bytes >= self.maxbytes:
                self.exit = ttk.Label(self, text="Terminado",
                                       background = 'black',
                                       foreground = 'white')
                                       self.exit.pack()

Answer: O problema não é a barra de progresso que trava o programa, mas sim o código de download. A interface gráfica do tkinter roda sempre na main thread e mais nenhum código pode rodar nela a partir do momento que você executa o mainloop ou sua interface poderá travar.
Um bom exemplo disso é a função time.sleep que faz o programa dormir e trava a interface:
def btn_function():
    time.sleep(2)

root = Tk()
Button(root, text = "Aguardar 2 segundos", command = btn_function).pack()
root.mainloop()

No exemplo acima, o programador que criou o código pensava que poderia fazer o programa apenas aguardar com o time.sleep sem travar a interface, mas isso não ocorre pois a função é chamada na thread principal.
"Mas o meu código não pede para o programa dormir, ele só faz download de um arquivo."
Realmente, mas existe uma espera até que o download seja feito, sendo justamente essa espera que afeta a interface e faz ela travar por um tempo.
A solução para isso é criar uma Thread, para que a execução do seu download não afete a execução da interface gráfica.
Veja este exemplo:
from tkinter import *
from threading import Thread
import requests

def download():
    response = requests.get("<url>")
    with open('page.html','wb') as file:
        file.write(response.content)

def btn_function():
    print("Downloading...")
    Thread(target = download).start()

root = Tk()
Button(root, text = "Download", command = btn_function).pack()
root.mainloop()

Comment: Obrigado mano! Adaptei meu código com esse conceito que você apresentou e aparentemente deu certo, ótima explicação. Assunto resolvido :)


How to assign a data attribute of a subclass to attributes of its parent class

Question: I have a class Rectangle with data attributes width and height, I want a subclass Square with data attribute side_length.
How do I make it so that square.width and square.height give its side length? i.e same as square.side
class Rectangle:
    def __init__(self, width, height):
        self.width = width
        self.height = height

class Square(Rectangle):
    def __init__(self, side)
        self.side = side

This is what I have so far.
Comment: What do you mean by this statement ? __"square.width and square.height give its side length"__
Comment: For an instance of the class Square (that I've also called square), when I use square.width or square.height to return the data attributes width and height, which are attributes of the parent class Rectangle, I would like these to return the same value as square.side (where square is an attribute of the class Square) since a squares side lengths are the same for width and height
Answer: You could call the constructor for Rectangle.
super(Square,self).__init__(side, side)
or you could have properties to return those attributes.  I'd edge towards the super.
@property
def length(self):
   return self.side

@property
def width(self):
   return self.side

Things get more complicated if you can change the side, height or width attribute after creating the object.  You need to keep width and height synched and coherent.  One possible way is to do away entirely with side as a stored attribute on Square and instead have it as a read-write property that updates Rectangle's width and height.
to keep height/width/side sorted after the initial constructors:

class Rectangle:

    @property
    def height(self):
        return self._height

    @height.setter
    def height(self, value):
        self._height = value

    @property
    def width(self):
        return self._width

    @width.setter
    def width(self, value):
        self._width = value

    def __repr__(self):
        return(f"{self.__class__.__name__}:{self.height=} {self.width=}")

    def __init__(self, height, width):
        self.height = height
        self.width = width

class Square(Rectangle):

    def __repr__(self):
        return(f"{self.__class__.__name__}:{self.side=}")

    @property
    def side(self):
        return self._width

    @side.setter
    def side(self, value):
        self._width = value
        self._height = value

    def __init__(self, side):
        super(Square, self).__init__(side, side)

    #these are here so you can't cheat and vary height and width
    #independently on a square
    @property
    def width(self):
        return self.side

    @width.setter
    def width(self, value):
        self.side = value

    @property
    def height(self):
        return self._side

    @height.setter
    def height(self, value):
        self.side = value

rectangle = Rectangle(5,2)
print(rectangle)
rectangle.height = 6
print(rectangle)

square = Square(3)
print(square)
square.side = 6
print(square)
square.height = 9
print(square)

output:
$ py test_square.py
Rectangle:self.height=5 self.width=2
Rectangle:self.height=6 self.width=2
Square:self.side=3
Square:self.side=6
Square:self.side=9

Comment: I would like to be able to change the side length attribute after creation since I have methods defined on the rectangle class to change width and height. Any pointers on how to do this?
Comment: @ogprog: If being able to reconfigure the side lengths independently from each other after construction is a feature of your Rectangle class, then your Square breaks Liskov substitution - you cannot do things with a Square that you can with a Rectangle. In that case, your Square class should not be a Rectangle subclass, or you should remove the side length reconfiguration feature from Rectangle.
Comment: @user2357112supportsMonica  not necessarily.  If you consider that altering width or height of a Square is the same as altering the side *and you write properties accordingly* then you don't break LSP.  this is what I did here.  Is the overall idea good OOP?  Mmmmm, not at all sure but at least a square remains a square *in this particular constrained scenario* and I had fun with setters which I rarely use.
Comment: @JLPeyret that's great thank you! I think that is as as we can get to the specification of the programme I'm trying to build, whilst still keeping the height setter methods on the Square


How to animate a mesh created outside init() in three.js?

Question: I am learning three.js and would like to understand how to animate a mesh created by a function outside the regular init().
I'm able to create a cube inside init() and rotate it inside animate(), but if the cube is created by a function outside init() the console says that cube is not defined.
Here's a quick example : http://jsfiddle.net/mattsparrer/yqbp5hx4/10/
function createCube(size) {
    var geometry = new THREE.CubeGeometry(size, size, size);
    var material = new THREE.MeshNormalMaterial();

    cube = new THREE.Mesh(geometry, material);
    scene.add(cube);
    }

By searching on the web I understand "cube" is not in the scope of animate(), but I can't find the proper way to do it.
Please can someone explain the way to go ?
Comment: I've changed a bit the [fiddle](http://jsfiddle.net/prisoner849/uotj19g5/)
Comment: Thanks for your help @prisoner849 I was looking for something like bind() or creating a loop like the example from Yakudoo, but in fact it was a bit obvious to create the cube before animate it...
Answer: This isn't so much a Three.js question, but more of a JavaScript variable scope question.
If you declare the cube variable within the init() function, it will only be available inside init(), but not inside render(). You have to declare it outside both these functions for it to be available to both.
Wrong:
function init(){
    // Declaring cube inside this function limits its scope
    var cube = new THREE.Mesh();
}

function render(){
    // Cube is not defined.
    // it's only available within the init() function.
    cube.rotation.y += 0.01;
}

console.log(cube); // Cube is also not defined out here.

Correct:
// Declare cube in global scope so both functions can "see" this variable
var cube;

function init(){
    // Assigns value to existing cube var
    cube = new THREE.Mesh();
}

function render(){
    // cube is also available inside this function
    cube.rotation.y += 0.01;
}

console.log(cube); // No error, because cube exists out here too

For more examples about variable scope, see here: What is the scope of variables in JavaScript?
Comment: Thanks @Marquizzo I tried it before posting, my mistake was to believe that the place of animate() in the script wasn't important
Comment: Ah, order of operations is also very important. If you call `animate` before calling `createCube` then there won't be any cube to animate! It should be 1: `init();` 2:`createCube(150);` and 3: `animate();`


How should I normalize my accelerometer sensor data?

Question: I'm working with a large set of accelerometer data collected with multiple sensors worn by many subjects. Unfortunately, nobody here seems to know the technical specifications of the devices and I don't think they have ever been recalibrated. I don't have a whole lot of info about the devices. I'm working on my master's thesis, the accelerometers were borrowed from another university and altogether the situation was a bit intransparent. So,  preprocessing on-board the device? No clue.
What I do know is that they are triaxial accelerometers with a 20Hz sampling rate; digital and presumably MEMS. I'm interested in nonverbal behavior and gesturing, which according to my sources should mostly produce activity in the 0.3-3.5Hz range.
Normalizing the data seems quite necessary, but I'm not sure what to use. A very large portion of the data is close to the rest values (raw values of ~1000, from gravity), but there are some extremes like up to 8000 in some logs, or even 29000 in others. See the image below. I think this makes it a bad idea to divide by the max or stdev to normalize.
What's the usual approach in a case like this? Divide by the median? A percentile value? Something else?
As a side issue, I'm also not sure if I should clip the extreme values..
Thanks for any advice!
Edit: Here is a plot of about 16 minutes of data (20000 samples), to give you an idea of how the data is typically distributed.
Comment: Can you provide a little more information on your measurement setup? Questions that come to mind: (**1**) Are these single-axis accelerometers or multi-axis? (**2**) Are they high-pass filtered or not and, if so, how? (It sounds like they are not, based on your description.) (**3**) What exactly are you measuring and what is the frequency range of the signal of interest? (**4**) What is the sensing mechanism (i.e., MEMS, piezoelectric, capacitive, etc.) or, even, part number(!) of the accelerometers you are using? ...
Comment: What are you trying to find out from these data? Are you perhaps trying to detect certain kinds of events, estimate frequencies of events, estimate mean accelerations, find correlations among different accelerometers, ...? The point is that if you would like good, relevant advice, don't ask about technical procedures with the data (which may be irrelevant or even useless, depending on the application): first tell us what *problem* you are trying to solve.
Comment: ... (cont) (**5**) Are these fully digital or do you have your own ADC (16-bit, maybe, by the description you give)?
Comment: @cardinal: I edited in the answers to your questions, thanks for asking. Not sure what an ADC is. I was involved in the experiment, but not in the extraction of the data from device memory, there's a gap between data collection and where I received a bunch of binary logs.
Comment: Hi, Junuxx. Sorry for the unexplained acronym (ADC="analog-to-digital converter"); I implicitly assumed you'd recognize it based on your question.
Comment: @cardinal: Ah, right. Does it matter for the normalization issue whether it's fully digital?
Comment: @whuber: As stated in the question I'm interested in gestures and social behavior. I'm using several machine learning techniques (HMMs, SVMs and others) to classify behavior types such as hand gestures, speech, laughter from this data. Also walking and a few postures for variety. I have some reasonable results already, I'm trying to understand whether some type of normalization could/should improve results. Dividing by the max for every subject looks like a bad idea here. I tried subtracting the mean but it did not have a noticeable effect.
Comment: Thanks. However, I still haven't seen enough information to answer the question: without knowing about the specific techniques you intend to use and what kinds of data characteristics you are looking for in order to identify and classify "behaviors" based on *acceleration components,* it's impossible to say whether standardization is needed or what kind of standardization might help.
Comment: @whuber: Well it varies really; the goal is compare a host of features and classifiers. But I'm training and testing on short windows of data, say 1-5 seconds, which I've manually annotated. Features include the windows' mean, standard deviation, skewness, kurtosis, and also FFT magnitudes. All features can be computed for each axis separately, or from the vector magnitude. So that's up to 12 features from the time domain and, in most cases, 21 features from the frequency domain per instance/window. Sorry for not being clear enough in the first place; don't mean to be a help vampire!
Comment: No problem. The situation is getting clearer, but I'm having a hard time seeing how any of those features would be related to gestures (except possibly some of the FT amplitudes). Wouldn't you be chiefly interested in detecting the occurrences of short, large accelerations and perhaps also in knowing their directions?
Comment: How did you get to synchronise all the multiple sensors. By this I mean how did you get data from all the sensors at a certain time t, without delays or misreads. Meaning at time t you have the corresponding precise values for that instant from all the sensors. Regards,
Comment: The sensor devices we used were all wirelessly connected to nodes which sent pulse signals for synchronization.
Comment: yes, but how did you treat those signals/messages arriving from those nodes? what programming language did you use? My concern is when I save the data. I want to associate it with a timestamp. If I have several nodes transmitting I want to make sure I get the data from all the sensors in the same instant.
Answer: The raw signals you show above appear to be unfiltered and uncalibrated. Appropriate filtering and calibration, with some artifact rejection will in effect normalize the data.
The standard approach with accelerometer data is the following:

Filter - e.g. 4th order, zero-phase IIR lowpass or bandpass filter
Artifact rejection - threshold based
Calibrate - Ferraris et al method (Procedure for effortless in-field
calibration of three-axis rate gyros and accelerometers, F Ferraris,
U Grimaldi, M Parvis - Sensors and Actuators, 1995) method works
well for this.

It is advisable to perform artifact rejection on inertial sensor data. I would be concerned that you don't know the provenance of the data, and so you cannot guarantee that the sensors were affixed correctly and consistently (in terms of orientation and physical placement) to all subjects. If the sensors were not affixed correctly, you can get a lot of artifact in the signals, as the sensor can move relative to the body-segment. Similarly, if the sensors were orientated differently (in how they were placed) on different subjects, the data will be difficult to compare across subjects.
Given the size of the outliers you report they seem likely to be artifacts. Such artifacts would almost certain skew any calibration calculation (though their effect will be lessened by appropriate filtering) and so calibration should be performed after artifact rejection.
A simple threshold may work well for an initial artifact rejection routine, i.e. remove (or replace with NaN) all samples above a certain empirical threshold. More sophisticated techniques will adaptively calculate this threshold using a running mean or moving window.
Depending on the location of the sensor you may also wish to correct for the influence of gravity on the acceleration signals, though detailed understanding on sensor axes and positioning is crucial here. The Moe-Nillson method (R. Moe-Nilssen, A new method for evaluating motor control in gait under real-life environmental conditions. Part 1: The instrument, Clinical Biomechanics, Volume 13, Issues 4–5, June–July 1998, Pages 320-327) is the most commonly used and works well for lower back mounted inertial sensors.
A good place to start on examining the data for gesture recognition would be to break the filtered, calibrated data into epochs (e.g. 10s) and calculate a number of features per epoch and relate these to the labels you have for the data, I can't offer more specific advice without knowing more about the data set and the associated labels.
Hope this helps.
Comment: That's an amazing reply @BGreene, thank you very much! References are very useful too. I wish I had asked this question a few months ago. The sensors were worn on a cord around the neck (not my idea), so there is definitely a lot of movement relative to the body. Some of your suggestions might be more suitable for further research I think, but at least they'll be helpful for my Future Work section. And fortunately the recognition part is not the problem, I do have a fairly solid background in machine learning, but thanks for the suggestions on that too.
Comment: No problem. In that case I'll think you'll be limited to examining gross movements as a cord means that you can't reliably say how the body was moving, only the sensor. You could possibly infer that large sensor output values equate with large gross movements but you do lose a lot the crispness of a properly affixed sensor.
Comment: (+1 yesterday) A couple of things might be taken into account in (1.) above. Since the lower bound of the frequency range of interest is pretty small, one alternative to consider is simply to apply a low-pass filter and subtract the mean. Second, instead of an IIR filter, one might consider a linear-phase finite-impulse-response filter in this instance. I say this because I suspect that to predict gestures by using the multi-axis accelerometer signal, one will want to keep the movement synchronized independently of frequency. (cont.)
Comment: (...) The nonlinear phase response of an IIR filter will shift different components by different amounts and this effect tends to be worse near the cutoff frequencies. Since everything is digital, it makes sense to go with a linear-phase FIR filter. Oftentimes one also has better control of the transient response as well. :-)
Comment: @cardinal thats all true - have edited my response above. just checked my code - my most recent accelerometer algorithm uses a zero-phase Butterworth IIR filter. Though I prefer to avoid subtracting the mean for short data segments
Comment: @BGreene: Thanks for your follow-up remarks. I see my comment on subtracting the mean may not have been as clearly stated as I intended. I simply meant that as an alternative (in conjunction with a LPF) to a bandpass filter, in effect only removing the DC component instead of rolling off at low frequencies which might distort some of the desired signal of interest given its low frequency. Nice answer. :-)


'heroku local' cannot find module 'load-foreman-procfile'

Question: I'm trying to run Heroku applications locally via 'heroku local,' but a missing module error is occurring in the Heroku CLI. Is this a Heroku bug that just needs to be reported or is there something wrong with how things have been setup on my machine (mac)? Any suggestions are appreciated.
In order to ensure my application isn't the problem, I've been debugging this issue with the node application Heroku provides in its getting started guides. Meaning, it already has a Procfile that can be run using default settings.
Things I've tried:

Re-install node modules for both application and CLI
Re-install the Heroku CLI

Here's the error:
node-js-getting-started [master] :> heroku local
Error: Cannot find module '../../load-foreman-procfile'
    at Object.<anonymous> (/usr/local/Cellar/heroku/7.26.1/libexec/node_modules/@heroku-cli/plugin-local/lib/commands/local/index.js:5:18)

The file for the route above requires a 'load-foreman-procfile' like so:
const Procfile = require('../../load-foreman-procfile');

That require path doesn't lead to a to file by that name. In fact, this is the only reference to 'load-foreman-procfile' I can find in '/usr/local/Cellar/heroku/7.26.1'.
Rather than the error code above, I would expect heroku local to yield a running local server started via my Procfile.
Answer: I got the same error running heroku-cli v7.26.0. I switched to their edge channel (currently v7.26.2) and heroku local worked for me after that.
Comment: For mac I'm not sure. I'm on ubuntu and the way I did it was run
```sudo snap refresh heroku --classic --edge```
Comment: Thanks @sophon. How did you switch channels? Oddly enough, ```heroku -v``` returns ```7.26.2``` on my end. But the error obviously is looking for information in the 7.26.1 directory.
Answer: like @sophon mentioned - updating from v7.26.0 to v7.26.2 solved this for me. heroku update on mac did the trick.


Como posso retornar dados que estão dentro de arrays?

Question: Estou usando este código para puxar características de um determinado produto:
<?php

$array = array(
    'key'       => '46dfg456465g4d654d65f4564dfg',
    'module'    => 'imoveis',
    'method'    => 'listar_origens'
);

$client = new SoapClient(null, array (
    'uri'       => 'http://soap.imo.bi/',
    'location'  => 'http://soap.imo.bi/soap.dll',
    'trace'     => 'trace'
));

$res = $client->get($array);

echo "
";
    print_r($res);
echo "
";

?>

Uma destas características é o campo [field] o qual preciso recuperar 250 vezes pois existe 250 valores diferentes para este campo. O resultado do script é este:
Array
(
    [0] => Array
        (
            [alias] => imo.DATA
            [field] => DATA
            [description] => Data cadastro
            [type] => Data
            [field_site] =>
        )

Ao colocar $res[0]['field'] ele me retorna o primeiro valor que é DATA e assim por diante conforme vou mudando os valores. Quero de forma dinâmica dentro de um loop recuperar os 250 valores de uma vez. Peço auxílio!!!
Comment: Testa `foreach($res as $item){ echo $item['field']; }`
Comment: Não tenho conhecimentos de PHP, mas creio que um loop resolveria essa situação, não?
Comment: Esse resultado está completo? Ou ele continua 0,1,2...?
Answer: Basta efetuar um loop, por exemplo:
Usando FOR
for($i = 0; $i < count($res); $i++){
echo $res[$i]['field'];
}

Usando FOREACH
foreach($res as $field){
echo $field['field'];
}

De ambas as maneira, ele irá resultar no valor em presente em $res[0]['field'], $res[1]['field'], $res[2]['field']...
Answer: Se tens uma array que tem dentro de cada elemento uma outra array associativa, podes fazer um loop da primeira e dentro do loop fazer echo dessa chave do elemento da primeira array que está a ser iterada.
Exemplo:
echo "
";
foreach($res as $item){
    echo $item['field'];
}
echo "
";


SQL Server Conditional statement in Where Clause

Question: I need to write a SQL query that retrieves records based on supplied RoleId.
e.g.

If RoleId = 1 THEN _t1.CreatedBy = @LoginUserId.

For other RoleId, I want all records from table without any condition on CreatedBy column.
I am providing sample query as per my requirement.
SELECT _t1.*
FROM [dbo].[TblPassDetail] _t1 WITH (NOLOCK)
INNER JOIN [dbo].[TblVisitor] _t2 WITH (NOLOCK) ON _t1.VisitorId = _t2.SrNo
WHERE _t1.LocationId = @LocationId
  AND _t1.CreatedBy = (CASE WHEN @RoleId = 1 THEN @LoginUserId ELSE 0 END)

Issue is that if supplied @RoleId is 1, I am getting all records for that LoginUserId, but if @RoleId is anything other than 1, then I am not getting any records as SQL checking records for _t1.CreatedBy = 0 which doesn't exist in the table.
Any suggestion on how to rewrite my query?
Answer: You can rephrase the difficult part of your WHERE clause to this:
@RoleId = 1 AND _t1.CreatedBy = @LoginUserId
OR
@RoleId <> 1

In other words, if the RoleId is 1, then the logged in user must be the creator.  But for other RoleId values there is no such dependence on the logged in user.  Here is the full query:
SELECT _t1.*
FROM [dbo].[TblPassDetail] _t1 WITH (NOLOCK)
INNER JOIN [dbo].[TblVisitor] _t2 WITH (NOLOCK)
    ON _t1.VisitorId = _t2.SrNo
WHERE
    _t1.LocationId = @LocationId AND
    (
        (@RoleId = 1 AND _t1.CreatedBy = @LoginUserId) OR
        @RoleId <> 1
    );

Comment: Hi Tim, Thank you so much, my query worked perfectly by replacing CASE WHEN statement with the above 'AND-OR' combination. I am struggling with several combinations of CASE WHEN statement for this.
Thanks Again.
Have a nice day.
Answer: One way of achiving this would be to convert your CASE statement into an OR:
SELECT _t1.*
FROM [dbo].[TblPassDetail] _t1 WITH (NOLOCK)
     INNER JOIN [dbo].[TblVisitor] _t2 WITH (NOLOCK) ON _t1.VisitorId = _t2.SrNo
WHERE _t1.LocationId = @LocationId
      AND ( (_t1.CreatedBy = @LoginUserId AND @RoleID = 1) OR @RoleID <> 1)

Another way, kind of a workaround would be the following, but since LIKE is used, you would need to check the execution plan and performance of it:
SELECT _t1.*
FROM [dbo].[TblPassDetail] _t1 WITH (NOLOCK)
     INNER JOIN [dbo].[TblVisitor] _t2 WITH (NOLOCK) ON _t1.VisitorId = _t2.SrNo
WHERE _t1.LocationId = @LocationId
AND _t1.CreatedBy LIKE (CASE WHEN @RoleId = 1 THEN @LoginUserId ELSE '%%' END)

Comment: Thanks Rigerta for your reply. I resolve my issue by using 1st approach.
Answer: Get all records when <> 1
(@RoleId = 1 AND _t1.CreatedBy = @RoleId) OR ISNULL(@RoleId,0)<> 1


Fixed effects at industry & year level for firm-level data

Question: Various papers that study firm-level effects include dummy variables at the industry & year level.
From what I understand, calculating fixed effects requires panel data, i.e. (for firm-level data) unique firm-to-year matches.
But unless there is exactly one firm per industry, there can be no unique matches for the fixed effects we are looking at, i.e. no unique industry-to-year matches.
My questions are:
(1) Is the common way to deal with this to obtain the average (of the dependent variable) across all firms per industry for each year? This average could then be included as a regressor.
(2) Or should I obtain de-meaned values of the dependent variable per industry and year, and include this as a regressor. I.e., for each observation, create one new variable that contains this observation minus the industry mean (across all years in the sample) and one that contains the observation minus the year mean (across all industries in the sample)?
Or (3) should I just include industry and year dummy variables instead?
Comment: I would go with option 3. I do not imagine estimation of that many coefficients of dummy variables should be problematic. With the other methods I would think you risk the standard errors are not correct even if you get a consistent estimator.
Answer: As Jesper Hybel has mentioned in his comment, you can go with option (3). The least-squares dummy variable (LSDV) estimator and the de-meaning approach (1) give you the same results. LSDV has the advantage that it easily allows you easily extract the values of the fixed-effects (if you are not only interested to control for industry and year heterogeneity but also want to see, for example, which industries have particularly large values of the dependent variable).
There are some (theoretical) issues with the LSDV that it might be inconsistent if the number of industries or years go to infinity (this is called the incidental parameter problem; the issue is that you would have to estimate an infinite number of parameters or dummies in that case). This is not problem with the demeaning approach. For applied researchers this is in my view however not a problem.
There are excellent answers regarding the equivalence of the least-squares dummy variable estimator and the de-meaning approach, see here or here
(2) is a related but somewhat different approach called Mundlak approach (there are similar alternatives with other names) which allows you to estimate the effect of, for example, time-invariant variables which would cancel out in the LSDV or the de-meaning fixed-effects approach.
Comment: There is an excellent post here on the difference in standard errors [link](https://stats.stackexchange.com/questions/140364/is-fixed-effects-model-using-demeaning-equivalent-to-the-lsdv-model)
Comment: Thanks for the valuable remark, one should of course take into account that the averages subtracted are estimated while calculating the standard error / p-values in the de-meaned approach.


Simple formula for integer polynomial with $2\sin(2\pi/n)$ as a root?

Question: Is there a simple formula an integer polynomial that $2\sin(2\pi/n)$ satisfies?
For $2\cos(2\pi/n)$ the answer is relatively nice.  For any given $n$, we have $2\cos(2\pi/n)= z + z^{-1}$ where $z = e^{2 \pi i/n}$ satisfies a cyclotomic polynomial of degree $\varphi(n) = 2k$,
$$
0 = a_{2k}z^{2k} + a_{2k-1}z^{2k-1} + \ldots + a_{1}z + a_0,
$$
where $a_{i} = a_{2k-i}$.  Dividing by $\zeta^k$ gives
$$
0 = a_{2k}z^k + \ldots + a_k + a_0z^{-k}
$$
Using the symmetry of the coefficients lets us write this as
$$
0 = a_0(z^k+z^{-k}) + \ldots + a_k.
$$
Then
$$
(z+z^{-1})^2 = z^2 + z^{-2} + \binom{2}{1}
$$
$$
(z+z^{-1})^3 = z^3 + z^{-3} + \binom{3}{1}(z+z^{-1})
$$
$$
(z+z^{-1})^4 = z^4 + z^{-4} + \binom{4}{1}(z^2+z^{-2}) + \binom{4}{2}
$$
and so on, and in the end we get something fairly nice.
What happens with $2\sin(2\pi/n)$?
EDIT: I am aware that $2\sin(2\pi/n) = -i(z - z^{-1})$.
EDIT: Arturo's comment made me realize that dividing by $(-z)^k$ or $(iz)^k$ may be the way to go.
Comment: Doesn't a similar argument hold, using the fact that $2\sin(\pi/n) = iz^{-1}-iz$, with $z$ satisfying a cyclotomic polynomial? Use the fact that $\zeta_n=e^{2\pi i/n} = \cos(2\pi/n) + i\sin(2\pi i/n)$, where $\zeta_n$ is a primitive $n$-th root of unity, so $\zeta_n - \zeta_n^{-1} = 2i\sin(2\pi i/n)$.
Answer: A similar, but much simpler answer than Douglas's results if one uses the Chebyshev polynomials of the second kind
$$U_n(x)=\frac{\sin((n+1)\arccos(x))}{\sin(\arccos(x))}$$
in which case, the (monic) polynomial with integer coefficients you need is $U_{n-1}\left(\frac{x}{2}\right)$.
Answer: If you have an integer polynomial $p(x)$ with $\cos(2\pi/n)$ as root, then you can construct an integer polynomial $q(y)$ with $\sin(2\pi/n)$ as root. Namely, you can write
$$ p(\sqrt{1-y^2}) = q_1(y)\sqrt{1-y^2}  + q_2(y) $$
and we can set $q(y) := q_2(y)^2 - q_1(y)^2(1-y^2)$. Of course, this polynomial is not the minimal polynomial of $\sin(2\pi/n)$ as it is invariant under $y \to -y$, but it's better than nothing.
Comment: I hadn't thought of this.  Very nice.
Answer: $\zeta_n=\cos (2\pi/n)+i\sin(2\pi/n)$ so $i\zeta_n=i\cos (2\pi/n)-\sin(2\pi/n)$ and adding conjugates of both gives $i(\zeta_n-\zeta_n^{-1})=2\sin(2\pi/n)$. you can probably work from there
Answer: I'll work with $\sin \frac{2 \pi}n$ instead of $2 \sin \frac{2 \pi}n$.
Since $\sin x = \cos (\frac \pi 2 - x)$, $\sin \frac{2 \pi}n = \cos (\frac {\pi}2 - \frac {2\pi}n) = \cos \frac{n-4}{2n}\pi$.
The Chebyshev polynomials of the first kind $T_k(x)$ have the property that $T_k(\cos x) = \cos kx$. They have integer coefficients since they satisfy the recurrence $T_0(x)=1, T_1(x)=x, T_{k+1}(x) = 2xT_k(x)-T_{k-1}(x)$.
$T_{4n}(\sin \frac {2 \pi}n) = T_{4n}(\cos \frac{n-4}{2n}\pi) = \cos((n-4) \times 2\pi) = 1$.
Therefore, $\sin \frac{2\pi}n$ is a root of $T_{4n}(x)-1$.
$2 \sin \frac{2 \pi}n$ is a root of $T_{4n}(x/2)-1$, but you may have to clear denominators to get a polynomial over the integers. Of course, this is far from the minimal polynomial.


how to pass --packages to spark-submit in Kubernetes managed cluster?

Question: I'm trying to use Snowflake spark connector packages in spark-submit using --packages
when i run in local, it is working fine. I'm able to connect to Snowflake table and returning a Spark DataFrame.
spark-submit --packages net.snowflake:snowflake-jdbc:2.8.1,net.snowflake:spark-snowflake_2.10:2.0.0 test_sf.py

but when i try to pass --master argument, its fails stating Snowflake class is not available.
spark-submit --packages net.snowflake:snowflake-jdbc:2.8.1,net.snowflake:spark-snowflake_2.10:2.0.0 --master spark://spark-master.cluster.local:7077 test_sf.py

Update:
I have tried all the options like --jars, extraClassPath on driver and executor and --packages, but nothing seems to be working.. is it because some problem in Spark standalone cluster
Latest update:
It is working when i specify the repository URL in --jars instead of file path. So basically i have to upload the jars in some repository and point to that.
error log:
Caused by: java.lang.ClassNotFoundException: net.snowflake.spark.snowflake.io.SnowflakePartition
    at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at org.apache.spark.serializer.JavaDeserializationStream$$anon$1.resolveClass(JavaSerializer.scala:67)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1868)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1751)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2042)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
    at java.io.ObjectInputStream.defaultReadFields(ObjectInputStream.java:2287)
    at java.io.ObjectInputStream.readSerialData(ObjectInputStream.java:2211)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:2069)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1573)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:431)
    at org.apache.spark.serializer.JavaDeserializationStream.readObject(JavaSerializer.scala:75)
    at org.apache.spark.serializer.JavaSerializerInstance.deserialize(JavaSerializer.scala:114)
    at org.apache.spark.executor.Executor$TaskRunner.run(Executor.scala:313)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    ... 1 more

Comment: @Paul it is working when i specify the Artifact URL, not with file path.
Comment: can you pass it via  the --jars parameter?
Comment: @Paul i tried `--jars` , extraclasspath, `packages`, but nothing seems to be working..  is it problem with Spark Standalone cluster?
Answer: I am posting on  behalf of a colleague that had some insights on this:
When you run spark-submit from your laptop to run a workload on Kubernetes (managed or otherwise) it requires you to provide the k8s master URL and not the spark master URL.  Whatever this URL is pointing to "spark://spark-master.cluster.local:7077" does not have a line of sight from your machine, it may be that it does not even exist in your original issue. When using spark submit it creates the executor and driver nodes inside k8s and at that time a spark master URL will be available but even then the spark master URL is available only from inside k8s unless the line of sight is made available
Per your Update section: For passing packages, packages search for packages in the local maven repo or a remote repo if the path is provided to the remote repo, you can use the --jars options. Wherein you can bake the jars inside the container that would run the spark job and then provide the local path in the --jars variable
Does any of this resonate with the updates and conclusions you reached in your updated question?


Porque os eventos jquery nao funcionam quando crio um objeto via innerHTML do Javascript?

Question: Estou fazendo o seguinte código:
var botoesTela = "<button id='okcad' class='botao_padrao botao_ok' value='OK' onclick=''>  OK </button>";
divBotoes.innerHTML = divBotoes.innerHTML + botoesTela;

mas quando eu tento pegar o click no botão na pagina HTML
$("#okcad").click(function()

ele não faz nada...alguém sabe porquê?
Comment: Pode ser a ordem em que as coisas são feitas. Nesse caso você precisaria [delegar o evento](http://pt.stackoverflow.com/questions/5196/qual-a-diferen%C3%A7a-entre-o-onclick-function-e-o-clickfunction/5199#5199).
Comment: Há algum erro no console? Quando o bind da função de click é realizado? Antes ou depois da inserção do botão no document?
Answer: Duas razões (erros no código) que podem levar a esse problema:
#1
Problema: O elemento é criado depois de esse jQuery ser lido.
Solução: Precisa delegar o evento.
Novo código: $(document).on('click', "#okcad", function(){
#2
Problema: IDs duplicadas se eventualmente estiver a adicionar botões como esse várias vezes.
Solução: Use classes em vez de IDs ou gere IDs dinamicamente para serem unicas.
Novo código: $(".botao_padrao.botao_ok").click(function(){

Pode combinar as duas ideias e usar:  $(document).on('click', '.botao_ok', function(){


How to convert UTC value to NYC/eastern?

Question: I have epochs in a pandas series:
0       1654769460000
1       1654772040000
2       1654774680000
3       1654776000000
4       1654776420000
            ...
2050    1655423700000
2051    1655423760000
2052    1655423820000
2053    1655423880000
2054    1655423940000
Name: t, Length: 2055, dtype: int64

I then convert them to pandas datetimes:
time_stamp = pd.to_datetime(final_df['t'], unit='ms')

My timezone is UTC - 4 so it's the wrong time. I need the time in NYC.
I try to print the following:
print(time_stamp.tz_localize('UTC').tz_convert('America/New_York'))

But it returns nothing - not even an error. What am I doing wrong?
Answer: Use .dt.tz_convert
df['tEST'] = pd.to_datetime(df['t'], utc=True, unit='ms').dt.tz_convert('America/New_York')


Count number of $m$ elements set from $\{1,2,\dots,n\}$ whose sum is multiple of $m$

Question: I am trying to count number of $m$ elements set from $\{1,2,\dots,n\}$ whose sum is multiple of $m$.
That's number of set $\{x_1, x_2,\cdots,x_m\}$ with $x_1+x_2+\dots+x_m \equiv 0 \pmod m$.
By using a computer, I found that it seems the result is
$$\frac1m\sum_{d|m} (-1)^{m-d} \varphi(\frac md){\lfloor\frac{dn}m\rfloor\choose d }$$
but I could not prove it. Could anyone help to prove it or provide a counterexample?
Comment: I did not check your result but you can write the $q-$binomial as $q^{\binom{m}{2}}{n\brack m}_q=\sum _{|X|=m}q^{\sigma (X)}$ where $\sigma (X)$ is the sum of the elements of $X$ and you want exactly the ones that are divisible by $m$. I would try to evaluate the $q-$binomial on a primitive $m-$root of unity to see what happens. Perhaps the generating function of $\varphi$ appears somehow.
Comment: Continue to look up the count of equation $x_1+x_2+...+x_m \equiv h (mod m)$, it seems the result is $\frac1m \sum_{d|m} (-1)^{m-d} \varphi(\frac md)g(\frac m{dh}) {\lfloor\frac{dn}m\rfloor \choose d}$ where $g(p^a)=\begin{cases}0&a\ge 2\\\frac1{1-p}&a=1\\1&a\le 0\end{cases}$. And  $g(p_1^{a_1}\cdots p_t^{a_t})=g(p_1^{a_1})\cdots g(p_t^{a_t})$
Answer: Phicar's suggestion in the comments is a good one. It follows from the q-binomial theorem that
$$q^\binom{m}{2} \binom{n}{m}_q = \sum_{X \subset [n] : |X| = m} q^{\sigma(X)}, \qquad (*)$$
where $\sigma(X)$ is the sum of the elements of a subset $X \subset \{1, \dots, n\}$. We are going to evaluate this expression on all complex $m$th roots of unity and sum. On the right-hand side, the only terms which survive are those with $\sigma(X) \equiv 0 \pmod m$, so we get precisely $m$ times what we want. What do we get on the left-hand side?
Say $q = e^{i2\pi k / m}$. First, $q^\binom{m}{2} = e^{i2\pi k (m-1)/2} = (-1)^{k(m-1)}$. Second, by definition
$$ \binom{n}{m}_q = \frac{(q^n - 1)(q^{n-1} - 1) \cdots (q^{n-m+1} - 1)}{(q^m-1) (q^{m-1} - 1) \cdots (q - 1)}.$$
The apparent singularities near roots of unity are all removable (this follows from (*) for example). We can evaluate $\binom{n}{m}_q$ when $q$ is a primitive $d$th root of unity, where $d \mid m$, by applying l'Hospital's rule $m/d$ times. Let $n'$ be the largest multiple of $d$ less than $n$. Then we get
$$ \frac{n'(n'-d) \dots (n'-m+d)}{m(m-d) \dots d} = \binom{n'/d}{m/d}.$$
Since there are $\varphi(d)$ primitive $d$th roots of unity, all together we get
$$\sum_{d \mid m} (-1)^{m(m-1)/d} \varphi(d) \binom{n'/d}{m/d}.$$
This is equivalent to your expression. (Regarding the sign factor, if $m$ is even then the sign factor is $(-1)^{m/d}$, so we agree in this case, while if $m$ is odd then the sign factor is always 1 and so is yours, so we agree in that case too.)
Comment: BTW, how did you find this expression "using a computer"?
Comment: First define $C_m(u,n,h)$ as number of u elements set from [n] whose sum is h modular m.
Classify set above according to whether the set contains number n, we have
$C_m(u,n,h)=C_m(u,n-1,h)+C_m(u-1,n-1,h-n)$
Classify set above according to whether the set contains number 1 and subtract all elements by 1, we have
$C_m(u,n,h)=C_m(u,n-1,h-u)+C_m(u-1,n-1,h-u)$
Comment: After that we could compute $C_m(m,n,0)$ via pari/gp code:

getC(N,m)={
   local(C,D,v,R);
   C=matrix(N,m);
   D=matrix(N,m);
   R=vector(N);
   for(h=1,m,
     for(n=1,N,
       C[n,h]=floor(n/m);
       if(h<=n%m, C[n,h]=C[n,h]+1)
     )
   );
   for(u=2, m,
      for(n=1, u-1,
         for(h=1,m,D[n,h]=0)
      );
      for(n=u,N,
         for(h=1,m,
             v=h-u;if(v<=0,v+=m);
             D[n,h]=D[n-1,v]+C[n-1,v]
         )
      );
      C=D
   );
   for(n=1,N,
      R[n]=C[n, m]
   );
   R
}
Comment: Next we could focus on n=km+r and it is easy to determine that $C_m(m,km+r,u)$ are order-m polynomial of k and we could find the polynomial:
getPolys(m)={
   local(C, P, H, R, r);
   C=getC(m*(m+1),m);
   H=matrix(m+1,m+1);
   for(u=1,m+1,
      H[u,1]=1;
      for(v=1,m, H[u,v+1]=(u-1)^v)
   );
   R=matrix(m+1,m);
   for(u=1,m+1,
      for(v=1,m,
         R[u,v]=C[(u-1)*m+v]
      )
   );
   R=H^-1*R;
   P=vector(m);
   for(u=1,m,
      P[u]=R[m+1,u];
      for(v=1,m,
         if(u==m, P[u]*=k-1,P[u]*=k);
         P[u]+=R[m+1-v,u]
      )
   );
   P
}
Comment: Subtract polynomial above by $\frac{n\choose m}{m}$ and I found the order of polynomial left is largest factor of m and coefficient of it is $\frac{u^{u-1}}{u!}\frac{d-1}d$ where m=ud.
Comment: In the other hand, since $C_m(m,n,h)=C_m(m,n-1,h)+C_m(m-1,n-1,h-n)$ and $C_m(m,n,h)=C_m(m,n-1,h)+C_m(m-1,n-1,h)$, we have $C_m(m-1,n-1,h)=C_m(m-1,n-1,h-n)$, which means $C_m(m-1,n-1,h) = C_m(m-1,n-1,h-\lambda gcd(m,n))$
esp. $C_m(m,n,h)=c_m(m,n-1,h)+\frac{n-1\choose m-1}{m}$ if $n\neq 0(\mod m)$
which hints that the result is related to factor of m and finally I found the formula.
Comment: formula should be $C_m(u,n,h)=C_m(u-1,n−1,h)+C_m(u−1,n−1,h−n)$ and $C_m(u,n,h)=C_m(u-1,n−1,h−u)+C_m(u−1,n−1,h−u) $
Comment: Interesting, thanks.
Comment: I could get your idea now.
For ${n \choose m}_q$ where q is primitive d-th root of unity, we could find the result is $\lim_{q\to\omega_d}\frac{(q^{n'd}-1)(q^{(n'-1)d}-1)\cdots (q^{(n'-r+1)d)}-1)}{(q^d-1)(q^{2d}-1)\cdots (q^{r d}-1)}$  since all non-zero factors could be eliminated, where rd=m and $\omega_d$ is primitive d-th root of unity.
For $\lim_{q\to\omega_d} \frac{q^{(n'-h+1)d}-1}{q^{hd}-1}$, L'Hospital's rule could be applied to result in $\frac{n'-h+1}h$
Comment: Nice, +1, the L'hopital can be avoided using $q-$Lucas.


How to select columns with an even ID number?

Question: I'm trying to solve the Hackerrank problem Weather Observation Station 3 which is stated below:

I came up with the following solution:
SELECT CITY
FROM STATION
WHERE MOD(ID, 2) = 0

but when I try to run it I get the compiler message "Wrong answer". I don't see what's wrong with this query?
Comment: The question still have 1 part: *exclude duplicates from your answer*
Comment: "Must exclude duplicates". Try it with a "Distinct"
Comment: The answer is right there: https://www.hackerrank.com/challenges/weather-observation-station-3/forum
Answer: SELECT DISTINCT CITY
FROM STATION
WHERE MOD(ID, 2) = 0

Answer: You can try this query:
SELECT DISTINCT CITY FROM STATION WHERE (ID % 2) = 0

Comment: Will this work in Oracle? The question was tagged with [tag:Oracle]. Don't you need to use the `MOD()` function instead, as suggested in [the accepted answer](https://stackoverflow.com/a/39446420/3025856)?
Answer: For DB2:
SELECT DISTINCT CITY
FROM STATION
WHERE MOD(ID, 2) = 0;

For Oracle:
SELECT DISTINCT CITY
FROM STATION
WHERE MOD(ID, 2) = 0;

For MySQL:
SELECT DISTINCT CITY
FROM STATION
WHERE MOD(ID, 2) = 0;

-- Or --
SELECT DISTINCT CITY
FROM STATION
WHERE ID%2=0;

For MSSQL:
SELECT DISTINCT CITY
FROM STATION
WHERE ID%2=0;

Answer: SELECT DISTINCT CITY FROM STATION WHERE (ID % 2) = 0;

DISTINCT for not allowing duplicates,
(Id % 2) tells SQL to divide the Id by 2 and return the remainder.
Since we're looking for only even values, we set this to = 0, as
2%2=0, 4%2=0, etc.
If we were looking for odd-numbered Ids, we'd use
= 1 instead, since there's always a remainder of 1 when dividing odd numbers by 2.
Comment: This is a good explanation. But will this work in Oracle? The question was tagged with [tag:Oracle], not [tag:mysql] or [tag:mssql]. Wouldn't  you need to use the `MOD()` function instead, as suggested in [the accepted answer](https://stackoverflow.com/a/39446420/3025856)?
Answer: MYSQL:
SELECT DISTINCT CITY FROM STATION WHERE (ID % 2)=0;

ORACLE:
SELECT DISTINCT CITY FROM STATION WHERE MOD(ID, 2)=0;

Answer: If the question would like "Query a list of CITY names from STATION with even ID numbers only" then the answer would be
select CITY from station where ID % 2 = 0;

But due the further criteria like "But must exclude duplicates from your answer." your answer should be
select DISTINCT CITY from station where ID % 2 = 0;

Comment: Will this work in Oracle? The question was tagged with [tag:Oracle], not [tag:mysql] or [tag:mssql]. Wouldn't  you need to use the `MOD()` function instead, as suggested in [the accepted answer](https://stackoverflow.com/a/39446420/3025856)?
Answer: I suggest another solution:
    SELECT DISTINCT CITY
    FROM STATION
    WHERE ID LIKE '%0' OR ID LIKE '%2' OR ID LIKE '%4' OR ID LIKE '%6' OR ID LIKE '%8';

Comment: Can you give some more explanation with your answer to help us understand better what the problem is you solved, and how you solved it?
Comment: This seems like it would be more expensive than the other suggested answers, and it's a lot less readable than using a simple modulus function or operator.
Answer: In MSSQL:
SELECT CITY
FROM STATION
WHERE (ID % 2) = 0
GROUP BY CITY

Comment: The question was tagged with [tag:Oracle], not [tag:mssql].
Answer: SQL Server using sub query with case-when statement:-
SELECT DISTINCT CITY FROM STATION WHERE ID IN (SELECT
                                               CASE
                                                   WHEN ABS(ID%2) = 0 THEN ID
                                               END
                                               FROM STATION);

Comment: Why should we use a subquery instead of directly checking the ID? And isn't ABS superfluous, since you only want zero as a result? I'm curious about your reasoning.
Comment: Nothing wrong to use ABS in it. It is standard practice to use ABS when performing any types of arithmetic operation. Which converts negative to positive. And about sub query i tried different way to solve it. Which is successful. If any one try to find different approach they can try.


Drupal timezone and database

Question: I have a content type with datetime field. When I save node, in database I have 2014-04-28 11:00:00 for instance. But when I edit the node i have 2014-04-28 13:00:00. I guess that it has something to do with timezones.
Now the problem is that i have lot of nodes and i have to get the time from database. I don't want to node_load or anything like that.
The question is - is it possible to extract 2014-04-28 13:00:00 datetime from database with MySQL query? Or any work around where I don't have to use node_load?
Any input will be appreciated :)
Answer: What version of Drupal is this?
It's against best practices to go directly to the database but if you really need to I don't see why you can't query the field's table. What problems are you having?
When entering data for a field, the data entered is assumed to be in the site's time zone. When the data is saved to the database, it is converted to UTC. When retrieved from the database, the data is converted to the Site's time zone for anonymous users or the User's time zone for logged in users when User-configurable time zones is enabled.
You may wanted to use format_date to convert your time.
See: https://api.drupal.org/api/drupal/includes!common.inc/function/format_date/7
UPDATE:
I don't know what source you time is in, either a timestamp or formatted date/time. In your example you're using  2014-04-28 11:00:00 so lets convert that to a unix timestamp:
  $newdate = new DateTime('2014-04-28 11:00:00 UTC', new DateTimeZone(date_default_timezone_get()));
  $unixts = $newdate->getTimestamp();
  $siteDate = format_date($unixts, 'small', '', date_default_timezone_get());

Comment: Make sure your date/time has UTC appended to the end of it. See my update for another attempt
Comment: It is Drupal 7. I'm using db_select interface in a custom module. But it returns 13:00:00, i need to have it in site's time zone which will return 15:00:00, just like in form where i can edit it.

When You wrote about converting. How can i do that?
Comment: Is there a specific reason you don't want to use node_load? These things are handled for you at that point. See my updated answer for using format_date
Comment: I need to preprocess 10k nodes every 5 minutes, i think that node_load will not be such good option:)
Comment: @Astaz3l ha! I agree then, better keep it simple and go directly to the field value.
Comment: sure, i wan't to avoid node_load. I can extract the datetime from database, that's not the issue. But i can't convert it so i can get 15:00:00 instead of 13:00:00 from database. Here is the code i'm using:
`$siteDate = \format_date($unixTimeStamp, 'small', '', date_default_timezone_get());` but still i get 13:00:00
Comment: 10k node_load() calls over 5 minutes is only ~33 nodes per second.  With decent hardware, you should be able to process well over 10k nodes with the Views module in the allotted time.
Comment: Just keep in mind a kitten dies every time you go rogue and circumvent the fantastic data abstraction layer in Drupal.
Answer: Gergely Lekli did a fantastic write-up on using views to avoid node_load() in Drupal 7.
By his calculations, using views was 6 fold faster.
With views I believe you will find it easier to output with the appropriate timezone as well.

Drupal timezone and database


Is there an infinite number of number sets? (natural, integers, real, complex...)

Question: I've heard of a number set on that's the smallest set after complex numbers, according to http://www.askamathematician.com/2012/09/q-is-there-a-number-set-that-is-above-complex-numbers/ (The Physicist) called quaternions.
A comment on that article says that there is another set called dual numbers, that's used to rendering fractals in graphics and even have equivalent quaternions, as stated by blackhole0173.
I wonder if there are more number sets to discover!
Comment: For each prime $p$, I would count the $p$-adic numbers $\mathbb{Z}_p$, or $\mathbb{Q}_p$, as a "number set" which makes infinitely many.  Also, any number field such as $\mathbb{Q}(\sqrt{n})$ for $n \ne 1$ square-free, or its ring of integers, would count as a "number set" in my book.
Comment: you might be interested to read about the [Cayley-Dickson construction](https://en.wikipedia.org/wiki/Cayley%E2%80%93Dickson_construction).
Answer: The problem with your question is that nobody knows what a "number set" is.  The way I interpret it, each positive integer $n$ creates a "number set" of modular arithmetic mod $n$, and there are infinitely many, so yes.
If you were just thinking of fields/division rings, then there's always infinite towers of fields, e.g. infinitely many subfields of the algebraic closure of the field of two elements.
I would encourage you to do a little bit of reading here about what concepts are used in mathematics that are colloquially referred to as "numbers", so that you become more familiar with the issue.


How to determine the volume of a polyhedron with square parallel bases, each one having sides parallel to the diagonal of the other

Question: This question appeared in a 1962 admissions test for an engineering school in Brazil:
Two equal squares with sides of length "m" are placed on parallel planes separated by a distance "h", such that

their centers belong to the same perpendicular line to both planes;
each side of one square is parallel to one diagonal of the other square.

Now consider the polyhedron whose edges are the sides of these two squares and the line segments that join each vertex of one square to the two vertices closest to it, belonging to the other square. The problem is to express its volume in terms of "m" and "h".
I have tried to start with the squares sides parallel to one another, and after joining the vertices as specified, give a "twist" of 45 degrees to one of them with respect to the other; but to no avail. Or maybe we could embed this polyhedron in a larger solid and then "slice out" some parts, in order to obtain its volume by difference.
Can someone give me any clues?
Comment: I like your second idea. Try starting with an octagon for the top and bottom faces.
Answer: Your polyhedron can be divided into a central prism with octagonal base, plus eight pyramids having as base each a lateral face of the prism (green in the diagram below), plus eight smaller pyramids with triangular base (orange in the diagram).

Every side of the regular octagons has length $(\sqrt2-1)m$, and the volume of the octagonal prism turns out to be
$$
V_{prism}=2(\sqrt2-1)m^2h.
$$
Each rectangular base pyramid has base area $(\sqrt2-1)mh$ and height $(\sqrt2-1)m/2$, so its volume is
$$
V_{repyr}={3-2\sqrt2\over6}m^2h.
$$
Each triangular base pyramid has base area $(2-\sqrt2)mh/4$ and height $(\sqrt2-1)m/2$, so its volume is
$$
V_{trpyr}={3\sqrt2-4\over24}m^2h.
$$
The volume of the polyhedron is then:
$$
V=V_{prism}+8V_{repyr}+8V_{trpyr}={2+\sqrt2\over3}m^2h.
$$
Comment: I think you have done it. Great spatial visualization!


Relationship between orbits of a graph implied by different automorphisms

Question: Let $\Phi = \{\phi, \phi'\}$ be automorphisms of a finite Graph $G$.
Suppose that $G$ has a further automorphism $\psi$.
$\Phi.v$ is the orbit of a Node $v$ according to $\Phi$.
Under which circumstances (conditions on $\Phi$ and $\psi$) does the following hold for all nodes $v$ in the graph?
$$
\psi(\Phi.v) = \Phi.(\psi(v))
$$
If I replaced '$=$' with '$\subseteq$' or '$\supseteq$', would things change?
Comment: It would help to make your quantifiers explicit. Is this supposed to hold for all $v$ or should the circumstances depend on $v$? For all $\psi$, or should the circumstances depend on $\psi$?
Comment: Thank you for your question. Indeed, it should hold for all $v$, and the circumstances should depend on $\psi$. Sorry. (My first question...)
Comment: That's all right, thanks for clarifying! I updated your post. Now, $\Phi$ is just a set of two given automorphisms, is that correct?
Comment: Yes. Thank you!
Answer: Let $\operatorname{Aut}(G)$ be group  of all automorphisms of the graph $G$, $\overline{\Phi}\le \operatorname{Aut}(G)$ be its semigroup  generated by $\Phi$. Since the graph $G$ is finite, $\overline{\Phi}$ is a finite group. Then
$L=\psi(\Phi.v) =\psi.\overline{\Phi}(v)$ and $R=\Phi.(\psi(v))=\overline{\Phi}.\psi(v)$.
Thus the comparison of the sets $L$ and $R$ is equivalent to the compation of the sets $\psi^{-1}(L)=\overline{\Phi}(v)$ and $\psi^{-1}(R)=\psi^{-1}\overline{\Phi}\psi(v)$ that is of the orbits of the node $v$ by the group $\overline{\Phi}$ and its conjugated group $\psi^{-1}\overline{\Phi}\psi$.
In particular, these orbits are equal if $\psi^{-1}\overline{\Phi}\psi=\overline{\Phi}$. The last happens exactly when both elements $\psi^{-1}\phi\psi$ and $\psi^{-1}\phi'\psi$ belong to the group $\overline{\Phi}$, in particular when $\psi$ commutes with both its generators $\phi$ and $\phi'$.
Now consider the general case. Let $S_v$ be the stablizer of the vertex $v$ that is the group of all automorphisms $\chi$ of the graph $G$ such that $\chi(v)=v$. Let $M$ be any subset of the group $\operatorname{Aut}(G)$. Then $M(v)=MS_v(v)$ and if $\xi(v)\in M(v)$ then $\xi(v)=\zeta(v)$ for some element $\zeta\in M$, so $\zeta^{-1}\xi \in S_v$ and $\xi\in MS_v$. Thus
$$MS_v=\{\xi\in \operatorname{Aut}(G):\xi(v)\in M\}.$$
Hence $\overline{\Phi}(v)$ $=$ (resp., $\subseteq$, $\supseteq$) $\psi^{-1}\overline{\Phi}\psi(v)$ iff
$\overline{\Phi}S_v$ $=$ (resp., $\subseteq$, $\supseteq$) $\psi^{-1}\overline{\Phi}\psi S_v$.
Comment: +1, but the way I originally interpreted the question was that the "orbit" $\Phi . v$ means the set $\{\phi(v), \phi'(v)\}$, not $\overline{\Phi}(v)$.


Batch file Nesting findstr inside a loop

Question: I'm trying to run the prntmngr.vbs script. I'm trying to find strings like Printer name, server name, etc. There are about 80-200 printers on each server
I want it to pipe the information in a csv format.
I'm having trouble nesting the findstr's and loops to get the information. I've pieced together some things.
running the vbs gives me every printer and its information.
The VBS outputs every printer in a block of information as follows. Theres about 80 printers on this one server. I'll worry about scoping out to other servers, as long as I can get it to output the information.

Server name lak-print01
Printer name 1015_Q1
Share name 1015_Q1
Driver name HP LaserJet 4350 PCL 5e
Port name IP_192.168.15.249
Comment Trust & Savings
Location 43rd & Meridian
Print processor HPCPP5r1
Data type RAW
Parameters
Attributes 8776
Priority 1
Default priority 0
Average pages per minute 0
Printer status Other
Extended printer status Offline
Detected error state Offline
Extended detected error state Other

Server name lak-print01
Printer name 1014_Q1
Share name 1014_Q1
Driver name Canon iR3225 PCL5e
Port name IP_192.168.14.245
Comment CSR and Teller Printer
Location Summit
Print processor WinPrint
Data type RAW
Parameters
Attributes 10824
Priority 1
Default priority 0
Average pages per minute 0
Printer status Idle
Extended printer status Unknown
Detected error state Unknown
Extended detected error state Unknown

Server name lak-print01
Printer name 1011_Q3
Share name 1011_Q3
Driver name HP LaserJet 4200 PCL 6
Port name IP_192.168.11.247
Comment HP LaserJet 4200 not being used can delete
Location Spanaway
Print processor HPZPP3xy
Data type RAW
Parameters
Attributes 8778
Priority 1
Default priority 0
Average pages per minute 0
Printer status Idle
Extended printer status Unknown
Detected error state Unknown
Extended detected error state Unknown

for instance I'd love the output to be a csv that outputs  the example vbs to
lak-print01,1015_Q1,HP LaserJet 4350 PCL 5e,IP_192.168.15.249,Trust & Savings,43rd & Meridian,Other
lak-print01,1014_Q1,Canon iR3225 PCL5e,IP_192.168.14.245,CSR and Teller Printer,Summit,Idle

pulling find strings for printer server, printer name, printer driver, port name, comment, location, status
Ive gotten a working script
@echo off

SetLocal enabledelayedexpansion

cscript prnmngr.vbs -l -s lak-print01 >test.csv

for /f "tokens=3*" %%i in ('findstr /i /c:"Printer name" /i /c:"Server name" /i /c:"Printer status" /i /c:"Driver name" test.csv') do @echo %%i,
endlocal

That outputs
1005_Q2,
HP,
Other,
status,
lak-print01,
1004_Q2,
HP,
Idle,
status,
lak-print01,
1004_Q1,
HP,
Idle,
status,
lak-print01,
1003_Q2,
HP,
Idle,
status,
lak-print01,
1003_Q1,
HP,
Idle,
status,

Which is great, however its only pulling the first word of the driver name even with the wildcard in the tokens. Now I just have to figure out how to make it carriage return after a for loop is complete to start a new line with new set of data.
Comment: OMG - that prnmngr.vbs output is horrible. There is nothing to tell you where the attribute name ends and the value begins. Also, the number of attributes is not constant. Sometimes the Start Time and Until Time attributes are present. Parsing and transforming the output into CSV will be much harder than it ought to be.
Comment: Can you post script output example?
Comment: I've edited the post to show vbs output
Answer: @ECHO Off
SETLOCAL enabledelayedexpansion
:: remove variables starting $
FOR  /F "delims==" %%a In ('set $ 2^>Nul') DO SET "%%a="
(FOR /f "delims=" %%a IN (q25900051.txt) DO CALL :analyse "%%a")>printers.csv

GOTO :EOF

:analyse
SET "line=%~1"
SET /a fieldnum=0
FOR %%s IN ("Server name" "Printer name" "Driver name"
            "Port name" "Comment" "Location" "Printer status"
        "Extended detected error state") DO CALL :setfield %%~s
GOTO :eof

:setfield
SET /a fieldnum+=1
SET "linem=!line:*%* =!"
SET "linet=%* %linem%"
IF "%linet%" neq "%line%" GOTO :EOF
IF "%linem%"=="%line%" GOTO :EOF
SET "$%fieldnum%=%linem%"
IF NOT DEFINED $8 GOTO :EOF
SET "line="
FOR /l %%q IN (1,1,7) DO SET "line=!line!,!$%%q!"
ECHO !line:~1!
:: remove variables starting $
FOR  /F "delims==" %%a In ('set $ 2^>Nul') DO SET "%%a="
GOTO :eof

I used a file named q25900051.txt containing your data for my testing.
This could be automated a little further, but I don't have the time at present.
Essentially, it analyses each line and sets a field number 1..number-of-columns+1. When the number-of-columns+1'th column is filled, the output is accumulated and echoed and the $ variables reset.
The "Manual" part is entering the names of the fields to be selected, including the "end of block" field as the last entry; then the variable $8 and the top limit for %%q are set - 8 fields potentially being analysed, 7 being output.
The jiggery-pokery with line, linem (modified line - minus the field name) and linet (total line - reconstructed) is first to extract the required data by removing the string as far as the target. The line is then reconstructed as linet and compared to the original version in line. This allos us to distinguish between the line that starts Printer status and theline that starts Extended printer status - when the target is printer status, the first line will be reconstructed to match the original, but the second will lop off Extended printer status then re-add printer status, so the reconstructed line does not match the original...

Modified for new requirement - output to file.
It's in a rather odd place - parenthisise the for statement invoking thesubroutines - any output from echo statements within the subroutines will be redirected to the file nominated.

since you asked...
Comment: That is amazing, that echo's exactly what I'm looking for. You are a MASTER! I'm trying to add a >printers.csv but I'm having issues placing where to put it in the code.
Answer: I'm shocked by the output of the prnmngr.vbs listing.
There is nothing to delimit the end of an attribute name / the beginning of the value.
Also, the number of attributes can vary (Start Time and Until Time may or may not be present)
Given that the utility is VBS, it is relatively easy to modify the script and create our own version.
I've created my own version that has two major changes:
1) The -l option now delimits the end of an attribute with a :
2) I've added the -lc option to list printers using CSV format. The first line is a header line giving the name of each column. All column values are enclosed in quotes. The Start and Until times are always listed (often empty).
The following simple command will create a CSV directly:
cscript prnmngrMod.vbs -lc -s lak-print01 >test.csv

The code is too large to post in this answer, so I have made it available at http://pastebin.com/e7xwhmn3


I would like to create subdomains Dynamically under my domain using asp.net ,C#?

Question: I would like to create subdomains Dynamically under my domain using asp.net ,C#?
I can not find good solution for this.
What are the things i should do to complete this.
Scenario:
1.user register with site
2.domain name should be: http://username.domain.com
Thanks
Comment: Duplicate http://stackoverflow.com/questions/1943356/creating-subdomains-programmatically
Answer: Most DNS providers allow you to specify wildcard DNS. That means you have an entry something like "*.example.com" that maps to your IP address.
If you do this, then you do not have to modify DNS entries on the fly, you just need to add an internal mapping in your database (or whatever) saying that "user1.example.com maps to user1", etc.