Q:

Accessing View function from internal functions in Ember

One of the views in my ember app has the following structure
export default Ember.View.extend({
    didInsertElement: function() {
        window.onload = function() {
            chrome.gcm.onMessage.addListener(function(message) {
                receiveGCM(message);
            });
        }
    },
    receiveGCM: function(message){
        console.log(message);
        //type check here
        //Then call necessary data insertion module
        //Or call the notification module
    }
});

This is throwing an error Error in event handler for gcm.onMessage: ReferenceError: receiveGCM is not defined
Calling receiveGCM(message) with the this object doesn't solve the problem. Wrong this object gets referred. I tried using bind(this). But that doesn't help.
How do I call receiveGCM() from the chrome listener method?

A:

Recursive binding of this object solves the problem.
window.onload = function() {
            chrome.gcm.onMessage.addListener(function(message) {
                this.receiveGCM(message);
            }.bind(this));
        }.bind(this)

But this restricts the usage of chrome's this object inside the listener. As long it's not used, this solution will work.


Q:

c++ if else statement won't go right pathway for text adventure game, always goes to the same Void Function

I have c++ issues.
On a text adventure game I am making, and on a part where I have choices for different options on what to do in a house, every choice I make always goes to the void Sleep() function:
void Home()
{
    cout << "\nYou are in the living room of your rented home. Everything looks nice and tidy." << endl;
    cout << "Choices:" << endl;
    cout << "Sleep" << endl;
    cout << "Leave" << endl;
    cout << "Stats" << endl;
    cin >> choice;

    if (choice == "Sleep" || "sleep")
    {
        Sleep(); // No matter what choice I make, it always
        //goes to the Sleep(); void.
    }
    if (choice == "Leave" || choice == "leave"){
        TownSquare();
    } if (choice == "Stats" || choice == "stats") {
        StatsH();
    }
    else {
        cout << "Please choose correctly!" << endl;
        Home();
    }
}

All help will be much appreciated. Thank you!

A:

Your line:
if (choice == "Sleep" || "sleep")

Evaluates as:
if ((choice == "Sleep") || "sleep")

Which is always true since "sleep" will always trigger. You may want to make a proper look-up table here and force the input as lower-case if that's a concern.


Q:

How to troubleshoot custom Keras layers

I'm creating a model using Keras (I'm a beginner) and wrote a lambda function to randomly choose whether or not to flip the initial input layer.
This is the snippet that attempts to do so:
input_global = Input(shape=(2001,1))
flipped = Lambda(lambda x: keras.backend.reverse(x, axes=1) if np.random.random() < 0.5 else x, output_shape=(input_global.shape[1], input_global.shape[2]))(input_global)

My model compiles, yet logging messages like print("Hello, world") in the middle of the definition of the model only result in "Hello world" being logged once- not every time data goes into the model during training.
How do I know that my function did what I intended it to do?

A:

When building a Keras model, you are building a graph of operations, and whenever you run input through your model, you are running your input through that graph of operations. In other words, you build a model once, and then you can run input through it as many times as you'd like.
Non-Keras functions will not be part of the graph, including operations like print or np.random.random(). You will need to use the Keras equivalents.
For print, use the function keras.backend.print_tensor.
For np.random.random, use the function keras.backend.random_uniform.
I think you did not intend to do this, but because you are using np.random.random() in your custom layer, that operation will be executed only when you build the model. It will not be run whenever you run data through your model. In other words, the layer will either only reverse the inputs, or it will only return the inputs. To get the random behavior I think you want, you need to use a Keras function (i.e., keras.backend.random_uniform). Using that Keras function will generate a random number every time you run your model.
To belabor the point, np.random.random() will be run once when you build the model, and in essence it will determine at build time what that layer will do (i.e., it will either only reverse the input, or it will only return the input unchanged). keras.backend.random_uniform(), on the other hand, will not generate a random number when you build the model, but instead it adds a random_uniform operation to the model, so every time data goes through the model, a random number will be drawn from a uniform distribution at that point.


Q:

VirtualBox - Two guests can't ping each other

I've selected bridged adapter option in virtualbox. I am able to ping from Machine 1 (WinXP) to Machine 2(Linux) and get a response, but I am not able to ping vice versa. I need to connect from Machine 2 to Machine 1. What should I do? Thanks.

A:

Enable ICMP echo requests on the Windows machine by doing the following: https://readme.phys.ethz.ch/windows/how_to_enable_icmp_echo_requests_ping_in_windows_xp_service_pack_2/


Q:

How to partition table in blocks when value change into one colum in TSQL?

The following query,
declare @data as TABLE (one int, two int);
insert into @data (one, two) values (1,1)
insert into @data (one, two) values (2,1)
insert into @data (one, two) values (3,2)
insert into @data (one, two) values (4,2)
insert into @data (one, two) values (5,2)
insert into @data (one, two) values (6,1)
insert into @data (one, two) values (7,1)
insert into @data (one, two) values (8,3)
insert into @data (one, two) values (9,3)
select  one, two,
dense_rank() OVER (ORDER BY two ASC) AS BlockNumber --Same dates same number
from @data
order by one

with results,
one two BlockNumber
1   1   1
2   1   1
3   2   2
4   2   2
5   2   2
6   1   1
7   1   1
8   3   3
9   3   3

I would however like the following result,
one two BlockNumber
1   1   1
2   1   1
3   2   2
4   2   2
5   2   2
6   1   3**
7   1   3**
8   3   4**
9   3   4**

Any suggestions?

A:

I can't think of a way to do it with the analytic functions from before SQL 2012 - there may be some Laggy goodness but I'm not that comfortable with those functions yet.
So, if the priority is the result set rather than how it's produced, I'd use:
;With Blocks as (
    select d1.one,d1.two,ROW_NUMBER() OVER (ORDER BY d1.one) as BlockNumber
    from @data d1
        left join
        @data d2
            on
                d1.two = d2.two and
                d1.one = d2.one + 1
    where d2.one is null
    union all
    select d.one,d.two,b.BlockNumber
    from
        @data d
            inner join
        Blocks b
            on
                d.two = b.two and
                d.one = b.one + 1
) select * from Blocks
order by one

The CTE first finds every row which differs from the previous row by its two value. We then keep adding any rows which immediately succeed already identified rows and have the same two value and assign them the same Block number.


Q:

Check if device has hardware volume controls?

Some devices like Kindle fire do not have hardware buttons for volume, so I was going to add some on screen controls, but I don't want to have them there if they are not necessary.
I can't find any info on this, I've looked in PackageManager features, plus Configuration.
Is it true maybe that all devices have hardware volume controls with exception of kindle fires?

A:

android.view.KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_VOLUME_UP)


Q:

Reducibility of the polynomial $x^4+1$

Show that  $x^4+1$ is reducible in $\mathbb{Q}(\sqrt2)$ and $\mathbb{Q}(\sqrt2 \,i)$ .Is true that  $x^{2n} +1 , n\ge3$ is reducible in $\mathbb{Q}(\sqrt2)$ and $\mathbb{Q}(\sqrt2\,i)$?
Is this correct to show that $x^4+1$ is reducible in $\mathbb{Q}(\sqrt2)$? Is there another way to show that?
$$x^4+1=(x^2+1)^2-2x^2=(x^2+\sqrt2x+1)(x^2-\sqrt2x+1)$$
Is this correct to show that $x^4+1$ is reducible in $\mathbb{Q}(\sqrt2\,i)$? Is there another way to show that?
$$x^4+1=(x^2-1)^2-(\sqrt2\,ix)^2=(x^2+\sqrt2\,ix-1)(x^2-\sqrt2\,ix-1)$$
How can I prove that  $x^{2n} +1 , n\ge3$ is reducible in $\mathbb{Q}(\sqrt2)$ and $\mathbb{Q}(\sqrt2\,i)$?

A:

Yes, a polynomial is reducible if it is divisible by a non-constant polynomial of lesser degree... by factoring the polynomial, you have shown just that.
For the second question, notice that $x^{2n}+1$ factors into integer polynomial factors when $n$ is odd:
$$x^{2n}+1 = (x^2+1)(x^{2n-2}-x^{2n-4}+\ldots - x^2 + 1).$$
When $n$ is even, try slight modifications of your argument for $x^4+1$.


Q:

asymmetric random walk, hitting time probability

Let's consider an asymmetric Random Walk on $Z$, with transition probabilities $p_{i, i+1}=p$, $~~p_{i, i+1}=q$, $\forall i \in \mathcal{Z}$, $p+q=1$ and $p>q$.
I am interested in the probability of the first hitting time of a bareer in $i=n$, assuming that the walk started from $i=0$ at time $t=0$. Is there an explicit formula for it? How does it depend on $n$?

A:

The explicit formula is: $P[N_m=n]=(m/n)P[S_n=m]$, where $P[N_m=n]$ is the
probability the position $m$ is hit after exactly $n$ steps,
$S_n = X_1+X_2+\dots X_n$ and $P[S_n=m]$ is the probablity after $n$ steps
the path to be at the position $m$. This last is well-known and is given
by
$$P[S_n=m]=\frac{n!}{[(n+m)/2]![(n-m)/2]!}p^{(n+m)/2}q^{(n-m)/2}.$$
This is true when $n$ and $m$ have the same parity, else the probability
is zero. Additionally $m$ is positive and $n$ is greater than or equal to $m$.
A similar expression can be found for negative $m$.


Q:

Деепричастный оборот и придаточное времени при СГС

1.1. Полностью освоив текущее направление, мы планируем развивать новое.

Смысл «мы уже освоили и сейчас планируем» или «мы планируем развивать тогда, когда освоим»?
Если поставить оборот перед инфинитивом, вроде бы можно добиться однозначного второго смысла:

1.2. Мы планируем, полностью освоив текущее направление, развивать новое.

За счёт такой позиции деепричастный оборот по смыслу больше примыкает к инфинитиву, и то, что развитие нового направления будет производиться только после освоения текущего, уже становится как бы частью объекта планирования.
Если переставить оборот в конец предложения, то также возможны оба смысла:

1.3. Мы планируем развивать новое направление, полностью освоив текущее.

——————————————————
Аналогичный пример с деепричастием несовершенного вида:

2.1. Работая в солидной компании, я хочу купить квартиру в центре Москвы.

