text:
Q: class header.h not included in main So for some reason when i try to compile i get an error that in main.cpp: value and balance are not declared in scope.
i used #include "account.h" in main so why are they not defined?
also do you see any issues with my class, including the constructor and destructor.
account.cpp
using namespace std;

#include <iostream>
#include "account.h"

account::account(){

}

account::~account(){

}

int account::init(){
cout << "made it" << endl;
  balance = value;

}

int account::deposit(){
  balance = balance + value;
}

int account::withdraw(){
  balance = balance - value;
}

main.cpp
using namespace std;

#include <iostream>
#include "account.h"

//Function for handling I/O
int accounting(){

string command;

cout << "account> ";
cin >> command;
account* c = new account;

    //exits prompt
    if (command == "quit"){
        return 0;
        }

    //prints balance
    else if (command == "init"){
        cin >> value;
        c->init();
        cout << value << endl;
        accounting();
        }

    //prints balance
    else if (command == "balance"){
        account* c = new account;
        cout << " " << balance << endl;
        accounting();
        }

    //deposits value
    else if (command == "deposit"){
        cin >> value;
        c->deposit();
        accounting();
        }

    //withdraws value
    else if (command == "withdraw"){
        cin >> value;
        cout << "withdrawing " << value << endl;
        accounting();
        }

    //error handling
    else{
        cout << "Error! Command not supported" << endl;
        accounting();
        }
}

 int main() {

     accounting();

return 0;
}

account.h
class account{

private:

int balance;

public:

    account();  // destructor
    ~account(); // destructor
    int value;
    int deposit();
    int withdraw();
    int init();

};

sorry if the code has bad style, i had a hard time with the stack overflow editor.

A: you are referring to value and balance as if they are normal variables, but they are not - they are instance-variables. you should have an object in which to refer to them:
account c;
cout << "withdrawing " << c.value << endl;

if you are accessing them from inside a method - say, from account::deposit - then value is a syntactic sugar for this->value, so you can use it this way; the object is effectively *this. these statements are equivalent:
balance += value;
balance += this->value;
balance += (*this).value;

A: value and balance are members of class account and they are suppose to be accessed as c->value and c->balance. But balance is a private member, you can't use it in main(). You need to write some accessor function like:
int account::GetBalance() const
{
    return balance;
}

and then call it as
cout << " " << c->GetBalance() << endl;

Also, you should free the allocated memory for c by calling .
delete c;


text:
Q: Conditionally position and display sprite given iphone different sizes in cocos2d 2 I created an app that is compatible for iOS 5 and pre iPhone 5. Meaning, its background and sprites positioning are the way they are supposed to for the iPhone 3.5 Retina. When I tried running my app on the iPhone 4" Retina, I see black padding on the top and bottom of my app. I was trying to find a smart way to conditionally display different background and sprite positioning given the size of the screen. I tried these two ways and they are not returning the value that I expect....
NSLog(@"Win Height: %f", winSize.height);
NSLog(@"Win Width: %f", winSize.width);
NSLog(@"Main Screen Height: %f", [UIScreen mainScreen].bounds.size.height);
NSLog(@"Main Screen Width: %f", [UIScreen mainScreen].bounds.size.width);

2012-10-02 21:36:47.317 Win Height: 480.000000
2012-10-02 21:36:47.318 Win Width: 320.000000
2012-10-02 21:36:47.319 Main Screen Height: 480.000000
2012-10-02 21:36:47.319 Main Screen Width: 320.000000

Does anyone know a way to conditionally position sprite given the size of the device?

A: Have you included the Default-568h@2x.png splash image to disable letterboxing?
Once that is done you could do something like this,
#define DEVICE_IS_IPHONE5 ([[UIScreen mainScreen] bounds].size.height == 568)

if(DEVICE_IS_IPHONE5)
{
     //Do something different
}
else
{
}

Edit: Forgot the @2x

redpajama_set_name: RedPajamaStackExchange


text:
Q: Extending lines to reach to x-axis I use the following code to draw 2 related lines from a defined node.
Is it possible to modify this code to extend the lines, so that L and S points reach x-axis, without defining their lengths.
\documentclass{beamer}
\beamertemplatenavigationsymbolsempty
\usepackage{tikz}
\begin{document}
\begin{frame}[t]
\frametitle{Line to x axis}
\begin{tikzpicture}[scale=.9, transform shape]
\draw [thick](0,0) -- (11,0) node [black, xshift=.2cm, yshift=-.2cm] {Y};
\draw [thick](0,0) -- (0,8) node [black, xshift=-.2cm, yshift=0cm] {r};
\draw [very thick, blue] (5.5,4) node (er1){} +(-40:5cm) node [blue, xshift=.2cm, yshift=-.2cm] {S} -- +(140:5cm)  +(40:5.5cm) node [blue, xshift=.2cm, yshift=.2cm] {M} -- +(-140:4cm) node [blue, xshift=-.2cm, yshift=.2cm] {L};
\end{tikzpicture}
\end{frame}
\end{document}

A: You can find these intersection points with the syntax:
(intersection of A--B and C--D) % for example

A complete example could be the following. Suppose that we know the points A, B and M (the late is where the two lines meet).
\documentclass[border=2mm]{standalone}
\usepackage{tikz}

\begin{document}
\begin{tikzpicture}
\coordinate (O) at (0,0);
\coordinate (X) at (5,0);
\coordinate (Y) at (0,5);
\coordinate (A) at (1,4);
\coordinate (B) at (4,5);
\coordinate (M) at (2,2);
\coordinate (C) at (intersection of A--M and O--X); % <-- We find here an intersection point...
\coordinate (D) at (intersection of B--M and O--X); %     and here the other one
\draw[latex-latex] (Y) node [above] {$y$} |- (X) node [right] {$x$};
\draw (A) node [above] {$A$} -- (C) node [below] {$C$};
\draw (B) node [above] {$B$} -- (D) node [below] {$D$};
\fill (M) circle (1pt) node [right] {$M$};
\end{tikzpicture}
\end{document}

Edit: Applying the above example at the OP figure, we have:
\documentclass{beamer}
\beamertemplatenavigationsymbolsempty
\usepackage{tikz}
\begin{document}
\begin{frame}[t]
\frametitle{Line to x axis}
\begin{tikzpicture}[scale=.9, transform shape]
\draw [thick](0,0) coordinate (O) -- (11,0) coordinate (Y) node
      [xshift=.2cm, yshift=-.2cm] {Y}; % added coordinates (O), (Y), removed 'black' (not necessary)
\draw [thick](0,0) -- (0,8) node [xshift=-.2cm] {r}; % removed 'black' and 'yshift' (not necessary)
\path (5.5,4) node (er1){} +(-40:5cm) node [blue, xshift=.2cm, yshift=-.2cm] {} --
  +(140:5cm) coordinate (N) +(40:5.5cm) coordinate (M) node [blue, xshift=.2cm, yshift=.2cm] {M} --
  +(-140:4cm) node [blue, xshift=-.2cm, yshift=.2cm] {}; % added coordinates (M), (N), changed \draw for \path, removed labels L and S
% new code
\coordinate (L) at (intersection of O--Y and M--er1);
\coordinate (S) at (intersection of O--Y and N--er1);
\draw [very thick, blue] (M) -- (L) node [below] {L};
\draw [very thick, blue] (N) -- (S) node [below] {S};
\end{tikzpicture}
\end{frame}
\end{document}


text:
Q: how can I force href direction to external host page? I have this html:
live map

I open it in my browser, as follows:
http://localhost:63342/RoutingRegression/html_pages/delta_to_baseline_table/delta_to_baseline_samples_agg_fresh.html#astar_improve
and when I press the link I'm direct to:
http://localhost:63342/myhost.com/tiles/internal?lineGeom=(-71.1208,42.3317,-71.1052,42.3261,-71.0872,42.3354,-71.0570,42.3295,-71.0376,42.3394),(-71.1208,42.3317,-71.0754,42.3311,-71.0617,42.3428,-71.0376,42.3394),(-71.1208,42.3317,-71.0675,42.3525,-71.0376,42.3395)

how can i change it to be directed to: (new http page):
"http:/myhost.com/tiles/internal?lineGeom=(-71.1208,42.3317,-71.1052,42.3261,-71.0872,42.3354,-71.0570,42.3295,-71.0376,42.3394),(-71.1208,42.3317,-71.0754,42.3311,-71.0617,42.3428,-71.0376,42.3394),(-71.1208,42.3317,-71.0675,42.3525,-71.0376,42.3395)"

Update
how can it be that it's generated "http:/" instead of "http://" ?
this is my url builder:
    UriBuilder builder = UriBuilder
            .fromPath(Constants.LIVEMAP_BASE_URL_US)
            .scheme("http");
    return builder.build().toString();

A: It seems your url is incorrect
change
http:/myhost.com

to be
http://myhost.com

A: You need to put double // in your url like this:
http://myhost.com/tiles/internal?lineGeom=(-71.1208,42.3317,-71.1052,42.3261,-71.0872,42.3354,-71.0570,42.3295,-71.0376,42.3394),(-71.1208,42.3317,-71.0754,42.3311,-71.0617,42.3428,-71.0376,42.3394),(-71.1208,42.3317,-71.0675,42.3525,-71.0376,42.3395)


text:
Q: Issue with definite integration by parts using IntegrateByParts I am trying to prove Cauchy's identity with Mathematica ResourceFunction["IntegrateByParts"]. It doesn't seem to work with definite integration. Cauchy's identity says:
$$
\int_{a}^{x}dz\int_{a}^{z}dy f(y)=\int_{a}^{x} (x-y)f(y)dy
$$
To prove Cauchy's identity I introduce a function F[z_] -> Inactive[Integrate][f[y], {y, a, z}]. Then, using IntegrateByParts on F[z], and applying the substitution rule F'[z] -> f[z] yields:
ResourceFunction["IntegrateByParts"][ F[z], {z, a, x}];
% /. {F[z_] -> Inactive[Integrate][f[y], {y, a, z}]};
% /. F'[z_] -> f[z] // Activate

This is not the expected result from Cauchy's identity. How can the IntegrationByParts be modified to work and verify Cauchy's identity?

A: I think it's a bug of ResourceFunction["IntegrateByParts"]. The output of
ResourceFunction["IntegrateByParts"][F[z], {z, a, x}]

is
-F[a] + F[x] - Inactive[Integrate][z Derivative[1][F][z], {z, a, x}]

but clearly the correct output should be
-a F[a] + x F[x] - Inactive[Integrate][z Derivative[1][F][z], {z, a, x}]