Та же самая неоднозначность: «работая, хочу» или «хочу купить тогда, когда буду работать»?

2.2. Я хочу, работая в солидной компании, купить квартиру в центре Москвы.

Во этом варианте также усиливается связь деепричастного оборота с инфинитивом, и то, что покупка квартиры будет производиться только во время работы в солидной компании, становится частью объекта желания.
Однако если сменить лицо глагола с первого на второе, то почему‑то опять можно понять двояко:

2.3. Вы хотите, работая в солидной компании, купить квартиру в центре Москвы.

То ли «вы уже работаете и хотите купить», то ли «вы хотите купить, но только тогда, когда будете работать».
Последний же вариант в данном случае несуразен:

2.4. Я хочу купить квартиру в центре Москвы, работая в солидной компании.

После того как высказана основная мысль — «я хочу купить квартиру в центре Москвы», указание на приуроченность к времени работы в солидной компании кажется лишним.
Хотелось бы получить точный ответ — какие факторы (позиция деепричастного оборота, его вид, время вспомогательного глагола в составном глагольном сказуемом) определяют, относится ли деепричастный оборот ко всему СГС или только к инфинитиву.
Пока я понял только одно: позиция деепричастного оборота в предложении с СГС явно влияет на его семантику.
Хорошим решением для ликвидации двусмысленности становится замена деепричастного оборота на придаточное времени:

3.1. Мы планируем развивать новое направление, когда полностью освоим текущее.

Разное время вспомогательного глагола в главном и глагола в придаточном не даёт их соотнести.
Однако в учебниках написано, что придаточные времени относятся ко всему главному предложению, а здесь придаточное относится лишь к части СГС — инфинитиву. В учебниках неточность?
К слову, двусмысленность снова возникает, если поставить вспомогательный глагол в будущее время:

3.2. Совет директоров наверняка запланирует развивать новое направление, когда текущее будет полностью освоено.

«Запланирует тогда, когда текущее направление будет полностью освоено» или «запланирует в некоторый момент в будущем, но развивать будут тогда, когда текущее направление будет полностью освоено»?
Как поступать в таком случае?
———————————
Похожие вопросы:
Деепричастный оборот при составном глагольном сказуемом‑сказуемом
Позиция обстоятельства при СГС (переформулирован)

A:

Я не отвечаю Вам конкретно (и уж тем более не даю точный ответ), но хочу поделиться своим впечатлением от Ваших вопросов. Я надеюсь, что эта информация может оказаться  для Вас полезной. Если что-то Вам не понравится в моем ответе, то я заранее прошу извинить меня, так как всё говорится с самыми добрыми чувствами и намерениями.
Когда я читаю Ваши вопросы, то мне кажется, что я общаюсь с искусственным интеллектом (в положительном смысле). В чем-то такой интеллект превосходит человеческий разум, но при этом он может испытывать трудности при понимании вполне обычных вещей, в частности это касается языка.
1) Вы обращаетесь с синтаксисом, как с механическим конструктором, считая, что можно комбинировать структурные элементы в любом порядке, но это не так.  В настоящее время изучение грамматики подводит нас к такому пониманию речи, когда  грамматическая форма и семантика изучаются совместно  (так называемое семантическое согласование).
Что это означает?   К примеру, согласно структурным схемам, деепричастный оборот может занимать любую позицию (в начале, в конце и в середине предложения). Но каждый вариант должен быть соотнесен с коммуникативной ситуацией.
Вот как это может выглядеть в вашем случае (например, в виде ответов на вопросы).
– Каковы ваши планы на будущее?  – Наша компания не стоит на месте. Полностью освоив текущее направление, мы планируем развивать новое.
– Это направление в технике возникло недавно, вы планирует его развитие? – Пока у нас нет таких возможностей. Заниматься чем-то новым мы сможем, полностью освоив текущее направление (если/когда освоим…).
2) Рассмотрим теперь временной  аспект этой темы. Если планировать – модальный глагол (связка в СГС), то в словаре он помечен следующим образом: 4. Разг. Иметь намерение сделать что-л.
Глагол планировать относится к настоящему моменту речи, а соотнесенность во времени рассматривается между действиями, выраженными  инфинитивом СГС и деепричастием, поэтому модальный глагол в этих временных рамках вообще, как мне кажется, не участвует.
Но и  тут при определении времени действия  всё не так просто. Если почитать грамматику Розенталя, то можно кое-что  узнать на эту тему.  Что именно? Классическое правило об одновременности действий для деепричастия несовершенного вида и смещения по времени для деепричастия совершенного вида всем известно. Но вот что интересно:  правило соотношения времен перестает действовать, если оборот  приравнивается к обстоятельственному придаточному, например, называет условие действия (если закончим текущее направление).
3)   И позиция деепричастного оборота  (в частности, совершенного вида) очень важна: в препозиции оборот обычно выражает предшествующее действие, а последующее  или одновременное действие встречается значительно реже, при этом оборот находится в постпозиции. Если рассматривать придаточные предложения, там также позиция очень важна и влияет на семантику (это особая тема).
4) Таким образом, множество этих нюансов всегда учитывается при общении, определяет нужный смысл и избавляет говорящих от угадывания возможных вариантов.  Двусмысленность воспринимается как недостаток в построении текста. Кроме того, ситуация обычно тоже подсказывает, что имеет в виду ваш собеседник.
5) Учитывая всё это, можно понять, почему Ваши вопросы обычными пользователями не воспринимаются как актуальные – для них таких проблем просто не существуют, если человек знаком с  основными грамматическими правилами.  Причем часто всё это происходит на интуитивном уровне, то есть очень важен  практический навык грамотной речи. Но если нужно совершенствовать свои знания, то лучше начинать не с «логических игр», а с подробного изучения грамматики.


Q:

Why did Joseph's brothers immediately leap to explaining Joseph's demands in the way they do?

Genesis 42:18-21 (NIV):

On the third day, Joseph said to them, “Do this and you will live, for I fear God: If you are honest men, let one of your brothers stay here in prison, while the rest of you go and take grain back for your starving households. But you must bring your youngest brother to me, so that your words may be verified and that you may not die.” This they proceeded to do.
They said to one another, “Surely we are being punished because of our brother. We saw how distressed he was when he pleaded with us for his life, but we would not listen; that’s why this distress has come on us.”

Why did they immediately jump to that conclusion? Was it because they saw Joseph and he reminded them of his younger self (so they were thinking about it anyway), or did they just feel guilty "in general"?

A:

We are not told the answer to this question but having had personal experience as a result my own stupidity, let me suggest that after 22 years of guilt over their deception and presumed indirect murder of Joseph, it does not take much to trigger personal recriminations and extreme remorse such as we see here.  [I also suspect that some other bad events might have triggered similar thoughts as well.]
Guilt is a very powerful emotion which is why the NT goes to such lengths to deal with it by way of complete forgiveness of sin (Matt 9:2, 5, 6, 12:31, 32, 26:28, Mark 14:24, Acts 8:22, Rom 4:7, James 5:12, 1 John 1:9, 2:12, etc).  See Rom 3:23-27.


Q:

Understanding why $a+b\sqrt {2}\neq \sqrt {3} $

I want to intuitively understand why $a+b\sqrt {2}\neq \sqrt {3} $ for $a, b \in \mathbb Q $
I really have no intuition regarding this matter, and have to deal with similar concepts regularly while studying field extensions.
Please do not give algebraic proofs like the squaring of both sides and arriving upon a contradiction. I'm looking for something that involves logic/geometry/anything else that would hone my intuition in such matters.

A:

$\sqrt2$ is just an arbitrary number that, when squared, produces $2$. Similarly for $\sqrt 3$. That is, although we define them as the positive roots, there is no algebraic distingtion between the positive and the negative root. Thus for any rational numbers $a,b$ for which $a+b\sqrt 2$ is "a" root of $3$, we should expect that also $a-b\sqrt 2$ (i.e., playing with "the other" root of $2$) gives "a" root ot $3$. It could be the same root of $3$, but then we conclude  $a=\sqrt 3$ by adding the equations. Or it could be the "other" root, but then we conclude $b\sqrt 2=\sqrt 3$ by subtracting the equations (and then $2b=\sqrt 6$).  Now dig out your favorite proof that $\sqrt 3$ and $\sqrt 6$ are irrational and you are done.

Alternatively, with "hidden" squaring:
Assume $a+b\sqrt 2=\sqrt 3$.
Then $$ a-b\sqrt 2=\frac{a^2-2b^2}{a+b\sqrt 2}=\frac{a^2-2b^2}{3}\sqrt 3$$
Hence
$$2a=\left(\frac{a^2-2b^2}3+1\right)\sqrt 3 $$
and by irrationality of $\sqrt 3$, this requires $a=0$ and then $2b^2=3$, which fails because $\sqrt 6$ is irrational.


Q:

Lists with MarkerStyle = Disc in a WPF-FlowDocument

I'm trying to display a fiew lists in a FlowDocument. I Realized that when using
MarkerStyle = TextMarkerStyle.Disc, the list gets less indentation then with the others. Im looking for a way to display lists with Disc-Markers but the same indentation as the other markers get, any hints?
Heres a snippet that shows my problem :
        List l = new List();
        l.MarkerStyle = TextMarkerStyle.Disc;
        l.ListItems.Add(new ListItem(new Paragraph(new Run("cxyc"))));
        l.ListItems.Add(new ListItem(new Paragraph(new Run("asdasd"))));
        l.ListItems.Add(new ListItem(new Paragraph(new Run("ghjtd"))));
        richTextBox.Document.Blocks.Add(l);

        l = new List();
        l.MarkerStyle = TextMarkerStyle.Decimal;
        l.ListItems.Add(new ListItem(new Paragraph(new Run("$!"))));
        l.ListItems.Add(new ListItem(new Paragraph(new Run("&!§"))));
        l.ListItems.Add(new ListItem(new Paragraph(new Run("&!"))));
        richTextBox.Document.Blocks.Add(l);

        l = new List();
        l.MarkerStyle = TextMarkerStyle.LowerLatin;
        l.ListItems.Add(new ListItem(new Paragraph(new Run("16123"))));
        l.ListItems.Add(new ListItem(new Paragraph(new Run("gasd"))));
        l.ListItems.Add(new ListItem(new Paragraph(new Run("612312"))));
        richTextBox.Document.Blocks.Add(l);

        l = new List();
        l.MarkerStyle = TextMarkerStyle.None;
        l.ListItems.Add(new ListItem(new Paragraph(new Run("15123"))));
        l.ListItems.Add(new ListItem(new Paragraph(new Run("fasdas"))));
        l.ListItems.Add(new ListItem(new Paragraph(new Run("5161234"))));
        richTextBox.Document.Blocks.Add(l);

A:

Set the Padding on the List to have an explicit left padding.  The default is Auto (NaN) for all four directions, and List will set the left padding based on the MarkerStyle when it is Auto.
l.Padding = new Thickness(20, double.NaN, double.NaN, double.NaN);


Q:

Is it possible to write a single named access function for both, constant reference and writeable reference of elements of a tuple?

I've got some hierarchy of std::tuple.
I would like to write some access functions for all these tuples so that the resulting code is more readable.
So instead of writing:
std::get<2>(std::get<1>(std::get<0>(s)))

I would rather prefer to write
getNetName(getFirstNet(getFirstOutput(s)))

Now the point is to avoid writing these access functions twice -- for constant parameters and for writeable parameters.
Can this be done?
And of course -- I want these access functions to be type-safe. There might be multiple tuples types to which std::get<0>() can be applied -- but I would rather prefer that getNetName() creates a compiler error if it is not applied to a net.

A:

std::get already does exactly what you want, so your goal is to simply write an alias for an existing function. The trick is to perfect forward your argument and return value to ensure nothing is lost. For example :
#include <tuple>

template<class T>
decltype(auto) getFirstElem(T&& p_tuple)
{
    return std::get<0>(std::forward<T>(p_tuple));
}

int main()
{
    std::tuple<int, int> mutable_x = { 42, 24 };
    const std::tuple<int, int> const_x = { 10, 20 };

    // mutable_ref is a `int&`
    auto&& mutable_ref = getFirstElem(mutable_x);

    // const_ref is a `const int&`
    auto&& const_ref = getFirstElem(const_x);
}

decltype(auto) ensure that the return value is perfect forwarded. This preserves the reference qualifier and the constness of the return type. Using auto would cause the return value to decay to the underlying value type (in this case int). auto&& is similarly used to capture the result without discarding reference qualifier or constness.
Edit : It seems there was a type safety component to the question I missed. This is easily fixed by introducing a static_assert and std::is_same to compare the argument type with the expected type. It's important to remove reference qualifiers and cv modifiers to ensure the comparison is correct.
template<class T>
decltype(auto) getFirstElem(T&& p_tuple)
{
    using t_expected = std::tuple<int, int>;

    // Verify that the tuple matches the expectations
    using t_tuple_clean = std::remove_cv_t<std::remove_reference_t<T>>;
    static_assert(std::is_same<t_expected, t_tuple_clean>::value, "Unexpected tuple type");

    return std::get<0>(std::forward<T>(p_tuple));
}

Unfortunately, the error message will usually be pretty long. Unfortunately I don't see a way to write this where the compiler's built-in argument matching could be used (which would generate clearer error messages). Perfect forwarding requires that the argument be a template type. Otherwise, you would need two overloads (one for const and one for non-const arguments) which would violate the single-function requirement of the question.
If you find it annoying to write out the check for every function, you can write a helper which can be used to more easily write new access functions.
#include <tuple>
#include <type_traits>

template<size_t index, class t_expected, class t_tuple>
decltype(auto) getHelper(t_tuple&& p_tuple)
{
    // Verify that the tuple matches the expectations
    using t_tuple_clean = std::remove_cv_t<std::remove_reference_t<t_tuple>>;
    static_assert(std::is_same<t_expected, t_tuple_clean>::value, "Unexpected tuple type");

    // Forward to std::get
    return std::get<index>(std::forward<t_tuple>(p_tuple));
}

template<class T>
decltype(auto) getFirstElem(T&& p_tuple)
{
    return getHelper<0, std::tuple<int, int>>(std::forward<T>(p_tuple));
}

The access function will now fail with a compiler error if the wrong type of tuple is provided :
int main()
{
    // Compiler error 'Unexpected tuple type'
    std::tuple<double, int> bad_tuple{};
    auto&& bad_ref = getFirstElem(bad_tuple);
}

A:

sorry this is C++11 (complain to my boss)!
template<typename T, std::size_t I>
struct get
{       auto operator()(T &_r) const -> decltype(std::get<I>(_r))
        {       return std::get<I>(_r);
        }
        auto operator()(const T &_r) const -> decltype(std::get<I>(_r))
        {       return std::get<I>(_r);
        }
};

and application:
typedef std::pair<
    std::size_t, // starting value
    std::size_t // size or ending value?
> dimension;
typedef get<dimension, 0> getDimensionStart;
typedef get<dimension, 1> getDimensionSize;
typedef std::pair<
    std::string,
    boost::optional<dimension>      // if scalar, then this is empty
> port;
typedef get<port, 0> getPortName;
typedef get<port, 1> getPortDimension;

using this code would look like this:
const port s("name", dimension(0, 10));
std::cout << getDimensionStart()(*getPortDimension()(s)) << std::endl;


Q:

Disccord.js message.content.includes creates an infinte loop