By checking the source code (it can be found by DirectoryName@FindFile@"ResourceFunctionHelpers`" <> "\\IntegrateByPart.wl" // SystemOpen, at least on Windows 10), there seems to be a mistake in the definition of makeResult. The
Subtract@@(f /. {{x -> hi}, {x -> lo}})

should be modified to
Subtract@@(u v /. {{x -> hi}, {x -> lo}})

With this correction, your code will give the desired result. BTW the code can be simplified to
ResourceFunction["IntegrateByParts"][F[z], {z, a, x}]
% /. F -> Function[z, Inactive[Integrate][f[y], {y, a, z}]]
% // Activate


text:
Q: ASP.NET - Add Event Handler to LinkButton inside of Repeater in a RenderContent call I've got a Sharepoint WebPart which loads a custom User Control. The user control contains a Repeater which in turn contains several LinkButtons.
In the RenderContent call in the Webpart I've got some code to add event handlers:
        ArrayList nextPages = new ArrayList();
        //populate nextPages ....
        AfterPageRepeater.DataSource = nextPages;
        AfterPageRepeater.DataBind();

        foreach (Control oRepeaterControl in AfterPageRepeater.Controls)
        {
            if (oRepeaterControl is RepeaterItem)
            {
                if (oRepeaterControl.HasControls())
                {
                    foreach (Control oControl in oRepeaterControl.Controls)
                    {
                        if (oControl is LinkButton)
                        {
                            ((LinkButton)oControl).Click += new EventHandler(PageNavigateButton_Click);
                        }
                    }
                }
            }
        }

The function PageNavigateButton_Click is never called however. I can see it being added as an event handler in the debugger however.
Any ideas? I'm stumped how to do this.

A: By the time RenderContent() is called, all the registered event handlers have been called by the framework. You need to add the event handlers in an earlier method, like OnLoad():
protected override void OnLoad(EventArge e)
 { base.OnLoad(e);
   EnsureChildControls();

   var linkButtons = from c in AfterPageRepeater.Controls
                                                .OfType<RepeaterItem>()
                     where c.HasControls()
                     select c into ris
                        from lb in ris.OfType<LinkButton>()
                        select lb;

   foreach(var linkButton in linkButtons)
    { linkButton.Click += PageNavigateButton_Click
    }
 }

A: Have you tried assigning the CommandName and CommandArgument properties to each button as you iterate through? The Repeater control supports the ItemCommand event, which is an event that will be raised when a control with the CommandName property is hit.
From there it is easy enough to process because the CommandName and CommandArgument values are passed into the event and are readily accessible.

A: You need to make sure that the link button is re-added to the control tree and/or that the event is rewired up to the control before the event fires.
Article @ 4guysfromrolla

A: I've never done a SharePoint WebPart, so I don't know if this will apply. But if it were a plain-old apsx page, I'd say that by the time it's rendering, it's too late. Try adding the event handlers in the control's Init or PreInit events.

Edit: Wait, I think Dilli-O might be right. See the Adding Button Controls to a Repeater section at the end of http://www.ondotnet.com/pub/a/dotnet/2003/03/03/repeater.html. It's in VB.NET, but you can easily do the same thing in C#.

A: As others have pointed out, you're adding the event handler too late in the page life cycle. For SharePoint WebParts you'd typically want to override the class' OnInit/CreateChildControls methods to handle the activity.

A: YOu need your webpart to implement the INamingContainer marker interface, it is used by the framework to allow postbacks to return to the correct control...
Also the controls in your webpart all need to have an ID.


text:
Q: Constructing borders for rectangles in Game of life I just started my first programming course in Python and I'm having trouble understanding what's wrong with my code for Game of life. Our task is to create the grid that the game will play in but I can't understand what is wrong with my code (see below).
def paint(target_window, grid):

    height = len(grid)
    width = len(grid[0])

    target_window.setCoords(0,height,width,0)

    for row in range(height):
        for col in range(width):
            rect = Rectangle(Point(row,col),Point(row + 1, col + 1))
        rect.draw(target_window)
    target_window.update()

More specific the grid is supposed to be "infinite" so that the game isn't restricted. I think that my .setCoords may have something to do with what's wrong.

A: In case you are using this Graphics library, indeed your call of setCoords is wrong. Try to change it into this
target_window.setCoords(0,0,width,height)

The documentation says

setCoords(xll, yll, xur, yur) Sets the coordinate system of the window. The lower-
  left corner is (xll, yll) and the upper-right corner is (xur, yur). All subsequent drawing
  will be done with respect to the altered coordinate system (except forplotPixel).

... and there is also issue with the indentation of rect.draw(target_window), as mkrieger1 pointed out.


text:
Q: migrating erb to haml - strange behavior when using the build method with nested forms I have a simple view in Rails that I'm migrating from ERB to HAML. This view renders a nested form, but includes an empty child object it there aren't any existing child objects.
With ERB, I was accomplishing this by doing this:
<%= form_for @question do |f| %>
  <%= f.label :name %>
  <%= f.text_field :name %>

  <%= f.object.answers.build if f.object.answers.empty? %>

  <%= f.fields_for :answers do |builder| %>
    <%= render 'answer_fields', f: builder %>
  <% end %>

  <%= f.submit %>
<% end %>

It works!  But when I do the same thing using HAML, it also "works", but prints an annoying text between the forms, something that looks like this: #<Answer:0xb159004>.
This is what my HAML looks like:
= form_for @question do |f|
  = f.label :name
  = f.text_field :name

  = f.object.answers.build if f.object.answers.empty?

  = f.fields_for :answers do |builder|
    = render 'answer_fields', f: builder

  = f.submit

It is literally the same thing, but ERB works and HAML, although it works, it also prints #<Answer:0xb159004> near the forms, which I don't know how to get rid.
Am I doing something wrong or is this a HAML limitation/bug? Is there any workaround?

A: This doesn't directly resolve your question, but I always use http://html2haml.heroku.com/ for switching existing erb templates to HAML. Simply do a copy and paste of your existing erb code into the textfield and it'll output the corresponding HAML for you. It also accepts plain HTML. I've yet to see it spit out incorrect syntax so it's great for converting existing code without any divergency.

A: I had this problem for many days, but after posting this, I had an insight and I fixed my own problem.
Replacing the beginning of the line from "=" to "-" fixes this, as this makes HAML not to insert the output of the ruby code.
= form_for @question do |f|
  = f.label :name
  = f.text_field :name

  - f.object.answers.build if f.object.answers.empty?    <--- fix

  = f.fields_for :answers do |builder|
    = render 'answer_fields', f: builder

  = f.submit

Every example I found on the web about this used ERB code in <%= syntax, and I assumed translating them to HAML were always just to remove <%, but not in this specific case I guess.


text:
Q: Intentional RF emitter failing unintentional emission test? Suppose a commercial product uses a FCC pre-certified WiFi module. If the quality is not consistent throughout the batch, I'd guess some pre-certified modules may produce unacceptable emissions. In that case, could these emissions fail the unintentional emission test for the final product? Or is it that pre-certified modules are somehow isolated during the test such that the emissions produced by the pre-certified modules will not affect the unintentional emission test outcomes?

A: Well possible that an unit that has approved building blocks fails as one new system. The cumulated total emission can be too much due a simple summing or due increased individual emissions caused by new interactions. Do not rely only on "all my parts already have the certificate".
Do not believe? What interactions????
Think about a radio device and a too high voltage power supply for it. The higher voltage can easily raise the spurious outputs too high or the output at the legitimate frequency can have too high power.


text:
Q: Side-by-side Forest Plot in R So this is some generic data. I currently use the metafor package and par() function to make the plots side by side. However, I would like to ideally get rid of the study column in the second graph and the log RR estimates from both plots. I would like both forest plots to be moved closer together as well. Sorry for not providing data previously - I'm new at this.
library(metafor)
par(mfrow=c(1,2))

### load BCG vaccine data
data(dat.bcg)
### calculate log relative risks and corresponding sampling variances
dat <- escalc(measure="RR", ai=tpos, bi=tneg, ci=cpos, di=cneg, data=dat.bcg)
### default forest plot of the observed log relative risks
forest(dat$yi, dat$vi)
### default forest plot of the observed log relative risks for second plot
forest(dat$yi, dat$vi)

===============================
Does anyone know how to make a side-by-side forest plot in r?
I want to have the subgroup names on the left hand side, then two forest plots immediately to the right (beside each other)
Somewhat like this http://www.nature.com/ng/journal/v43/n8/images_article/ng.882-F1.jpg
but much simpler.
I have tried the par() function with metafor package but it does not work.

A: This gets you pretty close:
library(metafor)
data(dat.bcg)
dat <- escalc(measure="RR", ai=tpos, bi=tneg, ci=cpos, di=cneg, data=dat.bcg)

par(mfrow=c(1,2))
par(mar=c(5,4,1,1))
forest(dat$yi, dat$vi, annotate=FALSE, cex=.8, at=seq(-3,2,1), digits=1, xlim=c(-6,2))
text(0, 15, "Figure 1", cex=.8, font=2)
par(mar=c(5,3,1,2))
forest(dat$yi, dat$vi, annotate=FALSE, slab=rep("",length(dat$yi)), cex=.8, at=seq(-3,2,1), digits=1, xlim=c(-5,3))
text(0, 15, "Figure 2", cex=.8, font=2)


text:
Q: Birthday notification ruby ive set up a system where the user signs up and in the sign up they include their birthday. How can i make it so there is some sort of notification to show it's their birthday today when for example they are going to checkout and get a discount
def change
  create_table :useraccount do |t|

    t.string :user
    t.string :password
    t.date   :birthday

    t.timestamps null: false
  end
 end
end

A: You could define a method like this in your useraccount model (app/models/useraccount.rb):
 def birthday_today?
   birthday.month == Time.now.month &&
   birthday.day == Time.now.day
 end

Then you could use it like this in a controller:
 @show_birthday_notification = Useraccount.find( useraccount_id ).birthday_today?

And do something like this in your view:
 <% if @show_birthday_notification %>
   It's your birthday!
 <% end %>

A: You can check like:
if current_user.birthday.strftime('%d-%m') == Date.today.strftime('%d-%m')
   # your stuff
end

Or you can create separate method as well like Eric Terry suggested.


text:
Q: What does the gnuwin32 program: [.exe do? Looking in the gnuwin32/bin directory, there is an odd-looking program file named [.exe
I couldn't find it in the documentation, gnuwin32.sourceforge.net or in a google search, so I ran it and got:
$ [
[: missing `]'
$

so I gave it ] as a parameter and got
$ [ ]

$

It didn't complain, so I assumed it was on the right track. I tried:
$ [ hello ]

again, no complaints. so I tried an arithmetic expression:
$ [ 1 + 1 ]
[: +: binary operator expected
$

I tried a bunch of different combinations, including prefix & postfix notation but nothing seemed to work. What does this thing do?

A: test a

==
[ a ]

It's just sugar
Edit: To clarify, that's the conditional syntax, e.g. [ "a" = "a" ]

A: It's used to evaluate conditional expressions.
It is equivalent to (possibly a symlink to?) the test executable.
The manpage is here.
You may see this in a lot of bash scripts:
if [ "$LOGNAME" = "scott" ]
then
    echo "Logged in as Scott"
else
     echo "incorrect user"
fi

The funny thing is, the [ is not part of the bash language, it's actually an executable whose return code is used by the 'IF'. This is the reason why the space after the [ and its first argument is mandatory - if it would be omitted, the script would try to execute ["$LOGNAME" and fail.
You can't do arithmetical operations with it - use expr for that (see here).
However, you can test for a wide range of file properties (does it exist? what type is it? etc) as well as use comparison operators on strings and numbers.

A: Another answer already mentioned it is the same as test. On bash, it is also a builtin, so you can get the help for it with the help builtin (help test).


text:
Q: Flask - Form on Modal - How to display the field error on modal? I am experimenting with flask and just creating some basic functionality to add data to a form displayed in a modal. While I have managed to get the form to display in the modal and save it from the modal, I am struggling to understand what needs to be done to ensure that field validation errors are shown on the modal itself. Currently if there are errors user is redirected to a whole page with edit form.
They say picture is better than words - So here is a gif showing what is happening:

The entire app code is on github and the current state on heroku can be accessed here... username: admin@admin.com and password: adminpassword. It's all sandbox anyway.
Relevant code is as below:
routes.py

@expenses.route("/expense")
@login_required
def expense():
    page = request.args.get('page', 1, type=int)
    expenses = Expense.query.order_by(Expense.expense_date.desc()).paginate(page=page, per_page=5)
    form = ExpenseForm()
    return render_template('expense/expense.html', expenses=expenses, form=form)

@expenses.route("/expense/new", methods=['GET', 'POST'])
@login_required
def new_expense():
    form = ExpenseForm()
    if form.validate_on_submit():
        expense = Expense(description=form.description.data, expense_date=form.expense_date.data,
                        amount=form.amount.data,vat_amount=form.vat_amount.data,Transferrable=form.Transferrable.data, author=current_user)
        db.session.add(expense)
        db.session.commit()
        flash('Your expense has been created!', 'success')
        return redirect(url_for('expenses.expense'))
    return render_template('expense/create_expense.html', title='New Expense',
                           form=form, legend='New Expense')

Now the expenses.html is a big one but on it the modal is called using the following:
<button type="button" class="btn btn-primary btn-sm m-1" data-toggle="modal" data-target="#AddNewModal">Add New Expense</button>
{% include "expense/partials/addModal.html" %}

and the addModal.html is as shown below:

{% from "util/macros.html" import form_field with context %}

Add New Expense

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
        ×
        </button>

          <form method="POST" action="/expense/new">
          {{ form.hidden_tag() }}
          <fieldset class="form-group">
            <legend class="border-bottom mb-4">{{ legend }}</legend>

              {{ form.description.label(class="form-control-label") }}
              {% if form.description.errors %}
                {{ form.description(class="form-control form-control-lg is-invalid") }}

                  {% for error in form.description.errors %}
                  {{ error }}
                  {% endfor %}

              {% else %}
                {{ form.description(class="form-control form-control-lg") }}
              {% endif %}

              {{ form.amount.label(class="form-control-label") }}
              {% if form.amount.errors %}
                {{ form.amount(class="form-control form-control-lg is-invalid") }}

                {% for error in form.amount.errors %}
                  {{ error }}
                {% endfor %}

              {% else %}
                {{ form.amount(class="form-control form-control-lg") }}
              {% endif %}

              {{ form.expense_date.label(class="form-control-label") }}
              {% if form.expense_date.errors %}
                {{ form.expense_date(class="form-control form-control-lg is-invalid") }}

                  {% for error in form.expense_date.errors %}
                    {{ error }}
                  {% endfor %}

              {% else %}
                {{ form.expense_date(class="form-control form-control-lg", type="date") }}
              {% endif %}

              {{ form.vat_amount.label(class="form-control-label") }}
              {% if form.vat_amount.errors %}
                {{ form.vat_amount(class="form-control form-control-lg is-invalid") }}

                  {% for error in form.vat_amount.errors %}
                    {{ error }}
                  {% endfor %}

              {% else %}
                {{ form.vat_amount(class="form-control form-control-lg") }}
              {% endif %}

            {% if form.Transferrable.errors %}
              {{ form.Transferrable(class="form-control form-control-lg is-invalid") }}

                {% for error in form.Transferrable.errors %}
                  {{ error }}
                {% endfor %}

            {% else %}
              {{ form.Transferrable(type="checkbox") }}
            {% endif %}
              {{ form.Transferrable.label(class="form-control-label") }}

<button type="submit" class="btn btn-primary">Add</button>

            </fieldset>
          </form>

          <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>

A: It is because if form has some errors you render create_expense.html that's why form is presented not in modal.
I would merge 2 views: /expense/new and /expense so that it can handle both GET and POST and conditionally show modal if form has some errors.
Merged views:
@expenses.route("/expense", methods=['GET', 'POST'])
@login_required
def expense():
    page = request.args.get('page', 1, type=int)
    expenses = Expense.query.order_by(Expense.expense_date.desc()).paginate(page=page, per_page=5)
    form = ExpenseForm()
    if form.validate_on_submit():
        expense = Expense(description=form.description.data, expense_date=form.expense_date.data,
                        amount=form.amount.data,vat_amount=form.vat_amount.data,Transferrable=form.Transferrable.data, author=current_user)
        db.session.add(expense)
        db.session.commit()
        flash('Your expense has been created!', 'success')
    return render_template('expense/expense.html', expenses=expenses, form=form)

Conditional modal showing at the bottom of addModal.html:
{% if form.errors %}

{% endif %}

And action for the form in addModal.html must be changed as well to:
<form method="POST" action="/expense">

However after these changes views /expense/new and /expense would have some code in common so refactoring might be needed. Now you at least know why errors are not shown in the modal.


text:
Q: How does Angular compile the DOM and process the directives? I am really curious about Angular's working mechanism (its workflow/pipeline). Short of diving into the source code, I don't find any material explaining this clearly.
Can anyone explain how Angular compile the HTML and directives?


text:
Q: Restricting Search Results based on list permissions I am attempting to restrict search results based on list permissions where the user should only be able to see those items which they added.  This works in the list itself using the "Read items that were created by the user" option.  However, search does not return any results from the list while this is active for anyone other than those users who have full control.
Could someone please advise?

A: It's because Search crawling account only has "Full Read" Access to the content which means, with those library settings enabled, the crawler isn't finding any items in the library to crawl.
If it's an On Prem environment, you could elevate the permissions for the Search Crawling account (Central Admin --> Web Applications --> Select the web app --> User policy --> Change the permission for the Search Crawling Account.
However wouldn't recommend doing that. So probably review the security requirements for your documents and then change the settings appropriately.


text:
Q: How to convert cftime.Datetime360Day to normal datetime I have an exported csv file that contains extracted climate data from netCDF file, however the Date column has exported as below list, I would like to change this column to normal datetime.
Is there any solution please!
Thanks!
(cftime.Datetime360Day(2006, 1, 1, 12, 0, 0, 0, has_year_zero=True),)

(cftime.Datetime360Day(2006, 1, 2, 12, 0, 0, 0, has_year_zero=True),)

(cftime.Datetime360Day(2006, 1, 3, 12, 0, 0, 0, has_year_zero=True),)

(cftime.Datetime360Day(2006, 1, 4, 12, 0, 0, 0, has_year_zero=True),)

(cftime.Datetime360Day(2006, 1, 5, 12, 0, 0, 0, has_year_zero=True),)

(cftime.Datetime360Day(2006, 1, 6, 12, 0, 0, 0, has_year_zero=True),)

(cftime.Datetime360Day(2006, 1, 7, 12, 0, 0, 0, has_year_zero=True),)

(cftime.Datetime360Day(2006, 1, 8, 12, 0, 0, 0, has_year_zero=True),)

I would like to change this column to normal datetime.
Is there any solution please!
Thanks!

A: Datetime360Day is a calendar with every year being 360 days long (divided into 30 day months)
Generally (in around all languages) if there is no means that can help you to do the conversion natively :
You have to use the datetime api and format a string coming from the calendar output.
Regards

A: I assume you've tried pandas pd.to_datetime() already, right?
If not, give that a shot. It generally works really well.


text:
Q: Почему на сайтах не используется отступ для начала красной строки? Почему даже на сайтах, основной контент которых основан на каких-то статьях, написания большого количества текста, не используется отступ на первом предложении при каждом новом абзаце?
Для этого есть своё css свойство, text-indent.
Грубо говоря, в школе всегда учили его ставить. А в интернете такого просто днем с огнем не сыщешь.
Почему такой отступ опускают всегда даже на новостных сайтах, где за форматированием смотрят (на нормальных сайтах), чтобы оно было идеальным?


text:
Q: Mapping lat/lon to zip code level or climate region level I have  a CFSR  30-year  climatology .nc file. I could read in the file and  get  lat, lon , date  and temperature. Now I  need roll up these information to a zip code then later to climate region level.
Where could I find such mapping?
I could find a zip code shapefile, I'm thinking I could find all the points within each zip code then roll up to region level.
Does anybody have more straightforward method?
I'm using R or Python to load the data.


text:
Q: How to use current date time in xamarin forms date picker? I have a xamarin App applying for leave. The student should apply to leave within 3 days from the day they took leave. If they take leave on 03-oct-2020 then they should apply to leave on or before October 6. I am using the calendar for selecting a date and setting the maximum date as today and a minimum date as Today -3. So the last remaining days won't be available. It's working. But when the student set the device date manually to any past date. Then the calendar in the app also changed to that date. How could prevent this?
Please help me on this

A: Here's a little sample to get date from internet and not depending on your local machine
View :
<StackLayout>
   <Label x:Name="dateLabel" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"/>
   <Button Text="Get Date" Clicked="Button_Clicked" HorizontalOptions="CenterAndExpand" VerticalOptions="CenterAndExpand"/>
</StackLayout>

Code Behind:
private void Button_Clicked(object sender, EventArgs e)
        {
            using (var httpClient = new HttpClient())
            {
                var response = httpClient.GetStringAsync(new Uri("http://worldtimeapi.org/api/timezone/Asia/Kolkata")).Result;

                ServerDateTime sDateTime = Newtonsoft.Json.JsonConvert.DeserializeObject<ServerDateTime>(response);

                dateLabel.Text = sDateTime.datetime.ToString("dd.MM.yyyy");
            }
        }

Model
public class ServerDateTime
    {
        public string abbreviation { get; set; }
        public string client_ip { get; set; }
        public DateTime datetime { get; set; }
        public int day_of_week { get; set; }
        public int day_of_year { get; set; }
        public bool dst { get; set; }
        public object dst_from { get; set; }
        public int dst_offset { get; set; }
        public object dst_until { get; set; }
        public int raw_offset { get; set; }
        public string timezone { get; set; }
        public int unixtime { get; set; }
        public DateTime utc_datetime { get; set; }
        public string utc_offset { get; set; }
        public int week_number { get; set; }
    }

A little side note on the cleartext HTTP issue:
https://forums.xamarin.com/discussion/164771/cleartext-http-traffic-not-permitted


text:
Q: Apply random rotation to canvas particles I'm trying to update an existing particle animation. In this demo, the particles are just lines with different lineWidths with random sizes and rotation as they fall down.
My goal is to replace the lines with a different shape, which looks like the image below keeping everything else as is.

I've already changed the shape, but I'm having a couple issues:

*

*It doesn't rotate anymore like in the original demo link posted above.

*Since, I replaced the lines with an image of the shape, I'm also facing performance issues if I increase the particles.

*If I randomize the size, it keeps updating the size of the shape constantly without keeping the first random size.
context.drawImage(svg, x, y, 20, 40)
                  |
                  v
context.drawImage(svg, x, y, Math.random() * 20, Math.random() * 40)

Could anybody point me in the right direction on I should go about fixing the above. Appreciate any help!

var confetti = {
  maxCount: 150,     //set max confetti count
  speed: 1,          //set the particle animation speed
  frameInterval: 30, //the confetti animation frame interval in milliseconds
  alpha: 1.0,        //the alpha opacity of the confetti (between 0 and 1, where 1 is opaque and 0 is invisible)
  gradient: false,   //whether to use gradients for the confetti particles
  start: null,       //call to start confetti animation (with optional timeout in milliseconds, and optional min and max random confetti count)
  stop: null,        //call to stop adding confetti
  toggle: null,      //call to start or stop the confetti animation depending on whether it's already running
  pause: null,       //call to freeze confetti animation
  resume: null,      //call to unfreeze confetti animation
  togglePause: null, //call to toggle whether the confetti animation is paused
  remove: null,      //call to stop the confetti animation and remove all confetti immediately
  isPaused: null,    //call and returns true or false depending on whether the confetti animation is paused
  isRunning: null    //call and returns true or false depending on whether the animation is running
};

(function() {
  confetti.start = startConfetti;
  confetti.stop = stopConfetti;
  confetti.toggle = toggleConfetti;
  confetti.pause = pauseConfetti;
  confetti.resume = resumeConfetti;
  confetti.togglePause = toggleConfettiPause;
  confetti.isPaused = isConfettiPaused;
  confetti.remove = removeConfetti;
  confetti.isRunning = isConfettiRunning;
  var supportsAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame;
  var colors = ["rgba(30,144,255,", "rgba(107,142,35,", "rgba(255,215,0,", "rgba(255,192,203,", "rgba(106,90,205,", "rgba(173,216,230,", "rgba(238,130,238,", "rgba(152,251,152,", "rgba(70,130,180,", "rgba(244,164,96,", "rgba(210,105,30,", "rgba(220,20,60,"];
  var streamingConfetti = false;
  var animationTimer = null;
  var pause = false;
  var lastFrameTime = Date.now();
  var particles = [];
  var waveAngle = 0;
  var context = null;

  function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  function resetParticle(particle, width, height) {
    particle.color = colors[(Math.random() * colors.length) | 0] + (confetti.alpha + ")");
    particle.color2 = colors[(Math.random() * colors.length) | 0] + (confetti.alpha + ")");
    particle.x = getRandomInt(0, width);
    particle.y = getRandomInt(-height / 2, 0);
    particle.diameter = Math.random() * 10 + 5;
    particle.tilt = Math.random() * 10 - 10;
    particle.tiltAngleIncrement = Math.random() * 0.07 + 0.05;
    particle.tiltAngle = Math.random() * Math.PI;
    return particle;
  }

  function toggleConfettiPause() {
    if (pause)
      resumeConfetti();
    else
      pauseConfetti();
  }

  function isConfettiPaused() {
    return pause;
  }

  function pauseConfetti() {
    pause = true;
  }

  function resumeConfetti() {
    pause = false;
    runAnimation();
  }

  function runAnimation() {
    if (pause)
      return;
    else if (particles.length === 0) {
      context.clearRect(0, 0, window.innerWidth, window.innerHeight);
      animationTimer = null;
    } else {
      var now = Date.now();
      var delta = now - lastFrameTime;
      if (!supportsAnimationFrame || delta > confetti.frameInterval) {
        context.clearRect(0, 0, window.innerWidth, window.innerHeight);
        updateParticles();
        drawParticles(context);
        lastFrameTime = now - (delta % confetti.frameInterval);
      }
      animationTimer = requestAnimationFrame(runAnimation);
    }
  }

  function startConfetti(timeout, min, max) {
    var width = window.innerWidth;
    var height = window.innerHeight;
    window.requestAnimationFrame = (function() {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function(callback) {
          return window.setTimeout(callback, confetti.frameInterval);
        };
    })();
    var canvas = document.getElementById("confetti-canvas");
    if (canvas === null) {
      canvas = document.createElement("canvas");
      canvas.setAttribute("id", "confetti-canvas");
      canvas.setAttribute("style", "display:block;z-index:999999;pointer-events:none;position:fixed;top:0");
      document.body.prepend(canvas);
      canvas.width = width;
      canvas.height = height;
      window.addEventListener("resize", function() {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
      }, true);
      context = canvas.getContext("2d");
    } else if (context === null)
      context = canvas.getContext("2d");
    var count = confetti.maxCount;
    if (min) {
      if (max) {
        if (min == max)
          count = particles.length + max;
        else {
          if (min > max) {
            var temp = min;
            min = max;
            max = temp;
          }
          count = particles.length + ((Math.random() * (max - min) + min) | 0);
        }
      } else
        count = particles.length + min;
    } else if (max)
      count = particles.length + max;
    while (particles.length < count)
      particles.push(resetParticle({}, width, height));
    streamingConfetti = true;
    pause = false;
    runAnimation();
    if (timeout) {
      window.setTimeout(stopConfetti, timeout);
    }
  }

  function stopConfetti() {
    streamingConfetti = false;
  }

  function removeConfetti() {
    stop();
    pause = false;
    particles = [];
  }

  function toggleConfetti() {
    if (streamingConfetti)
      stopConfetti();
    else
      startConfetti();
  }

  function isConfettiRunning() {
    return streamingConfetti;
  }

  function drawParticles(context) {
    var particle;
    var x, y, x2, y2;
    for (var i = 0; i < particles.length; i++) {
      particle = particles[i];
      particleWidth = particle.diameter;
      x2 = particle.x + particle.tilt;
      x = x2 + particle.diameter / 2;
      y = particle.y;

      var svg = new Image();
      svg.src = 'https://i.postimg.cc/TPBmVXH1/confetti.png';
      context.drawImage(svg, x, y, 20, 40)

      /*context.beginPath();
      context.lineWidth = particle.diameter;
      x2 = particle.x + particle.tilt;
      x = x2 + particle.diameter / 2;
      y2 = particle.y + particle.tilt + particle.diameter / 2;
      if (confetti.gradient) {
       var gradient = context.createLinearGradient(x, particle.y, x2, y2);
       gradient.addColorStop("0", particle.color);
       gradient.addColorStop("1.0", particle.color2);
       context.strokeStyle = gradient;
      } else
       context.strokeStyle = particle.color;
      context.moveTo(x, particle.y);
      context.lineTo(x2, y2);
      context.stroke();*/
    }
  }

  function updateParticles() {
    var width = window.innerWidth;
    var height = window.innerHeight;
    var particle;
    waveAngle += 0.01;
    for (var i = 0; i < particles.length; i++) {
      particle = particles[i];
      if (!streamingConfetti && particle.y < -15)
        particle.y = height + 100;
      else {
        particle.tiltAngle += particle.tiltAngleIncrement;
        particle.x += Math.sin(waveAngle) - 0.5;
        particle.y += (Math.cos(waveAngle) + particle.diameter + confetti.speed) * 0.5;
        particle.tilt = Math.sin(particle.tiltAngle) * 15;
      }
      if (particle.x > width + 20 || particle.x < -20 || particle.y > height) {
        if (streamingConfetti && particles.length <= confetti.maxCount)
          resetParticle(particle, width, height);
        else {
          particles.splice(i, 1);
          i--;
        }
      }
    }
  }
  startConfetti(5000, 20, 25)
})();
html {
  height: 100%;
}

body,
html {
  margin: 0;
}

body {
  background: black;
}

A: Ok so here is what I did:

*

*I changed drawParticles to apply the particle.tilt.

*I moved the svg variable to the top so it is reused and not loaded multiple times.

*I did set the random size in resetParticle so it does not change afterwards.

var confetti = {
  maxCount: 150,  //set max confetti count
  speed: 1,   //set the particle animation speed
  frameInterval: 30, //the confetti animation frame interval in milliseconds
  alpha: 1.0,   //the alpha opacity of the confetti (between 0 and 1, where 1 is opaque and 0 is invisible)
  gradient: false, //whether to use gradients for the confetti particles
  start: null,  //call to start confetti animation (with optional timeout in milliseconds, and optional min and max random confetti count)
  stop: null,   //call to stop adding confetti
  toggle: null,  //call to start or stop the confetti animation depending on whether it's already running
  pause: null,  //call to freeze confetti animation
  resume: null,  //call to unfreeze confetti animation
  togglePause: null, //call to toggle whether the confetti animation is paused
  remove: null,  //call to stop the confetti animation and remove all confetti immediately
  isPaused: null,  //call and returns true or false depending on whether the confetti animation is paused
  isRunning: null  //call and returns true or false depending on whether the animation is running
};

(function () {
  confetti.start = startConfetti;
  confetti.stop = stopConfetti;
  confetti.toggle = toggleConfetti;
  confetti.pause = pauseConfetti;
  confetti.resume = resumeConfetti;
  confetti.togglePause = toggleConfettiPause;
  confetti.isPaused = isConfettiPaused;
  confetti.remove = removeConfetti;
  confetti.isRunning = isConfettiRunning;
  var supportsAnimationFrame = window.requestAnimationFrame || window.webkitRequestAnimationFrame || window.mozRequestAnimationFrame || window.oRequestAnimationFrame || window.msRequestAnimationFrame;
  var colors = ["rgba(30,144,255,", "rgba(107,142,35,", "rgba(255,215,0,", "rgba(255,192,203,", "rgba(106,90,205,", "rgba(173,216,230,", "rgba(238,130,238,", "rgba(152,251,152,", "rgba(70,130,180,", "rgba(244,164,96,", "rgba(210,105,30,", "rgba(220,20,60,"];
  var streamingConfetti = false;
  var animationTimer = null;
  var pause = false;
  var lastFrameTime = Date.now();
  var particles = [];
  var waveAngle = 0;
  var context = null;

  var sizes = [];
  var svg = new Image();

  svg.src = 'https://i.postimg.cc/TPBmVXH1/confetti.png';

  function getRandomInt(min, max) {
    min = Math.ceil(min);
    max = Math.floor(max);
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  function resetParticle(particle, width, height) {
    particle.color = colors[(Math.random() * colors.length) | 0] + (confetti.alpha + ")");
    particle.color2 = colors[(Math.random() * colors.length) | 0] + (confetti.alpha + ")");
    particle.x = getRandomInt(0, width);
    particle.y = getRandomInt(-height / 2, 0);
    particle.diameter = Math.random() * 10 + 5;
    particle.tilt = Math.random() * 10 - 10;
    particle.tiltAngleIncrement = Math.random() * 0.07 + 0.05;
    particle.tiltAngle = Math.random() * Math.PI;

    particle.width = Math.random() * 20
    particle.height = Math.random() * 40

    return particle;
  }

  function toggleConfettiPause() {
    if (pause)
      resumeConfetti();
    else
      pauseConfetti();
  }

  function isConfettiPaused() {
    return pause;
  }

  function pauseConfetti() {
    pause = true;
  }

  function resumeConfetti() {
    pause = false;
    runAnimation();
  }

  function runAnimation() {
    if (pause)
      return;
    else if (particles.length === 0) {
      context.clearRect(0, 0, window.innerWidth, window.innerHeight);
      animationTimer = null;
    } else {
      var now = Date.now();
      var delta = now - lastFrameTime;
      if (!supportsAnimationFrame || delta > confetti.frameInterval) {
        context.clearRect(0, 0, window.innerWidth, window.innerHeight);
        updateParticles();
        drawParticles(context);
        lastFrameTime = now - (delta % confetti.frameInterval);
      }
      animationTimer = requestAnimationFrame(runAnimation);
    }
  }

  function startConfetti(timeout, min, max) {
    var width = window.innerWidth;
    var height = window.innerHeight;
    window.requestAnimationFrame = (function () {
      return window.requestAnimationFrame ||
        window.webkitRequestAnimationFrame ||
        window.mozRequestAnimationFrame ||
        window.oRequestAnimationFrame ||
        window.msRequestAnimationFrame ||
        function (callback) {
          return window.setTimeout(callback, confetti.frameInterval);
        };
    })();
    var canvas = document.getElementById("confetti-canvas");
    if (canvas === null) {
      canvas = document.createElement("canvas");
      canvas.setAttribute("id", "confetti-canvas");
      canvas.setAttribute("style", "display:block;z-index:999999;pointer-events:none;position:fixed;top:0");
      document.body.prepend(canvas);
      canvas.width = width;
      canvas.height = height;
      window.addEventListener("resize", function () {
        canvas.width = window.innerWidth;
        canvas.height = window.innerHeight;
      }, true);
      context = canvas.getContext("2d");
    } else if (context === null)
      context = canvas.getContext("2d");
    var count = confetti.maxCount;
    if (min) {
      if (max) {
        if (min == max)
          count = particles.length + max;
        else {
          if (min > max) {
            var temp = min;
            min = max;
            max = temp;
          }
          count = particles.length + ((Math.random() * (max - min) + min) | 0);
        }
      } else
        count = particles.length + min;
    } else if (max)
      count = particles.length + max;
    while (particles.length < count)
      particles.push(resetParticle({}, width, height));
    streamingConfetti = true;
    pause = false;
    runAnimation();
    if (timeout) {
      window.setTimeout(stopConfetti, timeout);
    }
  }

  function stopConfetti() {
    streamingConfetti = false;
  }

  function removeConfetti() {
    stop();
    pause = false;
    particles = [];
  }

  function toggleConfetti() {
    if (streamingConfetti)
      stopConfetti();
    else
      startConfetti();
  }

  function isConfettiRunning() {
    return streamingConfetti;
  }

  function drawParticles(context) {
    var particle;
    var x, y, x2, y2;
    for (var i = 0; i < particles.length; i++) {
      particle = particles[i];
      particleWidth = particle.diameter;
      x2 = particle.x + particle.tilt;
      x = x2 + particle.diameter / 2;
      y = particle.y;

      context.save();
      context.translate(x, y);
      context.rotate(particle.tilt / 180 * Math.PI);
      context.translate(-x, -y);
      context.drawImage(svg, x, y, particle.width, particle.height);
      context.restore();

   /*context.beginPath();
   context.lineWidth = particle.diameter;
   x2 = particle.x + particle.tilt;
   x = x2 + particle.diameter / 2;
   y2 = particle.y + particle.tilt + particle.diameter / 2;
   if (confetti.gradient) {
    var gradient = context.createLinearGradient(x, particle.y, x2, y2);
    gradient.addColorStop("0", particle.color);
    gradient.addColorStop("1.0", particle.color2);
    context.strokeStyle = gradient;
   } else
    context.strokeStyle = particle.color;
   context.moveTo(x, particle.y);
   context.lineTo(x2, y2);
   context.stroke();*/
    }
  }

  function updateParticles() {
    var width = window.innerWidth;
    var height = window.innerHeight;
    var particle;
    waveAngle += 0.01;
    for (var i = 0; i < particles.length; i++) {
      particle = particles[i];
      if (!streamingConfetti && particle.y < -15)
        particle.y = height + 100;
      else {
        particle.tiltAngle += particle.tiltAngleIncrement;
        particle.x += Math.sin(waveAngle) - 0.5;
        particle.y += (Math.cos(waveAngle) + particle.diameter + confetti.speed) * 0.5;
        particle.tilt = Math.sin(particle.tiltAngle) * 15;
      }
      if (particle.x > width + 20 || particle.x < -20 || particle.y > height) {
        if (streamingConfetti && particles.length <= confetti.maxCount)
          resetParticle(particle, width, height);
        else {
          particles.splice(i, 1);
          i--;
        }
      }
    }
  }
  startConfetti(5000, 20, 25)
})();
html {
  height: 100%;
}
body, html {
  margin: 0;
}
body {
  background: black;
}


text:
Q: How to read Text values of node XSLT How can read the value of node/element , which ignores few child tags.
I have List of tags which requires to be Ignored,
Example :
a)
    OUTPUT :Title Txt a
<Title>
     <Comment>Comment code</Comment>Title Txt a
 </Title>

b)
     OUTPUT :Title Txt b
 <Title>
     <Ignore1>Comment code</Ignore1>Title Txt b
 </Title>

c)
    OUTPUT :Comment code Title Txt c
 <Title>
     <includethis>Comment code</includethis>Title Txt c
 </Title>

A: You simply match for the Title element:
<xsl:template match="Title">

and output its text content:
<xsl:value-of select="."/>

Then, process the child nodes in turn:
<xsl:template match="*[parent::Title and starts-with(.,'Ignore')]"/>

<xsl:template match="includethis">
  <xsl:value-of select="."/>
</xsl:template>

Above, the first template matches elements whose name starts with "Ignore". This is because I assume there could me other elements named Ignore2, Ignore3 and so on.
Finally,  the includethis elements are matched and their text content is output, same as for the Title elements.
Now, to sum up:
<?xml version="1.0" encoding="utf-8"?>

<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

<xsl:output method="xml" indent="yes"/>

<xsl:template match="/Title">
  <xsl:value-of select="."/>
  <xsl:apply-templates/>
</xsl:template>

<xsl:template match="*[parent::Title and starts-with(.,'Ignore')]"/>

<xsl:template match="includethis">
  <xsl:value-of select="."/>
</xsl:template>

</xsl:stylesheet>

A: Thanks for your Help. But i missed to mention the important condition which started the problem,
I need to check the 'Title' for not empty before starting any processing.
example below tag is considered empty, when the child tag is from one from the Ignored List.
<Title>
 <Comment>Comment code</Comment>
</Title>

Sample Code :
<xsl:choose>
  <xsl:when test="Title and normalize-space(Title) != ''">
   <xsl:apply-templates select="Title" mode="xyz"/>
  </xsl:when>
  <xsl:otherwise>
    <xsl:call-templates name="getalternative_label" mode="xyz"/>
  </xsl:otherwise>
</xsl:choose>


text:
Q: Widget not returning view on Future condition in flutter Widget not returning view. isAttrAssignedToProduct in this method I'm trying to find the assigned attribute in the table if the product exists in the table then return true and the image will be inflated in listview item on the base of true or false. My database returning true or false on condition but the view is not visible.
Widget isAttrAssigned(int index){
Future result = isAttrAssignedToProduct(index);
return FutureBuilder(
    future: result,
    builder: (BuildContext context, AsyncSnapshot snapshot) {
      result.then((v){
        debugPrint('FUTURE VALE ${v}');
        attr(v);
      });
},);
 Widget attr(bool v){
    return v==true?Container(
      width: 20.0,
      height: 20.0,
      decoration: BoxDecoration(
          color: Colors.yellow),
      child: Image.asset('assets/images/right.png'),
    ):Text('df');
  }

My Query working fine
 Future<bool> isAttrAssignedToProduct(int index) async {
    List<Map<String, dynamic>> assd=new List<Map<String, dynamic>>();
    try{
      assd= await dbHelper.queryReadGroupAssignedAttribute(productList[index][DatabaseHelper.columnpid]);
      if(assd.length>0){
       // debugPrint('ASSIGNED ATTR PRESENT ${assd.length}');
        return true;
      }else{
        return false;
      }
    }catch(e){
      //debugPrint('ASSIGNED ATTR EXCEPTION ${e}');
      return false;
    }
  }

My List Tile
ListTile(
          contentPadding: EdgeInsets.only(left: height*0.03,right: height*0.03 ),
          onTap: (){
            Navigator.push(context,
              MaterialPageRoute(builder: (context) => ProductDetails(pid: productList[index]["pid"],),
                  settings: RouteSettings(name: '/productdetail')),).then((value){
                    setState(() {
                      length=value;
                    });
                    debugPrint('CEHCK BACK FROM DAETAIL $length');
            });
          },
          title: Text(
              '${title}',
              style: TextStyle(fontFamily: 'semibold',color: MyColors.colorPrimaryDark,fontSize: 18.0)),
          subtitle: Text(
              'Price \$${price}',
              style: TextStyle(color: Colors.grey,fontSize: 14.0,fontFamily: 'semibold')),
          trailing:isAttrAssigned( index), //here i'm trying to inflate image
        ),

A: You should use FutureBuilder. Examples in the link. Very easy to use

A: your function Widget isAttrAssigned is not returning anything.
If you want to build a widget based on a Future, you can use a FutureBuilder https://docs.flutter.io/flutter/widgets/FutureBuilder-class.html
Widget isAttrAssigned(int index) {
   // maybe you want to cache your result here, to avoid doing a call at each rebuild
   Future result = isAttrAssignedToProduct(index);

   return FutureBuilder(
      future: result
      builder: (BuildContext context, AsyncSnapshot snapshot) {
     // return widget
   });

}

snapshot.data is your boolean
switch (snapshot.connectionState) {
case ConnectionState.none:
return Container(); // empty or show a placeholder
case ConnectionState.active:
case ConnectionState.waiting:
return Text('Loading ...');
case ConnectionState.done:
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
}
return attr(snapshot.data);
}


text:
Q: Proper explanation for NodeJS/Typescript Export / Import? Could someone please explain exactly how exports and imports work in NodeJS using Typescript?
My setup is:

*

*NodeJS

*Everything in Typescript

*TSLint

*Typings

I am messing about with exports/imports instead of doing some proper coding, its driving me nuts, and cannot find any proper explanation of how it works.
Import
Can you please explain following:
var module = require ("module");

import module = require("module");

import module from "module";

import {something} from "module";

import * as module from "module";

Export
Can you please explain following
export = something;

export default something;

export interface|class something;

Questions

*

*How do properly export/import a class without initiating it

*How do properly export/import a class with it being initiated (construct did run)

*How do I properly export/import a class and interface

*How do I properly export/import class and multiple interfaces

*When to use modules declarations, what are they good for and why is tslint throwing errors at me if I try to use them.

I cannot seem to find proper way of doing exports vs. imports so my IDE is not covered in red and throwing hundreds of errors at me.
General Questions

*

*Is there even a way to not get errors using nodejs/typescript/tslint?

*TSLint is screaming at me for almost anything I type... it is extremely frustrating since there is 0 explanation to most of the errors. Is it even worth using it?

List of questions goes on and on, but im sure once some of the above is answered, I can pick up on the rest.
Thank you and sorry for such a general question, but my frustration level just reached the top...

A: Agreed, import/export syntax is confusing for at least two reasons:

*

*the commonjs syntax: var module = require ("module"); works but that is commonjs -> no typings

*it changed: the syntax import x = require('y') is now deprecated in TS

TL;DR;: Use the 'es6 style' syntax introduced in TS 1.5
The 'best' resource on import/export in TS I know is this
Overall I recommend reading this excellent handbook which will provide answers to most of your questions
To import
From a default export
Something was exported as a default (single) export ie export default Something in ts/es6
Use
import Something from "module"

You can actually import a default export with a different name. import SomethingElse from 'module' will also work
From named exports
Something was exported as a named export in "module"  using export {Something} or export class|interface Something{} in ts/es6
You want to import only that, use
import {Something} from "module"

You want to import everything that is exported from "module" under the namespace mod
import * as mod from "module

Then use const c:mod.Something = whatever
To export
See imports above
The form export = something is deprecated in favor of the new ES6 style syntax. It is mostly found in definition files to express the fact that a js library exports a single function/object e.g. module.exports=something.
What you should try using
Use ES6 style syntax and avoid default exports: they have the advantage that they can be imported using a different name but

*

*a default import cannot be re-exported, which may be problematic if you are writing a library

*they will confuse a lot of IDEs (not to mention yourself) when refactoring

*a named export can actually be locally renamed when imported i.e. import {Something as SomethingElse} from "module"
Concretely, export whatever needs to be exported and import it specifically
In api.ts
export interface MyInterface {
}

export class MyClass {
}

In main.ts
 import {MyInterface, MyClass} from './api'

Linting
There are a lot of good IDEs out there that provide excellent linting: VSCode, Atom Typescript and Webstorm to name a popular few, the first two being free and the third one even manages the imports for you.


text:
Q: Loop to randomly display Images from Array (Android) I have an array of 5 images (R.drawable.one, R.drawable.two,R.drawable.three, R.drawable.four, and R.drawable.five).
Previously, my program would pick 5 random images from these and display them randomly on the screen without any errors. I then added myImgCount and totalImgCount because I want to give each image an int value. For example: R.drawable.one would be equal to 1, R.drawable.two would be equal to 2...etc. I then want my for loop to keep track of the images placed using myImgCount and then run until totalImgCount is equal to 50. After I added  myImgCount and totalImgCount I now have an error:
"11-26 18:22:16.750: E/AndroidRuntime(13971): FATAL EXCEPTION: Thread-33401
E/AndroidRuntime(13971): java.lang.NullPointerException"
on Bitmap bmp = BitmapFactory.decodeResource(getResources(), array1[i]);
Here is the code I have so far:
public void surfaceCreated(SurfaceHolder holder) {

ArrayList<Integer> list = new ArrayList<Integer>();

    Random r = new Random();

    int[] images = new int[] { R.drawable.one, R.drawable.two,
        R.drawable.three, R.drawable.four, R.drawable.five };

    int totalImgCount = 0;

    for (int i = 0; i<50; i++)
    {
        while (true)
        {
            int myImgCount = r.nextInt(5);

                 totalImgCount += myImgCount + 1;

            if (totalImgCount<50) {

                list.add(images[myImgCount]);   //do it again if not yet at 50
                break;
            }
                   totalImgCount -= (myImgCount + 1);
        }

    }

    array1 = convertIntegers(list);

    }

The next part of my code that is used to give the images int values:
public static int[] convertIntegers(List<Integer> integers) {
    int[] ret = new int[integers.size()];
    Iterator<Integer> iterator = integers.iterator();
    for (int i = 0; i < ret.length; i++) {
        ret[i] = iterator.next().intValue();
    }
    return ret;
}

Before getting this error my program would run without errors and display 5 random images on the screen. As I mentioned above I am trying to create a loop that keeps displaying random images until the total sum of the images is 50. Let me know if you need any more info! I appreciate any help and thanks in advance!
EDIT: Left out my render method where I"m getting the error:
public void render(Canvas canvas) {

    if (canvas != null) {

        Random random = new Random();
        canvas.drawRGB(234, 237, 235);

        for (int i=0; i<50; ++i) {
          Bitmap bmp = BitmapFactory.decodeResource(getResources(),
array1[i]);            //This is where I am currently getting the error
          canvas.drawBitmap(bmp,random.nextInt(canvas.getWidth()-bmp.getWidth
                      ()), random.nextInt
                        (canvas.getHeight()-bmp.getHeight()),null);

        }
    }

}

A: It sounds like you're not restricting your random numbers to the array indexes (0-4).
Start with this to constrain your numbers between 0 and 4.
    int range = images.length-1;
    int myImgCount = 0;

    Random random = new Random();
    for( int i = 0; i < 50; ++i)
    {
        myImgCount = random.nextInt(range);
        list.add(images[myImgCount]);
    }

Adjust your render method, see if this will help:
    if (canvas != null)
    {
         Random random = new Random();
         canvas.drawRGB(234, 237, 235);

         //iterate over your integer array
         //there should be 50 resource ids available
         for(int resourceId : array1)
         {
               Bitmap bmp = BitmapFactory.decodeResource(getResources(), resourceId);
               //This is where I am currently getting the error
               canvas.drawBitmap(bmp,
                     random.nextInt(canvas.getWidth()-bmp.getWidth()),
                     random.nextInt(canvas.getHeight()-bmp.getHeight()), null);

         }
     }

I would also change the following:
for (int i = 0; i<50; i++)
{
    while (true)
    {
        int myImgCount = r.nextInt(5);

             totalImgCount += myImgCount + 1;

        if (totalImgCount<50) {

            list.add(images[myImgCount]);   //do it again if not yet at 50
            break;
        }
               totalImgCount -= (myImgCount + 1);
    }

}

Possible change:
 int i = 0;

 while(i < 50)
 {
      //calculate random resource ids from your resource array here and add them to your array1
      i++;
 }


text: Q: Proving that $f(x_1,x_2\ldots x_n)=\frac{1}{n}\sum_{i}x_i^2 - \frac{1}{n^2}\sum_{i\neq j}\ln|x_i-x_j|\geq 4$ I came across this inequality in Andersen, Giounnet and Zeitouni's book on Random Matrix Theory. Now, we are asked to establish this using the two inequalities $\ln|x_i-x_j|\leq \ln(|x_i|+1)+\ln(|x_j|+1)$ and $x^2-2\ln(1+|x|)\geq -4$. Further, we are required to verify that $-\frac{1}{n^2}\sum_{i\neq j}\ln|x_i-x_j|\leq f(x_1,x_2\ldots x_n)+4$. What I am able to verify directly is that $f(x_1,x_2\ldots x_n)\geq -4$, but not sure how to proceed. For context, this is involved in the proof that Dyson Brownian Motion never hits the boundary of the Weyl Chamber $x_1<x_2<x_3\ldots <x_n$. Any resources towards that end will also be helpful.


text:
Q: Override Extension Helper I'm trying to override a part of an helper of Help Desk MX extension.
So I created a module with the following file:
app/etc/modules/company.xml
<?xml version="1.0" encoding="utf-8"?>
<config>
     <modules>
        <Company_Helpdesk>
            <active>true</active>
            <codePool>local</codePool>
        </Company_Helpdesk>
    </modules>
</config>

app/code/local/Company/Helpdesk/etc/config.xml
<?xml version="1.0"?>
<config>
    <modules>
        <Company_Helpdesk>
            <version>1.0.0</version>
        </Company_Helpdesk>
    </modules>
    <global>
        <helpers>
            <mirasvit_helpdesk>
                <rewrite>
                    <email>Company_Helpdesk_Helper_Email</data>
                </rewrite>
            </mirasvit_helpdesk>
        </helpers>
    </global>
</config>

app/code/local/Company/Helpdesk/Helper/Email.php
<?php
class Company_Helpdesk_Helper_Email extends Mirasvit_Helpdesk_Helper_Email
{
    public function getHiddenSeparator()
    {
        return "".$this->getSeparator().'';
    }
}

Following this guide: http://inchoo.net/magento/overriding-magento-blocks-models-helpers-and-controllers/
But it doesn't work.
Where am I wrong?

A: change this  in your config.xml
<global>
    <helpers>
        <mirasvit_helpdesk>
            <rewrite>
                <email>Company_Helpdesk_Helper_Email</email>
            </rewrite>
        </mirasvit_helpdesk>
    </helpers>
</global>

to this
<global>
    <helpers>
        <helpdesk>
            <rewrite>
                <email>Company_Helpdesk_Helper_Email</email>
            </rewrite>
        </helpdesk>
    </helpers>
</global>

also, in your app/etc/modules/company.xml add this inside the Company_Helpdesk tag
<depends>
     <Mirasvit_Helpdesk />
</depends>

A: Here i am show you how to Extend community Or third party module helper class in your own modules.
Now here i am extend asmaty extension helper.

*

*create your module register xml  app/etc/modules/Myextend_Shopbyextend.xml
<?xml version="1.0"?>
<config>
    <modules>
        <Myextend_Shopbyextend>
            <active>true</active>
            <codePool>local</codePool>
            <depends>
                <Amasty_Shopby />
            </depends>
        </Myextend_Shopbyextend>
    </modules>
</config>

*create module config.xml file app/code/local/Myextend/Shopbyextend/etc/

<?xml version="1.0"?>
<config>
   <modules>
       <Myextend_Shopbyextend>
           <version>0.1.0</version>
       </Myextend_Shopbyextend>
   </modules>
   <global>
        <helpers>
           <shopbyextend>
               <class>Myextend_Shopbyextend_Helper</class>
           </shopbyextend>
           <amshopby>
               <rewrite>
                   <data>Myextend_Shopbyextend_Helper_Data</data>
               </rewrite>
           </amshopby>
        </helpers>
   </global>
</config>

*Last create your help file app/code/local/Plumtree/Shopbyextend/Helper/Data.php and extends Amasty_Shopby_Helper_Data class

class Myextend_Shopbyextend_Helper_Data extends Amasty_Shopby_Helper_Data
{
  public function getCurrentCategory()
    {
          \\ Write your code here
    }
}
I hope this will help you


text:
Q: Получение пути картинки из MySql и вставка в Blade Необходимо для конкретного id новости получать соответствующий путь пикчи из БД. Насколько я знаю вставка картинок сама по себе делается так :
{{asset('images/image.jpg')}}

А адрес своей картинки из БД я получаю так :
{{$playerprofile->playerphoto}}

Как мне это "состыковать"?

A: (нормальный вариант)
Использовать тег img и в путь помещать данные из БД
<img src="{{$playerprofile->playerphoto}}" alt="">

(плохой вариант)
Если именно "состыковать", есть вариант вставить промежуточное
<?php
 $image = $playerprofile->playerphoto; ?>

{{asset($image)}}


text:
Q: Remove phrase from string using regex and a variable Can anyone help me with this regex I can't get the regex to match. I'm trying to remove the phrases that match from the string

let url = 'en-gb/products/product-category/186/product-type/2';
let word = "product-category";
let regex = new RegExp("\/" + word + "\/\d+", "g");
let output = url.replace(regex, '');
//desired output = 'en-gb/products/product-type/2'
console.log(output);

A: You were close, you need to do it like so:

let url = 'en-gb/products/product-category/186/product-type/2';
let word = 'product-category';
let regex = new RegExp(word + '/\\d+/', 'g');
let output = url.replace(regex, '');
//desired output = 'en-gb/products/product-type/2'
console.log(output);

Also please try to be consistent with either double or single quotes.


text:
Q: How to concatenate/join __VA_ARGS__ with delimiters/separators? I would like to expand a variadic macro to another macro that takes a single argument, which is formed by joining the variadic arguments with a delimiter/separator (e.g. "_"). Something like this:
#define FOO(...)

FOO(a, b, c, d);

which expands into
#define BAR(X)

BAR(a_b_c_d);

I know there is __VA_ARGS__ for working with the variadic parameters, and ## for concatenation. How do I use them together to achieve what I want (preferably using C++17 and older language features, without libraries such as Boost)?

A: First, there are no language feature that directly tackles the question you are trying to solve. (there might be complier specific ones, but I don't know).

However, if you know the upper limit of the amount of argument that macro can take(preferably not too many), you can use this answer as a guide to iterate through the __VA_ARGS__: Is it possible to iterate over arguments in variadic macros?

On the other hand, Boost.Preprocessor is a header only library. While it is a pretty heavy macro-only library that could bring a lot of ugliness behind the scene, it does offer simple ways to handle macros that take up to thousands of parameter.
Here's a quick one that should work for you:
#define CAT_OP(index, state, elem) BOOST_PP_CAT(state, BOOST_PP_CAT(_, elem))
#define CAT_SEQ(seq) BOOST_PP_SEQ_FOLD_LEFT(CAT_OP, BOOST_PP_SEQ_HEAD(seq), BOOST_PP_SEQ_TAIL(seq))
#define CAT_VA_ARGS(...) CAT_SEQ(BOOST_PP_VARIADIC_TO_SEQ(__VA_ARGS__))

Demo.
It treats the variadic as a Sequence, then performs a left fold over the sequence with concat operation.


text:
Q: Testing DAO file with junit +spring I'm trying to test a DAO file with junit. Is there a way to compare a same query that was performed with 2 different ways?
Does junit supplies a mechanism that uses in two ways to access the DB?

A: there are many different was to perform asserts on data using spring and junit .
Here is a starting point :
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:applicationContext-test.xml"})
@Transactional
public abstract class BaseIntegration {

Then your test classes can extend that and just use the dao as normal, and perform asserts on any data.

A: You can compare the results of the query using the methods in Assert class

A: To test DAOs you can use DBUnit


text:
Q: WSO2 API Manager showing "null" in every text and label of the UI I'm having the same problem presente in this topic.
https://stackoverflow.com/questions/16961129/wso2-api-manager-1-4-publisher-store-ui-not-working
In a browser outside the server, the UI is always showing "null" instead of the right texts of the fields and labels.
The previous link shows an answer, setting the browser language to english, is this the only way?
Thank you.

A: There is a workaround fix for this. As stated in Browser Language section in [1], you can rename
APIM_HOME/repository/deployment/server/jaggeryapps/publisher/site/conf/locales/jaggery/locale_en.json ,
APIM_HOME/repository/deployment/server/jaggeryapps/store/site/conf/locales/jaggery/locale_en.json
two files, replacing 'en' with your language code.
         ex: If the browser is running on Italy language, rename to locale_it.json.
[1]http://docs.wso2.org/wiki/display/AM140/Quick+Start


text:
Q: Reading *.mhd/*.raw format 3D images in ITK How to load and write .mhd/.raw format 3D images in ITK? I have tried to use the following code but it is not getting loaded as the dimension of the loaded image is displayed as 0,0,0.
Can someone please point out the mistake I am making?
typedef float InputPixelType;
const unsigned int  DimensionOfRaw = 3;
typedef itk::Image< InputPixelType, DimensionOfRaw > InputImageType;

//typedef itk::RawImageIO<InputPixelType, DimensionOfRaw> ImageIOType;
typedef itk::ImageFileReader<InputImageType >   ReaderType;

/*
 * --------------------Loader and saver of Raws, as well the function that takes a resulting (from inference matrix/vector) and creates a Raw out of it.-----------------------
 */
InputImageType::Pointer loadRawImageItk( std::string RawFullFilepathname, ReaderType::Pointer & RawImageIO ) {
    //http://www.itk.org/Doxygen/html/classitk_1_1Image.html
    //http://www.itk.org/Doxygen/html/classitk_1_1ImageFileReader.html

    typedef itk::ImageFileReader<InputImageType> ReaderType;

    ReaderType::Pointer reader = ReaderType::New();
    reader->SetFileName(RawFullFilepathname);

    //ImageIOType::Pointer RawImageIO = ImageIOType::New();
    reader->SetImageIO( RawImageIO );

    try {
        reader->Update();
    } catch (itk::ExceptionObject& e) {
        std::cerr << e.GetDescription() << std::endl;
        exit(1);  // You can choose to do something else, of course.
    }

    //InputImageType::Pointer inputImage = reader->GetOutput();
    InputImageType::Pointer inputImage = reader->GetOutput();

    return inputImage;

}

int saveRawImageItk( std::string RawFullFilepathname, InputImageType::Pointer & outputImageItkType , ImageIOType::Pointer & RawImageIO) {
  std::cout << "Saving image to: " << RawFullFilepathname << "\n";

  typedef itk::ImageFileWriter< InputImageType >  Writer1Type;
  Writer1Type::Pointer writer1 = Writer1Type::New();

  writer1->SetInput( outputImageItkType );
  writer1->SetFileName( RawFullFilepathname );
  writer1->SetImageIO( RawImageIO ); //seems like this is useless.

  // Execution of the writer is triggered by invoking the \code{Update()} method.
  try
    {
    writer1->Update();
    }
  catch (itk::ExceptionObject & e)
    {
    std::cerr << "exception in file writer " << std::endl;
    std::cerr << e.GetDescription() << std::endl;
    std::cerr << e.GetLocation() << std::endl;
    return 1;
    }

  return 0;
}

A: I have just read the mhd and raw files in Python successfully using the following SimpleITK code:
import SimpleITK as sitk
import numpy as np
def load_itk_image(filename):
    itkimage = sitk.ReadImage(filename)
    numpyImage = sitk.GetArrayFromImage(itkimage)
    return numpyImage

Maybe you can use it as a reference.
Whether you should use the ReadImage function instead of the ImageFileReader? You can have a try.

A: A few good examples of file reading depending on a known format are found here.
reader->SetImageIO( RawImageIO );
seems the incorrect thing to do here if you are loading both .mhd and .raw files as they are seperate formats, MetaImage vs Raw format where you do and don't know the image size, origin, spacing etc based on the absense or presense of a header.
How are you determining the size of the image and getting (0,0,0)? image->GetSize()?
Can you provide test data?
https://itk.org/Wiki/ITK/Examples/IO/ReadUnknownImageType
https://itk.org/ITKExamples/src/IO/ImageBase/RegisterIOFactories/Documentation.html


text:
Q: RPN Evaluator optimization without losing readability I'm implementing a program that needs a RPN calculator function, I've got the one bellow, but being new to python I wonder if I can optimize it without losing the readability.
Found some solutions using dictionaries and so on, but I got lost in the 'pythonesque' parts, the lists are still somewhat of a mistery to me...
my function is :
def parseRPN(expression):
    """Parses and calculates the result fo an RPN expression
        takes a list in the form of ['2','2','*']
        returns 4
    """
    try:
        stack = []
        for val in expression:
            if val in ['-', '+', '*', '/']:
                op1 = stack.pop()
                op2 = stack.pop()
                if val=='-': result = op2 - op1
                if val=='+': result = op2 + op1
                if val=='*': result = op2 * op1
                if val=='/':
                  if op1==0:
                      result=1
                  else:
                      result = op2 / op1
                stack.append(result)
            elif val in ['sin','cos']:
                op1 =stack.pop()
                if val=='sin': result = sin(op1)
                if val == 'cos': result = cos(op1)
                stack.append(result)
            else:
                stack.append(float(val))
        return stack.pop()
    except:
        print('error parse RPN fn:parse_rpn :' + str(expression))
        return 10*10**10

Thanks in advance

A: The original implementation is fine, and clear.  Here's another that uses  more Pythonic features:

*

*tests using py.test (<3)

*parse errors are left alone, as they already indicate what's going on

*the operator module is used directly for many two-argument functions, like multiply

*likewise, single-argument math functions like sin/cos just call the math library

*for convenience, the expression can be specified as a single string, like "2 3 /"
Calculators are a lot of fun, and are a great introduction to cool topics like compiling and parsing. Have fun!
RPN calculator
import math
import operator

import pytest

ERROR_VALUE = -1.

def safe_divide(darg1, darg2):
    try:
        return darg1/darg2
    except ZeroDivisionError:
        return ERROR_VALUE

def parseRPN(expression):
    """Parses and calculates the result of a RPN expression
        takes a list in the form of ['2','2','*']
        returns 4
    """
    # allow simple string: "2 3 /"
    if isinstance(expression, basestring):
        expression = expression.split()

    function_twoargs = {
    '*': operator.mul,
    '/': safe_divide,
    '+': operator.add,
    '-': operator.sub,
    }
    function_onearg = {
    'sin': math.sin,
    'cos': math.cos,
    }
    stack = []
    for val in expression:
        result = None
        if val in function_twoargs:
            arg2 = stack.pop()
            arg1 = stack.pop()
            result = function_twoargs[val](arg1, arg2)
        elif val in function_onearg:
            arg = stack.pop()
            result = function_onearg[val](arg)
        else:
            result = float(val)
        stack.append(result)
    return stack.pop()

def test_happy_paths():
    assert parseRPN([2, 3, '*']) == 6.
    assert parseRPN('0 sin') == 0.
    assert parseRPN([2, 3, '/']) == 2./3

def test_safe_divide():
    assert parseRPN([2, 0, '/']) == ERROR_VALUE

def test_parse_error():
    with pytest.raises(ValueError) as excinfo:
        parseRPN('gin')
    assert str(excinfo.value) == 'could not convert string to float: gin'

A: This is my version:
import operator
import math

_add, _sub, _mul = operator.add, operator.sub, operator.mul
_truediv, _pow, _sqrt = operator.truediv, operator.pow, math.sqrt
_sin, _cos, _tan, _radians = math.sin, math.cos, math.tan, math.radians
_asin, _acos, _atan = math.asin, math.acos, math.atan
_degrees, _log, _log10 = math.degrees, math.log, math.log10
_e, _pi = math.e, math.pi
_ops = {'+': (2, _add), '-': (2, _sub), '*': (2, _mul), '/': (2, _truediv),
        '**': (2, _pow), 'sin': (1, _sin), 'cos': (1, _cos), 'tan': (1, _tan),
        'asin': (1, _asin), 'acos': (1, _acos), 'atan': (1, _atan),
        'sqrt': (1, _sqrt), 'rad': (1, _radians), 'deg': (1, _degrees),
        'ln': (1, _log), 'log': (1, _log10)}
_okeys = tuple(_ops.keys())
_consts = {'e': _e, 'pi': _pi}
_ckeys = tuple(_consts.keys())

def postfix(expression):
    """
    Evaluate a postfix expression.

    Arguments:
        expression: The expression to evaluate. Should be a string or a
                    sequence of strings. In a string numbers and operators
                    should be separated by whitespace

    Returns:
        The result of the expression.
    """
    if isinstance(expression, str):
        expression = expression.split()
    stack = []
    for val in expression:
        if val in _okeys:
            n, op = _ops[val]
            if n > len(stack):
                raise ValueError('not enough data on the stack')
            args = stack[-n:]
            stack[-n:] = [op(*args)]
        elif val in _ckeys:
            stack.append(_consts[val])
        else:
            stack.append(float(val))
    return stack[-1]

In the first five lines after the imports I make local names for the operators and constants as an optimization so we don't have to do a module lookup every time we use one. Allowing constants like e and pi is an extra feature.
The ops dictionary is key to the working of the calculator.
It links the symbol of an operator to a tuple containing the number of arguments that the operator consumes and the function to call. Because of this data structure, operators do not have to be handled specially by their number of arguments.
Furthermore we save the keys for the _ops and _consts dicts in tuples, since we'll be using these a lot.
The line stack[-n:] = [op(*args)] is the heart of the calculator. It
contains two tricks. First it does argument unpacking using the * operator. Second it replaces multiple values on the stack with the result of op.
Intentionally, this function does not catch exceptions caused by errors in the input data.


text:
Q: How to clean Vimperator search highlights In Vimperator, press / and do a search. If there are matches, all will be highlighted.
My question is how to clean these highlights in a decent way.
My current approach is to press / again, and type in a random string like "abcdefgh", enter, and press Esc to clean the red warning in command window.

A: Type the following to quickly clear highlighted text

:noh

or you can toggle it highlight with

:set hls!

A: The :nohlsearch command will remove the search highlights.  You could map this to a key if you use it frequently.

A: Remaping is awesome and you should do it!
To add to the answers above:
You can remap some of the keys to handle this automatically for you.
e.g. put this to your ~/.vimperatorrc
" adjust search to enable highlight when searching and disable when escape is pressed
noremap n :set hlsearch<return>n
noremap <esc> :noh<return><esc>

Explanation:
noremap - remaps a key sequence without remaping keys.
n key to remap.
:set hlsearch<return>n function we want remap to perform in this case enable highlighting.
This will set highlight on when you click n (for the next search result) and turn it off when you click escape. You can also use / instead of n if you want highlight on when you start search instantly.


text:
Q: How to overwrite create method in Viewset to accept my custom serializer in DRF? I need to create a instance of my model, but in my request.data i don't have the correct information for my serializer.
class CotizacionViewSet(viewsets.ModelViewSet):
   serializer_class = CotizacionSerializer
   permission_classes = [IsAuthenticated]

        def create(self, request):
            serializer = self.serializer_class(data=request.data)
            if serializer.is_valid():
                serializer.save()
                return Response({'message': 'Cotizacion creada correctamente.'}, status=status.HTTP_201_CREATED)
            return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

and my serializer is
CotizacionSerializer(serializers.ModelSerializer):
    cliente = ClienteSerializer()
    curso = CursoCatalogoSerializer()

    class Meta:
        model = Cotizacion
        exclude = ('state', 'created_date', 'modified_date', 'deleted_date')

i want the information that gives me the serilizers from cliente and from curso but i don't know how to create a Cotizacion.

A: To create Cotizacion you can overwrite create method in the serializer.
class CotizacionSerializer(serializers.ModelSerializer):
    cliente = ClienteSerializer()
    curso = CursoCatalogoSerializer()

    class Meta:
        model = Cotizacion
        exclude = ('state', 'created_date', 'modified_date',
                  'deleted_date')

    def create(self, validated_data):
        cliente = validated_data.pop("cliente")
        curso = validated_data.pop("curso")

        # or you just get the data like
        # cliente = validated_data["cliente"]
        # then create Cotizacion
        cotizacion = Cotizacion.objects.create(**validated_data)

        return cotizacion

I am not sure about relation between Cotizacion and cliente/curso. However, you can perform the required operations in this method. I may be able help further if you could show us the models.


text:
Q: Error while inserting image in fckeditor I see the following error whenever I insert an image into the fckeditor. I am running on Rails 2.3.8 and using the easy_fckeditor plugin
Error This page can't be displayed. Contact support for additional
information. The incident ID is: 0.

A: You can check the permission setting of Rails root folder


text:
Q: Cakephp + Jquery : how to user jquery methods? My problem is really simple.
I've a lot of links like :
$this->Html->link(__('Calculer'), 'log_import/'.$suivi['Suivi']['date'], array('class' => 'logImport')

As you can see, the href attribute of my 'a' tag changes on every links (kind of dates like '2012-01-01', '2012-10-15', etc...)
When i click on my link, jquery code is executing :
$this->Js
    ->get('.logImport')
    ->event('click',
        $this->Js->request(
          array('action' => '$(this).attr("href")'),
          array('async' => true,
                'update' => '#test')
          ));

And i get an error because the URL used by the ajax request is :
/suivis/$(this).attr("href")

and not :
/suivis/log_import/2012-01-01

A: I don't think this will work :
array('action' => '$(this).attr("href")')

It seems the value is treated as a string.
My suggestion is to use raw jquery code:
$('.logImport',this.DOMDoc).each(
  function(index, object){

    var href = $(this).get(0).href;
    $(this).get(0).href = "javascript:void(0);"

    // attach click function for each link
    $(this).click(function() {

        // make request here
        $.ajax({
            type: "post",
            url: href,
            ...
        })

    });
  }
);

A: Yep, finally i used "pure" jquery code in the JS Helper buffer.
This is my code (you can directly use $(this).attr and bypass the each loop ;-)
$this->Js->buffer('
  $(".logImport").click(function(event) {
    event.preventDefault();
    $.ajax({
        url: $(this).attr("href"),
        })
        .done(function(){
          alert("OK");
          })
        .fail(function(){
          alert("FAILED");
          });

    });
');

By the way, i'm still interested in the answer if anybody knows....


text:
Q: Operand + for Number in Java If I have two Object implement Number Interface, is it possible to add them together?
public static <T extends Number> T[] prefixSum(T [] arr,T zero){
    int n = arr.length;
    T [] arr2 = (T[]) new Object [n+1];
    arr2[0] = zero;
    for (int i=0;i<n;i++){
        arr2[i+1] = arr[i] + arr2[i]; // ERROR
    }
    return arr2;
}

I got error message at line 6.
How can I write this program generically?

A: A few ground rules before we begin:

*

*Arrays and generics simply don't mix well.  You get into a lot of headaches about the ability to store data correctly inside of the array at runtime (i.e. ArrayStoreException), and a lot of raw types floating around (your compiler may have emitted a warning about the generic array creation you have up there).
For that reason, we're going to move to List.  It's generic and a lot more flexible.  If you really want, you can convert it back.

*Generics aren't really necessary here.  You've got an array of Numbers coming in, with a Number as your zero value.  Since any class that extends Number is-a Number, there's no harm in bringing them in.  Conversely, it would bring us much unnecessary headache to bring a generic type in.

*Thinking about it logically, the object hierarchy of Number is such that everything that could be considered a Number is capable of being Comparable as well (and luckily we don't need that).  But, considering this chart of number types, I don't see any reason to utilize generics.
]
Here's an example of how the code would look without generics, and only with Number.  Mind, this is only taking the intValue, so all of your numbers will be integer-precise.  If you want the float or double value, then that's possible too.
public static List<? extends Number> prefixSum(Number [] arr, Number zero){
    final List<Number> result = new ArrayList<Number>();
    result.add(zero);
    for(int i = 0; i < arr.length; i++) {
        final Number sum = arr[i].intValue() + result.get(i).intValue();
        result.add(sum);
    }
    return result;
}


text:
Q: PDO inserts Japanese characters wrong in to database Background
I'm currently writing a small web application for myself to test my Japanese. It consists of getting to see a Japanese word, and then giving the correct translation in Dutch. I have a small set-up where I can specify a Japanese word with the Dutch translation, and it will get inserted in the database.
Problem

When inserting certain Japanese characters, such as "お" (or "O" for those wondering) it gets inserted in the database as "ず" (or "Zu"). There are more characters which also get transformed, but I forgot which (I cleared the database to see if certain solutions worked).
What have I tried
I've made sure that all the things I think need to be UTF-8 are set to UTF-8. I've set the following to UTF-8:

*

*HTML page header: <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

*PHP header (very first line): header('Content-Type: text/html; charset=utf-8');

*The MySQL table japanese_words:  ALTER TABLE japanese_words CONVERT TO CHARACTER SET utf8;

*PDO encoding:
$db = new PDO('mysql:host=localhost;dbname=japanese;charset=utf8', '****', '****');
And tried:
$db->exec("set names utf8");
Specifying the Japanese word works in PHP. I can dump, and regularly show, the Japanese words in my webpage. This means my HTML and PHP are set up correctly. So there are no errors before inserting it in the database.
When I insert the Japanese words manually in the database it works.
The characters get "transformed" when I try to insert it in to the database using PDO.
Trying to show the query PDO generates doesn't work. I get the query with the bound parameter and not the actual word.
Code
add_word.php (this all works fine):

$japanese_word = $_POST['japanese_word'];
$dutch_word = $_POST['dutch_word'];

$word = new Word();
$word->setDutchWord($dutch_word);
$word->setJapaneseWord($japanese_word);

$wordDAO = new WordDAO($db);
$success = $wordDAO->addWord($word);

WordDAO method, where I think the problem is (or somewhere between there and the actual MySQL database):
$query = "insert into `japanese_words` (`word`) values(:word)";
$stmt = $this->db->prepare($query);
$stmt->bindParam(':word', strtolower($word->getJapaneseWord()));
$stmt->execute();
$japanese_word_id = $this->db->lastInsertId();

Question
What am I doing wrong here? Did I forget to set up more encodings, or specify a particular PDO setting? Any help is appreciated.

A: The problem is I was using strtolower() in my bindParam. This changed the values of the Japanese words. Changing the code to the following worked:
$query = "insert into `japanese_words` (`word`) values(:word)";
$stmt = $this->db->prepare($query);
$stmt->bindParam(':word', $word->getJapaneseWord());
$stmt->execute();
$japanese_word_id = $this->db->lastInsertId();

Damn my blatant copy/pasting (of course I found out as soon as I posted the question).

A: PDO
mb_internal_encoding('UTF-8');

$dbh = new PDO("mysql:host=localhost;dbname=japanese;charset=utf8");
$dbh->exec("set names utf8");

$query = "insert into `japanese_words` (`word`) values(:word)";
$stmt = $this->db->prepare($query);

// use mb_* function for japanese string
$stmt->bindParam(':word', mb_strtolower($word->getJapaneseWord()));

$stmt->execute();

$japanese_word_id = $this->db->lastInsertId();

Change Charset and Collation of a Database and Table
ALTER DATABASE japanese CHARACTER SET utf8 COLLATE utf8_general_ci;
ALTER TABLE japanese_words CONVERT TO CHARACTER SET utf8 COLLATE utf8_general_ci;

Set the charset of your page
<?php
ini_set("default_charset", "UTF-8");
header('Content-type: text/html; charset=UTF-8');
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
...

You may have to check that your files are saved with the right charset!


text:
Q: Not able to produce JSON from SQL for Master/Detail tables Following is the query:
SELECT  [C].[Id],
        [C].[Name],
        [Module].[Id],
        [Module].[Name]
FROM [dbo].[Category] [C]
INNER JOIN [CategoryModule] [CM]
 ON [C].[Id] = [CM].[CategoryId]
CROSS APPLY (SELECT [M].[Id], [M].[Name] FROM [Module] [M]
 WHERE [M].[Id] = [CM].[ModuleId]) [Module]
 WHERE [C].[Id]IN (1,2)
 FOR JSON AUTO

Output:
[
  {"Id":1,"Name":"Book","Module":[{"Id":1,"Name":"Unit"}]},
  {"Id":2,"Name":"Business","Module":[{"Id":1,"Name":"Unit"}]},
  {"Id":1,"Name":"Book","Module":[{"Id":2,"Name":"App"}]}
]

Need:
[
  {"Id":1,"Name":"Book","Module":[{"Id":1,"Name":"Unit"},{"Id":2,"Name":"App"}]},
  {"Id":2,"Name":"Business","Module":[{"Id":1,"Name":"Unit"}]}
]

It generate separate object for same master table entry.

A: Hi i think it's possible use FOR JSON AUTO, OPENJSON and JSON_MODIFY
I had the same problem but i finally find a solution
In your case try this
SELECT
JSON_MODIFY (
    (SELECT value FROM  OPENJSON((SELECT * FROM Category  WHERE Id = C.Id FOR JSON AUTO),'$')),
    '$.Module',
    (SELECT M.Id, M.Name FROM CategoryModule CM INNER JOIN Module M ON CM.ModuleId= M.Id WHERE CM.CategoryId= C.Id FOR JSON AUTO)
) AS Category
FROM Category C
FOR JSON AUTO

The Ouput is
[{
    "Category": {
        "Id": 1,
        "Name": "Book",
        "Module": [{
            "Id": 1,
            "Name": "Unit"
        }, {
            "Id": 2,
            "Name": "App"
        }]
    }
}, {
    "Category": {
        "Id": 2,
        "Name": "Business",
        "Module": [{
            "Id": 1,
            "Name": "Unit"
        }]
    }
}]