bot.on('message', async message => {
    if(message.content.includes('stuff')) {
        message.channel.send("*stuff*");
    }
}

So if someone says something with stuff on my server, the bot will infinitely message the chat with
"repeat." I literally have no idea why this is happening.

A:

As other commenters have mentioned, you're creating an infinite loop because you're checking your own bot's message too, which sends the same thing you're checking for. Ignoring the bot client or just all bots in general will work:
bot.on('message', async message => {
    // To ignore your own client:
    if (message.author.id === bot.user.id) {
        return;
    }

    // To ignore all bots (including your own):
    if (message.author.bot) {
        return;
    }

    if(message.content.includes('stuff')) {
        message.channel.send("*stuff*");
    }
}


Q:

Java 6 Collections.checkedList appropriate usage

I am creating several functions in which I want to return the interface instead of the implementation, I.E. List instead of ArrayList .  My method signature and a brief implementation follows:
public List<MyAwesomeComposedObject> convert(Collection<MyAwesomeObject> awesomeObjects>)
{
    List<MyAwesomeComposedObject> composedObjects = new ArrayList<MyAwesomeComposedObject>();
    for(MyAwesomeObject awesomeObject : awesomeObjects)
    {
        MyAwesomeComposedObject composedObject = new MyAwesomeComposedObject(awesomeObject);
        composedObjects.add(composedObject);
    }

    List<MyAwesomeComposedObject> composedObjectList = Collections.checkedList<composedObjects, MyAwesomeComposedObject.class);
    return composedObjectList;
}

My question is, is this an antipattern of some sort?  I want to guarantee that the invoker of this method is getting the interface instead of an implementation.  I also do not believe this to be a case of overengineering.  If this is not the correct way to return an interface, in this scenario I am open to the correct implementation.
Attached is a small program that results in an exception:
public static void main(String[] args)
{
    Vector v = (Vector) c();
}

static List<Object> c()
{
    List<Object> l = new ArrayList<Object>();
    l.add(new Object());
    List<Object> o = Collections.checkedList(l, Object.class);
    return o;
}

The javadoc is here: checked list

A:

For your revised question: There is no way to prevent the caller from attempting to cast to whatever they want. If it is an inappropriate cast they will get the exception. This is the very reason why casting from an interface to a concrete class is strongly discouraged.
If you are really worried about this, consider returning an ArrayList instead of a List. That should discourage casting since they are getting a concrete type. Please note that I do not endorse this, it is just an option.

I want to guarantee that the invoker of this method is getting the interface instead of an implementation

This is not valid. You are returning a List where the declared type of the elements is an interface, however each element must be SOME instantiation. All a checked collection does is prevent the addition of elements of the incorrect type. There is nothing that prevents the user from casting back to the implementation type.
If you are attempting to ensure that the user gets List instead of ArrayList (my assumption here because I don't see an interface for you Awesome class), this again is flawed because the user could still cast the List to an ArrayList although this would be a bad idea since it risks a ClassCastException.


Q:

download file from s3 to STDOUT

I currently use s3cmd to download a file from s3. However I'd rather output the contents to STOUT. Do you know a unix tool that can do it?
Thanks, Jan

A:

You'll need to add - to the end of you command arguments to make it redirect the output to STDOUT.
Example : s3cmd get s3://... -
See this thread for more information.


Q:

Text cleaner in OpenCV like ImageMagicK script

I try to make text in image cleaner and clearer before run OCR with tesseract. In this link, they provided a good scripts to do it by ImageMagicK. I wonder is possible to convert this script and function into OpenCV code? For example, the script with arguments like this:
-g -e none -f 15 -o 20

From the explanation:
-g ...................... convert document to grayscale before enhancing
-e .... enhance ......... enhance image brightness before cleaning;
                       choices are: none, stretch or normalize;
                       default=none
-f .... filtersize ...... size of filter used to clean background;
                       integer>0; default=15
-o .... offset .......... offset of filter in percent used to reduce noise;
                      integer>=0; default=5

How can I do the same in OpenCV code? As I am a newbie in OpenCV, I just only know how to convert to grayscale. Any help would be appreciated.

A:

You have to check ImageMagick documentation to find the exact algorithms used but here is a rough guess:
-g ...................... convert document to grayscale before enhancing

That would be either cv::cvtColor with BGR2GRAY conversion or even better, load directly your image in grayscale with cv::imread(filename,CV_LOAD_IMAGE_GRAYSCALE)
-e .... enhance ......... enhance image brightness before cleaning;
                       choices are: none, stretch or normalize;
                       default=none

Since you choosed "none", that would be nothing. Otherwise, use cv::equalizeHist (tutorial).
-f .... filtersize ...... size of filter used to clean background;
                       integer>0; default=15
-o .... offset .......... offset of filter in percent used to reduce noise;
                      integer>=0; default=5

My guess for the two latter parameters is cv::adaptiveThreshold with -f corresponding the the blockSize param in OpenCV and -o to the constant C. The actual adaptive thresholding methode (gaussian or mean) is what you need to check in ImageMagick documentation


Q:

How to add a TabBar badge?

I tries this code but the badge is not showing up
tabBarController?.tabBar.Item![3].badgeValue = "3"

I added this code to my TabBarController class
Is this the right way to add it?

A:

Your code should be like this : self.tabBar.Item![3].badgeValue ="3" because it seems to be a subclass.


Q:

Confusion on statement of Fubini's theorem for characteristic function of measurable set

I'm having trouble understanding what this theorem is saying.
Theorem.  Let $(X \times Y, \overline{\Sigma \times \tau}, \lambda)$ be a complete measure space and suppose $E \in \overline{\Sigma \times \tau}$.  Then:

$E_{x} \in \tau$ a.e. d$\mu(x)$
$f: X \to [0, \infty]$, $f(x) = \nu(E_{x})$ (a.e. d$\mu(x)$) defines a measurable function.
$\lambda(E) = \int \limits_{X} \nu(E_{x}) \text{ d}\mu$.

Note that this product measure space is the product of complete measure spaces $(X, \Sigma, \mu)$ and $(Y, \tau, \nu)$.  Also, $E_{x} = \{ y \in Y \mid (x, y) \in E \}$.
My points of confusion:
The only statement in this theorem I understand completely is statement 3.  It is saying that the integral of the characteristic function of $E$ with respect to $\lambda$ is actually an iterated integral.  But for 1, is it saying that for almost all $x$, $E_{x} \in \tau$?  Which means there are some $x$ such that $E_{x} \not \in \tau$?  If so, then that means the function defined in 2 is only defined almost everywhere.  What does it mean for a function that is only defined almost everywhere to be measurable?

A:

For  $x$ such that $E_{x} \not \in \tau$ you can define $f(x)$ to be anything you want. Now you have a function that is defined everywhere. Apply the usual measurability definition. Notice the measure space is complete: any subset of a zero measure set is measurable.


Q:

How write to xlsm using openpyxl

I am writing this piece of code. My objective is to set a value in a specific cell of this excel file. The code is running quite ok and exits with no error, but the cell A1 remains blank. How can I fix this?
import openpyxl
wb = load_workbook('Test.xlsm')
ws = wb.worksheets[1]
ws.cell(row=1, column=1).value = 999999
wb.save('Test.xlsm')

A:

from openpyxl import Workbook
from openpyxl import load_workbook

wb = load_workbook('Test.xlsm',keep_vba=True)
ws = wb['Sheet1']
ws.cell(row=1,column=1).value = 9999999
wb.save('Test.xlsm')

You need to have 'keep_vba' enabled since you are trying to modify an .xlsm(Excel Macro Enabled Workbook),I don't know why but this seems to work.
wb = load_workbook('Test.xlsm',keep_vba=True)


Q:

C++: partial specialization of template template classes

The following code:
using namespace std;

template <typename X>
class Goo {};

template <typename X>
class Hoo {};

template <class A, template <typename> class B = Goo >
struct Foo {
  B<A> data;
  void foo1();
  void foo2();

};

template <typename A>
void Foo<A>::foo1() { cout << "foo1 for Goo" << endl;}

int main() {
  Foo<int> a;
  a.foo1();

}

gives me a compiler error:
test.cc:18: error: invalid use of incomplete type 'struct Foo<A, Goo>'
test.cc:11: error: declaration of 'struct Foo<A, Goo>'

Why can't I partially specialize foo1() ?  If this is not the way, how do I do this?
I have another question: what if I want foo2() to be defined only for A=int, B=Hoo
and not for any other combination, how do I do that?

A:

Function templates may only be fully specialized, not partially.
Member functions of class templates are automatically function templates, and they may indeed be specialized, but only fully:
template <>
void Foo<int, Goo>::foo1() { }  // OK

You can partially specialise the entire class and then define it anew:
template <typename A>
struct Foo<A, Goo>
{
  // ...
};

(See 14.7.3 for details.)


Q:

Where is the organization in this website?

Imagine a reference book with no table of contents.  Ridiculous, right?  Well this is an amazing reference site and it needs to group questions in categories.  I see none.  Just tags.  There's a million different types of tags one could use.  It's a terrible way of organization - that's why almost nobody uses it solely.  If it's used as well as categories of course it enhances things.  But to rely on it only for finding things.....doesn't work well for most of us.
UPDATE:  I see some groupings at
http://stackexchange.com/sites#
but it's not organized properly.  You have Gardening besides Travel.  ???  Server Fault beside Photography.  ???  Looks like you took categories and threw them in a blender.  Is this on purpose?  I don't get it.
I see:
Technology
Culture / Recreation
Life / Arts
Science
Business
Professional
on the top but within each it's also jumbled.  Tor beside Sound Design.  Tor should be under Operating Systems or Privacy.  It's not even in alphabetical order!  Why?  Are you purposely trying to make things difficult to find?  I do not understand.

A:

The sites are broken into categories, like so:

You can then choose a category and order the sites as you wish — including in alphabetical order:

Here are your full options:

The idea of grouping tags together in categories, as I think you've suggested, has been done before (see also here). I've heard that the idea hasn't good over incredibly well with the team, but they haven't said no to it yet.
My view on it is that yes, it could help new users browsing the site. There are a hell of a lot of tags on any given site, and when you get to the larger sites, things become even wilder. However,

As you become more experienced, you learn more about the tags.
If you start to type in a couple letters in the tag bar thingie, you'll be given a short list of tags containing that letter. So if you had a question about BLT sandwiches, you could type sandwich into the bar and be shown a bunch of different tags containing that word. Or, you could just type it into the search bar under the "Tags" page on the top.
In general, you can type the name of the main focus of your question into the tag bar thingie, and chances are good that there's a tag for that.


Q:

simple prompt quiz javascript , pop up questions is showing all questsions

im new to programming and i keep having all questions comeup,i want the math.random  to pick 1 random question and ask it and log answer to the console but i keep getting prompted all the questions
var langquestion = prompt('what is the best language?');
var progquestion = prompt('how many years have you been programming?');
var drivequestion = prompt('does veronica drive good?');

var ran = Math.random() * 10;

if (ran < 3) {
    if (langquestion === 'javascript') {
        console.log('correct');
    } else {
        console.log('wrong');
    }
} else if (ran < 6 && ran > 3) {
    if (progquestion < 2) {
        console.log('keep working hard');
    } else if (progquestion > 2 && progquestion < 5) {
        console.log('your a programmer');
    } else {
        console.log('your the man');
    }
} else {
    if (drivequestion === 'yes'){
        console.log('correct');
    } else {
        console.log('wrong');
    }
};
    ;

A:

Your problem is that you prompt multiple times in a row, on the first 3 lines of your code.
Since your questions have different logics to handle the answer, you could structure your code like this:

var questions = [
  {
    text: 'What is the best language?',
    handler: function(answer) {
      return answer === 'javascript' ? 'Correct' : 'Wrong';
    }
  },
  {
    text: 'How many years have you been programming?',
    handler: function(answer) {
      if (answer < 2) return 'Keep working hard';
      else if (answer < 5) return 'You\'re a programmer';
      else return 'You\'re the man';
    }
  },
  {
    text: 'Does veronica drive well?',
    handler: function(answer) {
      return answer === 'yes' ? 'Correct' : 'Wrong';
    }
  }
];

var rand     = Math.floor(Math.random() * questions.length),
    question = questions[rand],
    answer   = prompt(question.text);

console.log(question.handler(answer));


Q:

Spark w Kafka - can't get enough parallelization

I am running spark with the local[8] configuration. The input is a kafka stream with 8 brokers. But as seen in the system monitor, it isn't parallel enough, it seems that about only one node is running. The input to the kafka streamer is about 1.6GB big, so it should process much faster.
system monitor
Kafka Producer:
import java.io.{BufferedReader, FileReader}
import java.util
import java.util.{Collections, Properties}

import logparser.LogEvent
import org.apache.hadoop.conf.Configuration
import org.apache.kafka.clients.producer.{KafkaProducer, Producer,     ProducerRecord}
import org.apache.kafka.common.serialization.StringDeserializer

object sparkStreaming{

  private val NUMBER_OF_LINES = 100000000

  val brokers ="localhost:9092,localhost:9093,localhost:9094,localhost:9095,localhost:9096,localhost:9097,localhost:9098,localhost:9099"
  val topicName = "log-1"
  val fileName = "data/HDFS.log"
  val producer = getProducer()

  // no hdfs , read from text file.
  def produce(): Unit = {
    try { //1. Get the instance of Configuration
      val configuration = new Configuration

      val fr = new FileReader(fileName)
      val br = new BufferedReader(fr)
      var line = ""
      line = br.readLine
      var count = 1
      //while (line != null){

      while ( {
        line != null && count < NUMBER_OF_LINES
      }) {
        System.out.println("Sending batch " + count + "  " + line)
        producer.send(new ProducerRecord[String, LogEvent](topicName,     new LogEvent(count,line,System.currentTimeMillis())))
        line = br.readLine
        count = count + 1
      }
      producer.close()
      System.out.println("Producer exited successfully for " +     fileName)
    } catch {
      case e: Exception =>
        System.out.println("Exception while producing for " +     fileName)
        System.out.println(e)
    }
  }

  private def getProducer() : KafkaProducer[String,LogEvent] = { // create instance for properties to access producer configs
    val props = new Properties
    //Assign localhost id
    props.put("bootstrap.servers", brokers)
    props.put("auto.create.topics.enable", "true")
    //Set acknowledgements for producer requests.
    props.put("acks", "all")
    //If the request fails, the producer can automatically retry,
    props.put("retries", "100")
    //Specify buffer size in config
      props.put("batch.size", "16384")
    //Reduce the no of requests less than 0
    props.put("linger.ms", "1")
    //The buffer.memory controls the total amount of memory available     to the producer for buffering.
    props.put("buffer.memory", "33554432")
    props.put("key.serializer",     "org.apache.kafka.common.serialization.StringSerializer")
    props.put("value.serializer", "logparser.LogEventSerializer")
    props.put("topic.metadata.refresh.interval.ms", "1")
    val producer = new KafkaProducer[String, LogEvent](props)
    producer
  }

  def sendBackToKafka(logEvent: LogEvent): Unit ={
    producer.send(new ProducerRecord[String, LogEvent]    ("times",logEvent))
  }

  def main (args: Array[String]): Unit = {
    println("Starting to produce");
    this.produce();
  }
}

Consumer:
package logparser

import java.io._

import java.util.Properties

import kafka.serializer.StringDecoder

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}

import org.apache.kafka.common.serialization.StringDeserializer

import org.apache.spark.SparkConf

import org.apache.spark.rdd.RDD

import org.apache.spark.streaming._

import org.apache.spark.streaming.kafka010._

object consumer {

  var tFromKafkaToSpark: Long = 0

  var tParsing :  Long = 0

  val startTime = System.currentTimeMillis()

  val CPUNumber = 8

  val pw = new PrintWriter(new FileOutputStream("data/Streaming"+CPUNumber+"config2x.txt",false))

  pw.write("Writing Started")

  def printstarttime(): Unit ={

    pw.print("StartTime : " + System.currentTimeMillis())

  }

  def printendtime(): Unit ={

    pw.print("EndTime : " + System.currentTimeMillis());
  }
  val producer = getProducer()

  private def getProducer() : KafkaProducer[String,TimeList] = { // create instance for properties to access producer configs
    val props = new Properties
    val brokers ="localhost:9090,"
//Assign localhost id
    props.put("bootstrap.servers", brokers)
    props.put("auto.create.topics.enable", "true")
    //Set acknowledgements for producer requests.
    props.put("acks", "all")
    //If the request fails, the producer can automatically retry,
    props.put("retries", "100")
    //Specify buffer size in config
    props.put("batch.size", "16384")
    //Reduce the no of requests less than 0
    props.put("linger.ms", "1")
    //The buffer.memory controls the total amount of memory available     to the producer for buffering.
    props.put("buffer.memory", "33554432")
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
props.put("value.serializer", "logparser.TimeListSerializer")
props.put("topic.metadata.refresh.interval.ms", "1")
val producer = new KafkaProducer[String, TimeList](props)
producer
  }

  def sendBackToKafka(timeList: TimeList): Unit ={
    producer.send(new ProducerRecord[String, TimeList]("times",timeList))
  }

def main(args: Array[String]) {
val topics = "log-1"
//val Array(brokers, ) = Array("localhost:9092","log-1")
val brokers = "localhost:9092"
// Create context with 2 second batch interval
val sparkConf = new SparkConf().setAppName("DirectKafkaWordCount").setMaster("local[" + CPUNumber + "]")
val ssc = new StreamingContext(sparkConf, Seconds(1))
// Create direct kafka stream with brokers and topics
val topicsSet = topics.split(",").toSet
var kafkaParams = Map[String, AnyRef]("metadata.broker.list" -> brokers)
kafkaParams = kafkaParams + ("bootstrap.servers" -> "localhost:9092,localhost:9093,localhost:9094,localhost:9095,localhost:9096,localhost:9097,localhost:9098,localhost:9099")
kafkaParams = kafkaParams + ("auto.offset.reset"-> "latest")
kafkaParams = kafkaParams + ("group.id" -> "test-consumer-group")
kafkaParams = kafkaParams + ("key.deserializer" -> classOf[StringDeserializer])
kafkaParams = kafkaParams + ("value.deserializer"-> "logparser.LogEventDeserializer")
//kafkaParams.put("zookeeper.connect", "192.168.101.165:2181");
kafkaParams = kafkaParams + ("enable.auto.commit"-> "true")
kafkaParams = kafkaParams + ("auto.commit.interval.ms"-> "1000")
kafkaParams = kafkaParams + ("session.timeout.ms"-> "20000")
kafkaParams = kafkaParams + ("metadata.max.age.ms"-> "1000")
val messages = KafkaUtils.createDirectStream[String, LogEvent](
  ssc,
  LocationStrategies.PreferConsistent,
  ConsumerStrategies.Subscribe[String, LogEvent](topicsSet, kafkaParams))

var started = false
val lines = messages.map(_.value)
val lineswTime = lines.map(event =>
  {
    event.addNextEventTime(System.currentTimeMillis())
    event
  }
)

lineswTime.foreachRDD(a => a.foreach(e => println(e.getTimeList)))

val logLines = lineswTime.map(
  (event) => {
    //println(event.getLogline.stringMessages.toString)
    event.setLogLine(event.getContent)
    println("Got event with id   =  " + event.getId)
    event.addNextEventTime(System.currentTimeMillis())
    println(event.getLogline.stringMessages.toString)
    event
  }
)
//logLines.foreachRDD(a => a.foreach(e => println(e.getTimeList  +  e.getLogline.stringMessages.toString)))

val x = logLines.map(le => {
  le.addNextEventTime(System.currentTimeMillis())
  sendBackToKafka(new TimeList(le.getTimeList))
  le
})

x.foreachRDD(a => a.foreach(e => println(e.getTimeList)))

//logLines.map(ll => ll.addNextEventTime(System.currentTimeMillis()))
println("--------------***///*****-------------------")

//logLines.print(10)
/*
val words = lines.flatMap(_.split(" "))
val wordCounts = words.map(x => (x, 1L)).reduceByKey(_ + _)
wordCounts.print()
*/

// Start the computation
ssc.start()
ssc.awaitTermination()
ssc.stop(false)

pw.close()

}
}

A:

There's a piece of information missing in your problem statement: how many partitions does your input topic log-1 have?
My guess is that such topic have less than 8 partitions.
The parallelism of Spark Streaming (in case of a Kafka source) is tied (modulo re-partitioning) to the number of total Kafka partitions it consumes (i.e. the RDDs' partitions are taken from the Kafka partitions).
If, as I suspect, your input topic only has a few partitions, for each micro-batch Spark Streaming will task only an equal amount of nodes with the computation. All the other nodes will sit idling.
The fact that you see all the node working in an almost round-robin fashion is due to the fact that Spark do not always choose the same node for processing data for the same partition, but it actually actively mix things up.
In order to have a better idea on what's happening I'd need to see some statistics from the Spark UI Streaming page.
Given the information you provided so far however, the insufficient Kafka partitioning would be my best bet for this behaviour.


Q:

add conditionals to a displayed external xml feed

I found the following code online and customized it to pull the xml feeds from our online calendar software and display event information on several different WP pages.
function otpl_add_class_feed() {
    if ( is_page(48) ) {
        $url = "http://orion.lib.mi.us/evanced/lib/eventsxml.asp?ag=&et=Computer+Class&nd=31&dm=exml&alltime=1";
        $xml = simplexml_load_file($url);
        foreach($xml->item as$item)
            {
                echo "
";
                echo "
link."'>".$item->title."
";
                echo "
".$item->date." from ".$item->time." to ".$item->endtime."
";
                echo "
".$item->description."
";
                echo "
link."'>Register Online.
";
                echo "
";
            }
    } // END IF
}

How can I include a conditional statement so that if $item->date. is populated the above code will run but if $item->date. is empty then another code stating that there are no events scheduled will run?  I'm sure it's something simple but my understanding of syntax isn't very strong.  My few attempts have broken my functions page.

A:

As @birgie pointed out, add a conditional statement to check that the date has been set:

if ( isset( $item->date ) && strlen( $item->date ) > 0 ) { ... }


Q:

What are the Salesforce Spring '15 release features?

As a Salesforce developer, consultant and administrator, I like to stay on top of new features in dev or due to be released in the medium or near future. As the Spring '15 release maintenance exam dates have already been posted I take it that Spring '15 release planning is well under way and so I would like to know ASAP what the new features planned are and when they will be available for pre-release/sandbox trialling.

A:

You can find the release notes digest here.
The full release notes here.
There are several blogs out and the topic can be found on the success community here.
Here is a preview of the Spring 15 release.
There is also a "Success - Release Readiness" collaboration group here.


Q:

Error in invoking javac - Debian Squeeze

I am trying to solve this issue:
PWC6345: There is an error in invoking javac.  A full JDK (not just JRE) is required
We have a third-party Java app that uses a Jetty server but looks like either the JDK is missing or not reachable where it is located?
In /usr/bin I see:
java
javaws
jexec
No javac so probably no JDK installed.
The box is Debian "Squeeze" with the following:
java -version
java version "1.6.0_18"
OpenJDK Runtime Environment (IcedTea6 1.8.13) (6b18-1.8.13-0+squeeze2)
OpenJDK Client VM (build 14.0-b16, mixed mode, sharing)
What is this the right Squeeze package?
apt-cache search javac
default-jdk - Standard Java or Java compatible Development Kit
openjdk-6-jdk - OpenJDK Development Kit (JDK)
Something else?
Thanks!
HTTP ERROR 500

Problem accessing /. Reason:

PWC6345: There is an error in invoking javac.  A full JDK (not just JRE) is required

Caused by:

org.apache.jasper.JasperException: PWC6345: There is an error in invoking javac.  A full JDK (not just JRE) is required
at org.apache.jasper.compiler.DefaultErrorHandler.jspError(DefaultErrorHandler.java:92)
at org.apache.jasper.compiler.ErrorDispatcher.dispatch(ErrorDispatcher.java:378)
at org.apache.jasper.compiler.ErrorDispatcher.jspError(ErrorDispatcher.java:119)
at org.apache.jasper.compiler.Jsr199JavaCompiler.compile(Jsr199JavaCompiler.java:208)
at org.apache.jasper.compiler.Compiler.generateClass(Compiler.java:384)
at org.apache.jasper.compiler.Compiler.compile(Compiler.java:453)
at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:625)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:374)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:492)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:378)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:598)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:486)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:542)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1065)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:413)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:192)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:999)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:271)
at org.eclipse.jetty.server.Dispatcher.forward(Dispatcher.java:98)
at org.eclipse.jetty.servlet.DefaultServlet.doGet(DefaultServlet.java:557)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:735)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:848)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:598)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:486)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:119)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:499)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:231)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1065)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:413)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:192)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:999)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:117)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:250)
at org.eclipse.jetty.server.handler.HandlerCollection.handle(HandlerCollection.java:149)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:111)
at org.eclipse.jetty.server.Server.handle(Server.java:350)
at org.eclipse.jetty.server.AbstractHttpConnection.handleRequest(AbstractHttpConnection.java:454)
at org.eclipse.jetty.server.AbstractHttpConnection.headerComplete(AbstractHttpConnection.java:890)
at org.eclipse.jetty.server.AbstractHttpConnection$RequestHandler.headerComplete(AbstractHttpConnection.java:944)
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:630)
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:230)
at org.eclipse.jetty.server.AsyncHttpConnection.handle(AsyncHttpConnection.java:77)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:620)
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:46)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:603)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:538)
at java.lang.Thread.run(Thread.java:636)

A:

Actually, depending on the web application you want to run in Jetty, it might be better to install the Sun JDK ( sun-java6-jdk , which would automatically divert all java/javac/... symbolic link to the Sun JDK ), because it often provides a much better compatibility with some applications.
The default-jdk should at least provide javac, so the error might indicate that you have a compatibility issue (It does NOT say that javac could not be found, but that javac failed to execute correctly).


Q:

Using RxJS to display a loading indicator and handling timing with the merge operator

I have the following minimal example that demonstrates the problem I am facing, where episode is fed a value from the UI and getEpisodeTitleFromApi is a long running observable that emits a string.
In the situation where episode is null or greater than 6, result$ emits an empty string immediately to handle invalid or empty input.
The intent of loading$ should be pretty clear.
episode = new Subject<number>();

result$ = this.episode.pipe(
  switchMap(episode => !episode || episode > 6 ? of('') : getEpisodeTitleFromApi(episode)),
  share()
);

loading$ = merge(
  this.result$.pipe(mapTo(false)),
  this.episode.pipe(mapTo(true))
);

The problem is, when episode is null or greater than 6 and emits right away, loading$ emits false and then true.
How can I wire up the loading$ observable to emit in the correct order or achieve the desired result?

A:

If you want your result not to run synchronus you can use the observeOn and set the execution on the macro task via observeOn(asyncScheduler) - [RxJS - Scheduler][1]
const episode = new Subject<number>();

const result$ = episode.pipe(
  switchMap(episode => of('')),
  observeOn(asyncScheduler)
);

const loading$ = merge(
  result$.pipe(mapTo(false)),
  episode.pipe(mapTo(true))
);

loading$.subscribe(console.error);

episode.next(1);

Output: true, false


Q:

Php echo some text;

I was going through a php file and there I saw this line
echo PRO_PREVIEW_BUTTON;

and actually didn't even find this PRO_PREVIEW_BUTTON printed anywhere in htmlfile.
So what does it mean according to you???

A:

echo PRO_PREVIEW_BUTTON;

This is surely a constant expression.
You can test it this way:
define('PRO_PREVIEW_BUTTON', 'Some value');
echo PRO_PREVIEW_BUTTON;

Constants do not need a $ (dollar sign) before it.


Q:

Movie streaming with mplayer

How can I see a movie from one of several streaming sites?
I would like use mplayer, given a certain url.
For instance:
mplayer -url http://address

A:

Well, I have the same problem, and I solved the problem in this way:

open link in Chrome;
press F12 to open console and go to the Network tab;
before pressing "Play" clear history console, then press "Play";
you will see some element in Network list, so order by "Type" and search for an alement of "application/octet-stream" type: right-click on this element and select "Copy as cURL": the bulk of the work has been done!
close Chrome and open a console:
paste cURL and put the stream in a new file, like in this way:
curl ..... > movie
now, in another tab, you can view your movie with mplayer, simply in this way:
mplayer -fs movie -idx

Explanation:
-fs put your video in fullscreen
-idx "Rebuilds index of files if no index was found, allowing seeking. Useful with broken/incomplete downloads, or badly created files."


Q:

Get json data through ajax

The question I am asking is a basic question because I am new in json and ajax.
so I have a json data of name , task , date and status I am getting data through ajax but it  is not showing in on my page.

my ajax code is this:
$(document).ready(function(e) {
    // Using the core $.ajax() method
    $.ajax({
        url: "getdata.php",
        type: "GET",
        dataType : "json",
        success: function( json ) {
            $( "
" ).text( json.name ).appendTo( "body" );
            $( "
").html( json.task ).appendTo( "body" );
        },
        complete: function( xhr, status ) {
            alert( "The request is complete!" );
        }
    });
});

this is my json data:
[
  {"name":"Usman ","task":"Getting work","date":"27-07-2014 12:28:45 PM","status":"1"},
  {"name":"Hamza","task":"Starting work","date":"27-07-2014 12:29:36 PM","status":"1"},
  {"name":"Hamza","task":"Geted","date":"27-07-2014 2:04:07 PM","status":"1"},
  {"name":"Hamza","task":"Start work","date":"02-08-2014 3:56:37 PM","status":"1"}
]

I don't know why It is not appending html data but it is showing complete alert.
I have added fiddle even if it is not working.
Fiddle

A:

Ok, i see you actually getting results so i guess you do have a success. You do have a flaw though. You are trying to access properties directly, but your json is an array of objects and not an object.
You need to do a foreach itteration.
json.forEach(function (entry) {
    $( "
" ).text( entry.name ).appendTo( "body" );
    $( "
").html( entry.task ).appendTo( "body" );
});


Q:

Alternatives to the repository pattern?

People have yelled at me, that I should always use the repository pattern, which I've done for quite a while... Now I'm wondering whether there is any decent alternatives for this pattern at all?

A:

Well there's the Data Access Object pattern, but that often sits on top of the repository, and serves to wrap up complex queries so they can simply be called as a single method.
Repository provides a standard interface into your database, and DAO exposes standard queries, which is why the two go together so well; DAO forwards specific calls to repository.  Of course you could certainly choose to not use a repository in your DAO.  You could open a connection to your DB and run the queries directly, or use a Table Data Gateway, but I think the reason most people prefer Repository is because it's quite a bit cleaner than those two options, though they shouldn't be yelling at you :)
http://en.wikipedia.org/wiki/Data_access_object

In computer software, a data access
  object (DAO) is an object that
  provides an abstract interface to some
  type of database or persistence
  mechanism, providing some specific
  operations without exposing details of
  the database. It provides a mapping
  from application calls to the
  persistence layer. This isolation
  separates the concerns of what data
  accesses the application needs, in
  terms of domain-specific objects and
  data types (the public interface of
  the DAO), and how these needs can be
  satisfied with a specific DBMS,
  database schema, etc. (the
  implementation of the DAO). This
  design pattern is equally applicable
  to most programming languages, most
  types of software with persistence
  needs and most types of database, but
  it is traditionally associated with
  Java EE applications and with
  relational databases accessed via the
  JDBC API because of its origin in Sun
  Microsystems' best practice
  guidelines[1] ("Core J2EE Patterns")
  for that platform.


Q:

Can an ordinary whip be poisoned?

I'm running a whip-wielding ranger/rogue, and I'm wondering if it's possible to poison a whip, both from a rules standpoint and as a practical matter.
Rules-wise, there's this from the DMG:

Injury. A creature that takes slashing or piercing damage from a weapon or piece of ammunition coated with injury poison is exposed to
  its effects.

since a whip deals slashing damage, it suggests that it's at least legal. The PHB seems to back this up:

Poison, Basic. You can use the poison in this vial to coat one slashing or piercing weapon or up to three pieces o f ammunition.
  Applying the poison takes an action...

Am I missing anything that specifies bladed or metal weapons?
Then, assuming it's legal, the other question is does it make sense? I'm no expert on whips, although at our local Renaissance Faire there's a guy who dips his chainmail bullwhip in gas and lights it on fire, which suggests a whip might soak up a liquid, like a poison.
Is there anyone out there who can make a practical case for or against poisoning a whip?

A:

I just want to add some real world experience as a whip wielder in real life.   One of the things we do for tricks is to dip the "popper", that's the cutting part of the whip, in ink.  We do this to color our targets.   One dose will last 5 or so hits, and gets into the target.
I can't speak to how real poison works, but as far as to whether or not a whip can be used to get poison into a wound, it absolutely could.

A:

Yes, this works according to the rules. Whether it "makes sense" is up to you.
You've already quoted the relevant parts of the rules.

Poison, Basic. You can use this vial to coat one slashing or piercing weapon...  PHB, page 153

A whip is a slashing weapon. There's nothing to say that it only applies to bladed or metal weapons.
As for whether it makes sense, that's entirely up to you. Remember that D&D isn't a simulation for real life. What works in a tabletop RPG may not work in real life and what works in real life may not work in a tabletop RPG.

A:

Does it work according to the rules? Yes.
Purple Monkey answered this completely, but we like answers to be self contained. Yes, the rules allow poison on slashing weapons and whips are slashing weapons. Therefore, RAW, whips can be poisoned for full effect.
Does it make sense in the real world? No.
Poisoned weapons in the real world do not work anything like the way they work in D&D or most RPGs. This question has several answers that go into detail: Realism of Poisoned Weapons
The short version is that while poisoned weapons have seen use in the real world most of them are far too slow to be useful during melee combat the way they are often used in D&D. Instead, they tended to make sure the target (whether an enemy or prey animal) died eventually. It also tended to be much harder to obtain and use than RPGs portray.
Of course, the flip side is that poisoning food and drink comes up far less often in most D&D situations than you saw in the real world were that did work quite well.
In short, the way D&D portrays poisons in general already does not make a lot of sense in the real world.
Does it make sense within the D&D world? Probably.
As mentioned, the way D&D handles poisons does not make sense within the real world. However, if you accept that poisons work the way they do in the D&D fiction then poisoning a whip makes as much sense as poisoning a sword. Whips can break skin and some poisons can be absorbed through the skin so even breaking skin is not necessarily a strict requirement.


Q:

Is it necessary to use resistor when connecting backlight of 16x2 LCD display?

I wonder if it's necessary to use any resistor when you're connecting backlight of
16x2 LCD module? OR it depends on voltage?
I am using Hitachi HD47780

A:

This is just a complementary answer for people facing this question for the first time (beginners or even non-beginners), like I did a few months ago when received a batch of no-name LCD modules clones of the JHD162A with an incorrect datasheet. This answer only apply to LCD modules with a LED backlight (using a single LED or an array of LEDs) which are the most popular.

If you have the datasheet, it should contain the information somewhere, you just need to calculate the current limiter resistor value using the suggested LED forward current and supply voltage minus the LED forward voltage.
If you don't have the datasheet, check the back of the LCD. Usually you can find easily if there is a resistor in series with the A (or even the K) pin. The following images show how some modules which already have a limiting resistor. Just be sure it is really a resistor and not a jumper (a zero ohm "resistor").
If you find (or not) the limiting resistor, verify it is in series with the LED supply by measuring the resistance from the A pin to the anode of the backlight and from the K pin to the cathode of the backlight. The backlight usually is soldered to pads marked as A and K.
If even after inspecting and measuring you are not sure, just use a 100 or 220 ohms resistor and test.
If you are designing a PCB and you are not sure if the provisioned LCD modules will have already a resistor, just add the space for a resistor in your circuit; so later on, during production, you can use a resistor or a jumper. (Of course that kind of thing should be known in advance, but sometimes is not always possible, or the requirements may state that your circuit it should work with any LCD module).

In this image a LCD 16x2 character module has a 100 ohm resistor (R8) in series with the A pin (pin 15) trace. The value was verified measuring from pin 15 to the A pad (in the left edge) soldered to the backlight.

In this image, a JDH204A (JHD629) LCD 20x4 character module has a combination of jumpers and resistors to select what pins are for the cathode (K) and anode (A) (the table in the silkscreen describe the configuration options). In this case R9 and R11 are using jumpers, meaning pin 15 is for the anode and 16 is for the cathode of the backlight, and the R12 and R13 are the limiting resistors (they are in parallel, in this case both are 68 ohms, providing 34 ohms). The value was verified by measuring the resistance between pin 15 and the A1 pad (at the left edge) soldered to the backlight.

In this image, a JDH204A clone, there is a 51 ohm resistor in series with the A pin trace and a jumper for the K pin trace. The value was verified measuring the resistance between pin 15 and the top pad at the left edge (you can follow the trace from the resistor to that pad, so we expect it to be the LED anode connection). You may note the resistors are installed perpendicular to the position drawn in the silkscreen; the manufacturer can change easily the polarity of the A and K pins just by solder the resistor/jumper pair vertically or horizontally.

In all modules I have used over the years, the A and K pins are completely independents of the LCD and controller circuit, so you may use a different supply rail with a different voltage than the rest of the circuit. (Just note that this has just been my experience with the original JHD modules and some clones, but this may not apply to other brands).

A:

It depends entirely on the module.  Some have a limiting resistor (e.g. the JHD162 commonly seen on eBay) and some do not.  You will need the datasheet for your specific model, or have a look at the LED connections and see if you can see a series resistor.
The HD44780 is not connected to the backlight in any way.


Q:

Using Pebble template engine with Spring Boot

So I'm trying to integrate Pebble templating engine to my spring boot application but I'm confused on how to implement this.
So I've read through their site on how to implement it however it says for Spring MVC which I think not similar with Spring Boot.
I also go to their github page then trying to add their maven dependency to POM.xml but I don't know if I will configure something or it is the same as Thymeleaf or Mustache that are autoconfigured.
Link to their site: http://mitchellbosecke.com/pebble/

A:

Add the starter dependency to your pom.xml:
spring-boot v1
<dependency>
    <groupId>io.pebbletemplates</groupId>
    <artifactId>pebble-spring-boot-starter</artifactId>
    <version>2.6.2</version>
</dependency>

OR
spring-boot v2
<dependency>
    <groupId>io.pebbletemplates</groupId>
    <artifactId>pebble-spring-boot-2-starter</artifactId>
    <version>2.6.2</version>
</dependency>

This is enough for autoconfiguration to kick in. This includes:

a Loader that will pick template files ending in .pebble from /templates/ dir on the classpath
a PebbleEngine with default settings, configured with the previous loader
a ViewResolver that will output text/html in UTF-8

PLEASE NOTE: the starter depends on spring-boot-starter-web but is marked as optional, you'll need to add the dependency yourself or configure Spring MVC appropiately.
Boot externalized configuration
A number of properties can be defined in Spring Boot externalized configuration, eg. application.properties, starting with the prefix pebble. See the corresponding PebbleProperties.java for your starter version. Notable properties are:

pebble.prefix: defines the prefix that will be prepended to the mvc view name. Defaults to /templates/
pebble.suffix: defines the suffix that will be appended to the mvc view name. Defaults to .pebble
pebble.cache: enables or disables PebbleEngine caches. Defaults to true
pebble.contentType: defines the content type that will be used to configure the ViewResolver. Defaults to text/html
pebble.encoding: defines the text encoding that will be used to configure the ViewResolver. Defaults to UTF-8
pebble.exposeRequestAttributes: defines whether all request attributes should be added to the model prior to merging with the template for the ViewResolver. Defaults to false
pebble.exposeSessionAttributes: defines whether all session attributes should be added to the model prior to merging with the template for the ViewResolver. Defaults to false
pebble.defaultLocale: defines the default locale that will be used to configure the PebbleEngine. Defaults to null
pebble.strictVariables: enable or disable the strict variable checking in the PebbleEngine. Defaults to false

Customizing Pebble
Pebble extensions
Extensions defined as beans will be picked up and added to the PebbleEngine automatically:
@Bean
public Extension myPebbleExtension1() {
    return new MyPebbleExtension1();
}

@Bean
public Extension myPebbleExtension2() {
    return new MyPebbleExtension2();
}

CAVEAT: Spring will not gather all the beans if they're scattered across multiple @Configuration classes. If you use this mechanism, bundle all Extension @Beans in a single @Configuration class.
Customizing the Loader
The autoconfigurer looks for a bean named pebbleLoader in the context. You can define a custom loader with that name and it will be used to configure the default PebbleEngine:
@Bean
public Loader<?> pebbleLoader() {
    return new MyCustomLoader();
}

PLEASE NOTE: this loader's prefix and suffix will be both overwritten when the ViewResolver is configured. You should use the externalized configuration for changing these properties.
Customizing the PebbleEngine
Likewise, you can build a custom engine and make it the default by using the bean name pebbleEngine:
@Bean
public PebbleEngine pebbleEngine() {
    return new PebbleEngine.Builder().build();
}

Customizing the ViewResolver
And the same goes for the ViewResolver, using the bean name pebbleViewResolver:
@Bean
public PebbleViewResolver pebbleViewResolver() {
    return new PebbleViewResolver();
}

PLEASE NOTE: you need to change the Loader's prefix and suffix to match the custom ViewResolver's values.
Using Pebble for other tasks
The main role of this starter is to configure Pebble for generating MVC View results (the typical HTML). You may define more PebbleEngine/Loader beans for other usage patterns (like generating email bodies). Bear in mind that you should not reuse the default Loader for other Engine instances.


Q:

Find a match in workbook using Excel VBA: run-time error 1004

I am trying to create a macro which searches for the word "Routing" in all sheets of my active workbook.
When it detects the first occurrence in one of my sheets of my workbook, I want my macro to select the related cell on the corresponding sheet.
My macro returns the error message:

run-time error 1004: activate method of range class failed…

It seems this line of code generates the issue: Loc.Activate
Sub FindAndExecuteRouting()
Dim Sh As Worksheet
Dim Loc As Range
For Each Sh In ActiveWorkbook.Worksheets
    With Sh.UsedRange
        Set Loc = .Cells.Find(What:="Routing")
        If Not Loc Is Nothing Then
            Loc.Activate
        End If
    End With
Next
End Sub

A:

You can't Activate a Range unless it's on the ActiveSheet.
So you'd have to do Sh.Activate before you can do Loc.Activate. Note that normally you do not want to Activate a cell you already have a reference to, but when the goal is to select a cell so that the user can see the selection box around a specific cell... well, that's one of the very few legit use cases for Worksheet.Activate =)
Public Sub FindAndExecuteRouting()
    Dim Sh As Worksheet
    Dim Loc As Range
    For Each Sh In ActiveWorkbook.Worksheets
        With Sh.UsedRange
            Set Loc = .Find(What:="Routing")
            If Not Loc Is Nothing Then
                Sh.Activate
                Loc.Activate
                Exit Sub
            End If
        End With
    Next
End Sub

Note the Exit Sub: you want to stop looping (Exit For would work as well) once you've found one, otherwise you'll just successively select every result very quickly, and only the last one will end up selected.
Consider using an indenter to help keep indentation consistent!


Q:

Where are the actual names of the packages in "apt list --upgradable"?

It seems to be printing only the versions:
$ apt list --upgradable
Listing... Done
dpkg/bionic-updates 1.19.0.5ubuntu2.3 amd64 [upgradable from: 1.19.0.5ubuntu2.2]
file-roller/bionic-security 3.28.0-1ubuntu1.1 amd64 [upgradable from: 3.28.0-1ubuntu1]
libdpkg-perl/bionic-updates,bionic-updates 1.19.0.5ubuntu2.3 all [upgradable from: 1.19.0.5ubuntu2.2]

Tried using "1.19.0.5ubuntu2.3" or just "ubuntu", to no avail as expected:
$ apt show 1.19.0.5ubuntu2.3
N: Unable to locate package 1.19.0.5ubuntu2.3
N: Couldn't find any package by glob '1.19.0.5ubuntu2.3'
N: Couldn't find any package by regex '1.19.0.5ubuntu2.3'
N: Unable to locate package 1.19.0.5ubuntu2.3
N: Couldn't find any package by glob '1.19.0.5ubuntu2.3'
N: Couldn't find any package by regex '1.19.0.5ubuntu2.3'
E: No packages found
$ apt show ubuntu
N: Unable to locate package ubuntu
N: Unable to locate package ubuntu
E: No packages found

So, where are the actual package names? OS version reads Ubuntu 18.04.3 LTS.

A:

dpkg, file-roller, and libdpkg-perl are the packages that can be upgraded. 1.19.0.5ubuntu2.3, 3.28.0-1ubuntu1.1, and 1.19.0.5ubuntu2.3 are the versions to which they can be upgraded, respectively.


Q:

Oracle client ORA-12541: TNS:no listener

I am new on Oracle database, but I have one issue.
On my Database server (server1) listener and database instance run correctly and I can use sqlplus to connect to this DB.
When I connect to database by using other server, I check the TNS configuration and it is correct but system says:

ERROR:
ORA-12541: TNS:no listener

My database is Oracle 10gR2
So how can I solve this issue?

A:

You need to set oracle to listen on all ip addresses (by default, it listens only to localhost connections.)
Step 1 - Edit listener.ora
This file is located in:

Windows: %ORACLE_HOME%\network\admin\listener.ora.
Linux: $ORACLE_HOME/network/admin/listener.ora

Replace localhost with 0.0.0.0
# ...

LISTENER =
  (DESCRIPTION_LIST =
    (DESCRIPTION =
      (ADDRESS = (PROTOCOL = IPC)(KEY = EXTPROC1521))
      (ADDRESS = (PROTOCOL = TCP)(HOST = 0.0.0.0)(PORT = 1521))
    )
  )

# ...

Step 2 - Restart Oracle services

Windows: WinKey + r
services.msc

Linux (CentOs):
sudo systemctl restart oracle-xe

A:

I also faced the same problem but I resolved the issue by starting the TNS listener in control panel -> administrative tools -> services ->oracle TNS listener start.I am using windows Xp and Toad to connect to Oracle.

A:

Check out your TNS Names, this must not have spaces at the left side of the ALIAS
Best regards


Q:

Does Magento Cron Job reindex data now?

Under Index Management, all categories were reindexed at the same time this morning. It was either someone did it, or the cron job did it.
But I confirmed that no one did it. I wonder if Magento cron job now reindex data. I know it didn't before, and I don't want any reindex in the cron job.
Here is my cron set up
*/5 *   *   *   *   /usr/local/bin/php /home/xxxx/public_html/cron.php -mdefault
*/5 *   *   *   *   /usr/local/bin/php /home/xxxx/public_html/cron.php -malways

A:

Although you didn't specify your Magento version, Magento 1.x series doesn't do it. It is surely, either triggered via admin or someone launched the command from shell.
If you happen to be in 2.x series(I highly doubt that, judging by the cron setup), cron is the only recommended way to re-index data now.


Q:

Best aproach for working with Time in WinForms?

I'm trying to make a field where user will enter amount of time per day he/she spent on a project per day. It can be from 30 minutes to 8 hours. Is DateTimePicker with CustomFormat hh:mm best choice for this? Or there's better alternative for WinForms C#? Maybe TextBox or MaskedTextBox with special settings?

A:

Although the MaskedTextBox is generally a pain, this is a situation it could be useful. With Mask="00:00".
Give it a spin.
And you will have to convert to/from text to TimeSpan yourself


Q:

Using empty tables NAV 2009 R2

I'm no NAV professional nor got any experience with NAV. Since 1 week I'm working with NAV and I got several questions about it, but I think that those "Microsoft specialized" experts my new employer is working with are just fooling us.
They for example said that it is not possible to autonumber items, and thats its never ever possible to import tables from Excel, thus I managed it with a plugin I got from mibuso.com
NOW they told my boss, that we have to buy new tables because we got nothing left. We are using only 1/3 of the whole NAV and we got many empty tables we dont use and we never will use ever! For example the module fpr "service" or "production".

as you can see there are many Tables empty. Is it possible to use them for other things than they are made for? Like I said i have no idea about NAV but when I think about usual SQL tables, I though that we can of course use them for other purposes (In this case we want to have programmed a storage for old bills)
Thanks in advance.

A:

Well... I can't tell that they totally fooling you, I'd suppose there is some misunderstanding between you and "experts".

There is a way to automatically assign numbers to such entities like Items, Orders, Invoices etc. If that is what you mean by "items". It is standard functionality and work across whole system. Its called No. Series. For example when you create new Item in Item table it will have next number from corresponding series: I0001, I002, I0003 and so on. If that is what you asking.
There are number of ways to integrate Nav with Excel and hell of other systems. But most of them requires development. So if your experts don't have development license - they can't do it.
Now... the tables. It is normal situation then you're not using whole system. I think it is practically impossible to use all of Nav granules. But that does not mean that you can use those table for your needs, thats why:

Not all tables can be altered by MS Partners (your experts).
Not all tables can be used by you (limited by granules you bought in your license).
If one changes the definition of a standard table (all that is not "Customer design area", see link below) in most cases it will brake some standard functionality somewhere else in the system, so it needs to be changed as well. It may require a lot of work.
If standard objects are changed you cant safely apply application updates (hotfixes) released by MS to your system.
No guarantee that you will not want to use those standard objects in the way they suppose to in the future.

There is a "Customer design area" - objects with ID's in range 50,000 - 99,999. This is where development goes specially for you by your experts. And that is where they are asking you to buy additional tables (forms, reports, etc). It is common practice because in this area object can be modified in any way you desire.

Object Numbering Conventions


Q:

Getting Equation to Find a Perfect Square

I'm trying to work through the explanation of Ferrari's Solution of the Quartic.
The arbitrary variable: $y$ is introduced to the depressed quartic in the link's step 3, yielding a right side of: $$(\alpha + 2y)u^2 - \beta u + (y^2 + 2\alpha y + \alpha^2 - \gamma)$$
Then the statement is then made that:

As the value of $y$ may be arbitrarily chosen, we will choose it in order to get a perfect square in the right-hand side. This implies that the discriminant in $u$ of this quadratic equation is zero, that is $y$ is a root of the equation

Somehow that yields the equation: $$(-\beta)^2 - 4(2y + \alpha)(y^2 + 2\alpha y + \alpha^2 - \gamma) = 0$$
I need help seeing what was done to achieve that jump. Can someone explain to me how we just decided that this equation could be used to solve for $y$?

A:

We can rewrite the equation as
$$(\alpha+2y) \left (u^2 + \frac{-\beta}{\alpha+2y} u + \frac{y^2+2\alpha y + \alpha^2 - \gamma^2}{\alpha+2y}\right ).$$
In order for
$$\left (u^2 + \frac{-\beta}{\alpha+2y} u + \frac{y^2+2\alpha y + \alpha^2 - \gamma^2}{\alpha+2y}\right )\qquad(*)$$
 to be a perfect square we must have that
$$\left(\frac{-\beta}{2(\alpha+2y)}\right)^2 = \frac{y^2+2\alpha y + \alpha^2 - \gamma^2}{\alpha+2y}$$
or equivalently
$$(-\beta)^2- 4(\alpha+2y)(y^2+2\alpha y + \alpha^2 - \gamma^2)=0.$$
This means that $(*)$ will be a perfect square whenever $y$ is a solution to this last equation.


Q:

a:visited make white on "Learn more about company X"

When you go to a job page you can scroll down to the company area where there is a button to "Learn more about Company X".  The button forecolor text is initially white, but becomes blue when visited.  Please eliminate this style as to keep the button text white at all times.
Once visited it looks like this:

This is so bad I consider it a bug!
Actually I just checked and this is on all the blue buttons on jobs.  Even the "Apply Now" button.  I think they should have a white foreground whether or not you click the button.

A:

Thank you for your bug report. We just did a big CSS-related refactor for Jobs, and this was a regression.
This issue has now been fixed.


Q:

Angular 7 formbuilder initialize value on multi-select get form invalid

I have problem initializing a fromgroup with select multiple control.
the initialization runs ok, but angular mark the from as invalid.
{{controlPanelForm.value | json}} -> tasks: ["3","1","5"]
{{controlPanelForm.status | json}} -> "INVALID"

now, when user select one or more tasks on multi-select the formgroup become valid.
{{controlPanelForm.value | json}} -> tasks: ["3","1","5"]
{{controlPanelForm.status | json}} -> "VALID"

I need, the formGroup valid from the initialization.
thanks, in advance.
////html
<form [formGroup]="controlPanelForm" (ngSubmit)="submit()">
    <select multiple id="tasks" size="7" [formControl]="controlPanelForm.get('tasks')">
        <option *ngFor="let t of projectTasks" [ngValue]="t.id">{{t.title}}</option>
    </select>
</form>

    {{controlPanelForm.value | json}}

    {{controlPanelForm.status | json}}

/////ts
controlPanelForm: FormGroup;
projectTasks: ProjectTask[] =[
    {id:'3', title:'title3'},
    {id:'1', title:'title1'},
    {id:'5', title:'title5'},
]
projectTasksIds: string[];

ngOnInit() {
    this.projectTasks.map((t) => {
        this.projectTasksIds.push(t.id.toString());
    });
    this.buildForm();
}

buildForm(): void {
        this.controlPanelForm = this.fb.group({
            'tasks': [[this.projectTasksIds], Validators.compose([Validators.required, Validators.pattern('.+')])],
        });
}

A:

The problem was syncro! the values of tasks: ["3","1","5"] came from ajax. So, when the form initilize the values are: []. To solve problem, I used controlPanelForm.patchValues(...) method on ajax response.
I hope this be helpfull for the others with the same problem.


Q:

android Local variable not used from Switch

Why I get two warnings: that variable "input5" is not used, and when I want to use it later in Intent: "input5" cannot be resolved to variable.
What am I missing in between? Thanks!
    final Switch mySwitch = (Switch) findViewById(R.id.edit_home);
    mySwitch.setOnCheckedChangeListener(new Switch.OnCheckedChangeListener() {

        @Override
        public void onCheckedChanged(CompoundButton buttonView,
                boolean isChecked) {
            // TODO Auto-generated method stub
            if(isChecked){
                 **double input5 = 1;**
                }else{
                 **double input5 = 2;**
                }

    Button buttonForward = (Button) findViewById(R.id.buttonToMain2);
    buttonForward.setOnClickListener(new OnClickListener(){

        @Override
        public void onClick(View arg0) {

    EditText edit_team = (EditText) findViewById(R.id.edit_team);
    EditText edit_form = (EditText) findViewById(R.id.edit_form);
    EditText edit_import = (EditText) findViewById(R.id.edit_import);
    String ekipa1 = edit_team.getText().toString();

    final double input2 = Double.valueOf(ratingBar.getRating());
    final double input3 = Double.valueOf(edit_form.getText().toString());
    final double input4 = Double.valueOf(mplayerControl.getProgress());
    final double input6 = Double.valueOf(edit_import.getText().toString());

    Intent intent=new Intent(MainActivity.this,Main2Activity.class);
    intent.putExtra("Value",input2);
    intent.putExtra("Value1",input3);
    intent.putExtra("Value2",input4);
    intent.putExtra("Value3",**input5**);
    intent.putExtra("Value4",input6);
    intent.putExtra("team1", ekipa1);
    startActivity(intent);

            }
    });
    }
    });

A:

Declare input5 as a instance-member
  if(isChecked){
             **double input5 = 1;**
            }else{
             **double input5 = 2;**
            }

It is declared and initialized in the if else block (input 5 is local to if else block).
If you have already declared as instance-member then initialize the variable input5.
 if(isChecked){
             input5 = 1;
            }else{
             input5 = 2;
            }