Q: Deciding which derived class is passed as an argument I'm struggling with my current design and would like to know, if theres a possibility to decide which method to call without using a casting method. Say I've got a base Fence class.
And at the moment my workers know how to build wooden fences and how to build barb wire fences. And they can add two fences together... but up to now they only learned how to connect the wooden ones with wooden ones, and the barb wired ones with barb wired ones.
But as they probably will learn more, the Fence class has a virtual addFence(const Fence& fence) method.
As I wanted to avoid any casting methods, I tried to add special addFence()methods in both classes. Here is an example:
class Fence {
public:
    virtual void addFence(const Fence& fence) = 0;
    ...
};

class BarbWireFence : public Fence {
public:
    ...
    void addFence(const Fence& fence) {
        //only add such a fence, if it is a barb wired one
    }
    void addFence(const BarbWireFence& fence) {
        //continue the fence with the given one
    }
};

class WoodenFence : public Fence {
public:
    ...
    void addFence(const Fence& fence) {
        //only add the fence, if it is a wooden one
    }
    void addFence(const WoodenFence& fence) {
        //continue the fence with the given one
    }
};

Now I would like to do something like
Fence *woodenFence1 = new WoodenFence();
Fence *woodenFence2 = new WoodenFence();
woodenFence1->addFence(*woodenFence2);

But as it is a runtime decision what sort of fence I've got, I only have the base Fence* pointer and therefore the definition of the base class Fence is used in the last line.
So is there a better implementation to decide 'automatically' what sort of fence I've got? Or should I use a completely different design?

A: I'm not aware of a general approach in C++ but assuming you have a fixed set of derived classes, you can actually deal with the situation using an extra indirection:
class BarbWireFence;
class WoodenFence;
class Fence {
public:
    virtual void add(Fence& fence) = 0;
    virtual void add(BarbWireFence& fence) = 0;
    virtual void add(WoodenFence& fence) = 0;
};

class BarbWireFence {
    void add(Fence& fence) override { fence.add(*this); }
    void add(BarbWireFence& fence) override; // deal with the actual addition
    void add(WoodenFence& fence) override;   // deal with the actual addition
};
class WoodenFence {
    void add(Fence& fence) override { fence.add(*this); }
    void add(BarbWireFence& fence) override; // deal with the actual addition
    void add(WoodenFence& fence) override;   // deal with the actual addition
};

A: Welcome to the wonderful world of binary methods.
There is no satisfactory solution to this problem. You may want to learn about double dispatch and its more formal sibling the Visitor pattern. These two things are basically the same, only presented a bit differently. In the most simplistic scenario you do this:
class WoodenFence;
class BarbWireFence;

class Fence {
public:
    virtual void addFence(const Fence& fence) = 0;
    virtual void addMe(BarbWireFence& fence) const = 0;
    virtual void addMe(WoodenFence& fence) const = 0;
    ...
};

class BarbWireFence : public Fence {
public:
    ...
    void addFence(const Fence& fence) {
      fence->addMe(*this);
    }
    void addMe(BarbWireFence& fence) const {
      fence->addBarbWireFence(*this);
    }
    void addMe(WoodenFence& fence) const {
      throw error("bad fence combo");
    }

    void addBarbWireFence(const BarbWireFence& fence) {
      // actually add fence...
    }
};

class WoodenFence : public Fence {
public:
    ...
    void addFence(const Fence& fence) {
      fence->addMe(*this);
    }
    void addMe(BarbWireFence& fence) const {
      throw error("bad fence combo");
    }
    void addMe(WoodenFence& fence) const {
      fence->addWoodenFenceFence(*this);
    }

    void addWoodenFence(const WoodenFence& fence) {
      // actually add fence...
    }

    ...
};

You can figure out what should happen when you add 10 other fence types.
There's a totally different direction one might take, namely, templatize the entire business and get rid of the Fence base class, as it doesn't provide a type-safe interface.
class BarbWireFence {
public:
...
void addSimilarFence(const BarbWireFence& fence) {
    //continue the fence with the given one
    }
};

class WoodenFence {
public:
...
void addSimilarFence(const WoodenFence& fence) {
    //continue the fence with the given one
    }
};

template <typename Fence>
void addFence (Fence& f1, const Fence& f2) {
   f1->addSimilarFence(f2);
}


Q: Custom filename for generated file in Jekyll In my _config.yml file I have defined the permalink like permalink: /posts/:title/ (notice the ending slash).
For a post in _posts/my_first_post/2017-05-06-my_first_post.markdown the generated file is _site/posts/my_first_post/index.html.
How can I change the filename from index.html to something arbitrary like something.htm?
Edit 1:
Didn't want to do this, but I ultimately had to look at the Jekyll source code:
In the lib/jekyll/page.rb there is this:
def destination(dest)
  path = site.in_dest_dir(dest, URL.unescape_path(url))
  path = File.join(path, "index") if url.end_with?("/")
  path << output_ext unless path.end_with? output_ext
  path
end

And in lib/jekyll/document.rb there is this:
def destination(base_directory)
  dest = site.in_dest_dir(base_directory)
  path = site.in_dest_dir(dest, URL.unescape_path(url))
  if url.end_with? "/"
    path = File.join(path, "index.html")
  else
    path << output_ext unless path.end_with? output_ext
  end
  path
end

So the index.html part is hardcoded. This question cannot be answered...unless there is a plugin that does what I want.

A: You can adjust the code of Jekyll to your specific requirement.
Open lib\jekyll\Page.rb in jekyll folder and update the destination method:
module Jekyll
  class Page
    def destination(dest)
      path = site.in_dest_dir(dest, URL.unescape_path(url))
      path = File.join(path, "index") if url.end_with?("/")
      path << output_ext unless path.end_with? output_ext

      # replace index with title
      path.sub! 'index',  data['title'] if data['title']

      path
    end
  end
end

Also update the destination method in lib\jekyll\Document.rb with the same line before returning path

A: Create a plugin and monkey patch those classes

Create _plugins/_my_custom_index.rb
module Jekyll
  class Page
    def destination(dest)
      path = site.in_dest_dir(dest, URL.unescape_path(url))
      path = File.join(path, "index") if url.end_with?("/")
      path << output_ext unless path.end_with? output_ext

      # replace index with title
      path.sub! 'index',  data['title'] if data['title']
      path
    end
  end
end

module Jekyll
  class Document
    def destination(base_directory)
      dest = site.in_dest_dir(base_directory)
      path = site.in_dest_dir(dest, URL.unescape_path(url))
      if url.end_with? "/"
        path = File.join(path, "index.html")
      else
        path << output_ext unless path.end_with? output_ext
      end

      # replace index with title
      path.sub! 'index',  data['title'] if data['title']

      path
    end
  end
end

A: You can change to permalink /posts/:title/:title.html
However, the post will be now accessible via http://server/post/my_first_post/my_first_post.html
If you want to change the default behavior, you should modify Jekyll.Page.destination

A: You can use permalink: /posts/:title/something:output_ext in the _config.yml or in post front matter


Q: If $\lim_{n\to\infty}\frac{a_{n+1}}{a_n}=1$, $\lim_{n\to\infty}\frac{a_{2n}}{a_n}=\frac{1}{2}$ then $\lim_{n\to\infty}\frac{a_{3n}}{a_n}=\frac{1}{3}$ Let $\{a_n\}$ be a decreasing sequence and $a_n>0$ for all $n$.
If $\displaystyle\lim_{n\to\infty}\frac{a_{n+1}}{a_n}=1$ and $\displaystyle\lim_{n\to\infty}\frac{a_{2n}}{a_n}=\frac{1}{2}$,
how to prove or disprove that
$\displaystyle\lim_{n\to\infty}\frac{a_{3n}}{a_n}=\frac{1}{3}$ ?
Thank you.

A: This is not an answer, but a longer train of thoughts / conjectures that might lead to a full answer.
It might be an idea to use $\displaystyle\lim_{n\to\infty}\frac{a_{2n}}{a_n}=\frac{1}{2}$ and apply it $r$ times. This gives
$$
\displaystyle\lim_{n\to\infty}\frac{a_{2^rn}}{a_n}=\frac{1}{2^r}
$$
which holds for all $r$. Now take some $m$ and identify $r$ such that $2^r \leq m < 2^{r+1}$. Then one has
$$
\frac{1}{2^r} \geq \displaystyle\lim_{n\to\infty}\frac{a_{m n}}{a_n} > \frac{1}{2^{r+1}}
$$
In particular, this holds when $m$ is chosen to be any power $3^p$. This gives a countable infinite set of inequalities of the type above, all of which must hold. They do hold if
$$
\displaystyle\lim_{n\to\infty}\frac{a_{3 n}}{a_n}=\frac{1}{3}
$$
implying
$$
\displaystyle\lim_{n\to\infty}\frac{a_{3^p n}}{a_n}=\frac{1}{3^p}
$$
The conjecture is that there is no other way that they can hold.

A: The limit of $\frac{a_{3n}}{a_n}$ need not be $\frac13$, because it need not exist.
Each $n>0$ can be written uniquely as $2^k + r$, where $2^k \le n < 2^{k+1}$. Define $a_n$ (in terms of these $k$ and $r$) piecewise as follows: $$a_n = \begin{cases} \frac{2^{1 - r/2^{k-1}}}{2^k} & \mbox{if }r < 2^{k-1} \\
\frac{1}{2^k} & \mbox{if }r \ge 2^{k-1}.
\end{cases}$$
Essentially, for the first half of the range from $2^k$ to $2^{k+1}$, $a_n$ decreases from $\frac{1}{2^{k-1}}$ to $\frac1{2^k}$ geometrically, by factors of $2^{-1/2^{k-1}}$. For the second half of that range, $a_n$ stays at $\frac1{2^k}$.
It is identically true that $\frac{a_{2n}}{a_n} = \frac12$. Moreover, if $n \ge 2^k$, then $2^{-1/2^{k-1}} \le \frac{a_{n+1}}{a_n} \le 1$, so $\frac{a_{n+1}}{a_n} \to 1$.
However, when $n = 2^k$, $\frac{a_{3n}}{a_n} = \frac14$, while $\frac{a_{9n}}{a_{3n}} = \frac1{2^{5/4}}$, so $\frac{a_{3n}}{a_n}$ does not converge.
You might complain that the sequence $a_n$ is not strictly decreasing. If this is a problem, just replace $a_n$ by $a_n' = a_n\left(1 + \frac1n\right)$. We have:

*

*$\frac{a'_{n+1}}{a'_n} = \frac{a_{n+1}}{a_n} \cdot \frac{1+\frac1{n+1}}{1+\frac1n} = \frac{a_{n+1}}{a_n} \left(1 - \frac1{(n+1)^2}\right)$, which still converges to 1.

*$\frac{a'_{2n}}{a'_n} = \frac{a_{2n}}{a_n} \cdot \frac{1 + \frac1{2n}}{1 + \frac1n} = \frac{a_{2n}}{a_n} \left(1 - \frac1{2n+2}\right)$, which still converges to $\frac12$.

*$\frac{a'_{3n}}{a'_n} = \frac{a_{3n}}{a_n} \cdot \frac{1 + \frac1{3n}}{1 + \frac1n} = \frac{a_{3n}}{a_n} \left(1 - \frac2{3n+3}\right)$, which still does not converge to anything.

*Since we already had $a_{n+1} \le a_n$, we now have $a'_{n+1} = a_{n+1} \left(1 + \frac1{n+1}\right) \le a_n \left(1 + \frac1{n+1}\right) < a_n \left(1 + \frac1n\right) = a'_n$.

If the limit $\frac{a_{3n}}{a_n}$ does exist, then we may proceed as in Andras's answer to show that it must equal $\frac13$:
If $\frac{a_{3n}}{a_n} \to c$, then $\frac{a_{3^kn}}{a_n} \to c^k$ for any $k$, but we can bound $\frac{a_{3^kn}}{a_n}$ between $\frac{a_{2^\ell n}}{a_n}$ and $\frac{a_{2^{\ell+1} n}}{a_n}$ for $\ell$ such that $2^\ell < 3^k < 2^{\ell+1}$ (i.e., $\ell = \lfloor k \log_2 3\rfloor$). These two ratios converge to $\frac{1}{2^{\ell}}$ and $\frac1{2^{\ell+1}}$, so we get that $2^{-\ell/k} < c < 2^{-(\ell+1)/k}$. Taking $k$ arbitrarily large, $\frac{\ell}{k} \to \log_2 3$, so $c$ must be $2^{-\log_2 3} = \frac13$.


Q: struts2 s:property tag: Better way to replace value? I have a POJO whose properties I'm displaying on a JSP using Struts2 property tags:
public Class message
{
    string messageText;
    string messageType;

    //getters and setters, here
}

Text: <s:property value="messageBean.messageText"/>
Type: <s:property value="messageBean.messageType"/>

The object is created either by user input, or reading from a database.  The "messageType" attribute only ever has integer values in it, which are used as keys for a lookup table within the database.
When selecting the "type" values, users are given a radio selection on a previous page, and each option corresponds to an integer.  When I'm displaying the values, I'm currently showing just the integer.  I'd like to show the text that corresponds to the integer, and I would accomplish this by having a key/value lookup method in the action class, and change the code to appear as follows:
//in Action class
public String getTranslatedType()
{
    if (messageBean.getMessageType().equals("12"))
        return "Message for frequent callers.";

    if (messageBean.getMessageType().equals("17"))
        return "Message for first time callers.";
    //etc
}

Text: <s:property value="messageBean.messageText"/>
Type: <s:property value="translatedType"/>

Is there a better way to do this?
This does not seem to work:
Type: <s:property value="Utility.getTranslatedText(messageBean.messageType)"/>

Is there a syntax for calling a static utility method from within the property tag?

A: I'm not sure exactly what you are trying to achieve.  Why would you prefer to use a static call instead of accessing data from the ValueStack (which is where the action properties are accessed from)?  It really is best to avoid static calls if possible and stick to the intended design of the framework and access data from the ValueStack/action.
If you just wish to separate the logic from your action, you could change your method to:
public String getTranslatedType() {
   return Utility.getTranslatedText(getMessageBean().getMessageType());
}

Or are you wishing to have the translated text appear on the page dynamically?  If so, perhaps you could use Javascript and JSON to achieve your goal with something along the lines of the following steps:

*

*Place your messageType integers (as the keys) and your translatedText Strings (as the values) into a map along the lines of messageTypeText.put(12, "Message for frequent callers.");

*Convert this to JSON using something like (new JSONObject(messageTypeText)).toString();

*Then expose this to the client by any of a number of ways such as var messageTypeText = <s:property value="messageTypeText"/>;

*Bind a javascript method to the messageType radio button that then displays the translated text by accessing it from the javascript map/array using the value of the currently selected radio/messageType.  I could give more detail on this approach, but I don't want to waste my time if its not what you're looking for!  :)


Q: How to disable zuul decoding encoded slash %2F? I'm using a solution with Spring Cloud Zuul and Eureka. The REST application register itself with Eureka and Zuul provide access to the Service via Eureka Service Discovery.
I had to configure the REST application to accept encoded slash in URL with:
System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");

To accept encoded dash in the Spring Boot REST application, and:
@Bean
public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
    DefaultHttpFirewall firewall = new DefaultHttpFirewall();
    firewall.setAllowUrlEncodedSlash(true);
    return firewall;
}

@Override
public void configure(WebSecurity web) throws Exception {
    web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
}

In WebSecurityConfigurerAdapter for the same purpose. And:
@Override
public void configurePathMatch(PathMatchConfigurer configurer) {
    UrlPathHelper urlPathHelper = new UrlPathHelper();
    urlPathHelper.setUrlDecode(false);
    configurer.setUrlPathHelper(urlPathHelper);
}

In WebMvcConfigurer to skip decoding url encoded characters.
After that, the REST application alone started to answer normally the request with the encoded slash. When I connected the REST application with Zuul, the gateway, the problem happened with slash encoded happens again. I did the same configuration of REST application with Zuul plus the property decode-url: false in application.yml and the combination of Zuul and REST application worked again.
When I added the Service Discovery/Service Registration solution with Eureka, the problem begun happen again. I searched a lot, even cloned the Spring Cloud Netflix Eureka Server 2.1.0.RELEASE and Eureka Core 1.9.8 but couldn't find any solution.
How to disable the decoding of slash in Eureka encoded in URL?

A: The solution is to change Spring Boot version from 2.1.3.RELEASE to 2.1.4.RELEASE in the gateway.


Q: Using the word "worthwhile" alone If I want to describe something in a sentence like:

We believe that doing X is worthwhile.

In particular I mean can I use worthwhile without following it with a noun like endeavor or something else.

A: Yes. Worthwhile, like most adjectives (not all) can be used predicatively as well as attributively.


Q: How do I compute the individual terms of a polynomial to the power of -1? If my polynomial $p$ is: $x+1$, obviously $p^{-1} = \frac{1}{x+1}$.  Is it possible for me to split $\frac{1}{x+1}$ into a sum of two terms? In other words, is there an algorithm to write $p^{-1}$ as another polynomial other than just writing $\frac{1}{p}$?

A: It is not possible to write $1/(x+1)$ as a polynomial in $x$.  There are many ways to see this, probably the easiest is that the polynomial would give a value at $x=-1$, but $1/(x+1)$ has no value at $-1$.

A: For your case, it is impossible to write $\dfrac{1}{x+1}$ as a combination of two fractions. But you can with fractions that have denominators with degree $2$ or higher. You do this using partial fraction decomposition. For example, the fraction
$$\dfrac{1}{x^2-5x+6}$$
can be "split up" into two terms. What you need to do is factor the denominator, and split the fraction apart. Let me show you what I mean.
$$\dfrac{1}{x^2-5x+6}$$
$$=\dfrac{1}{(x-2)(x-3)}$$
$$=\dfrac{A}{x-2}+\dfrac{B}{x-3}$$
You have to assume variables $A$ and $B$ (they are both constants). Before I forget, do not assume that you are always going to be doing partial fractions this way. There are different ways for different kinds of fractions. But for this example, we have all linear, non-different factors. So it is ok to just assume the constants $A$ and $B$. For linear factors, there will be no $x$ in the numerator.
Now we multiply both $\dfrac{A}{x-2}+\dfrac{B}{x-3}$ and $\dfrac{1}{x^2-5x+6}$ by $x^2-5x+6$. This will eliminate all of our denominators.
$$\dfrac{A(x-2)(x-3)}{x-2}+\dfrac{B(x-2)(x-3)}{x-3}=\dfrac{1(x^2-5x+6)}{x^2-5x+6}$$
$$A(x-3)+B(x-2)=1$$
We have to solve for $A$ and $B$. To do this, let's pick values of $x$ that will eliminate one of the two. Let's pick $x=3$ to eliminate $A$ first.
$$A(3-3)+B(3-2)=1$$
$$1B=1$$
$$B=1$$
I do not think you can just plug the value of $B$ back into the equation to find $A$. Instead, we have to pick a value of $x$ to eliminate $B$. This time, we will pick $x=2$.
$$A(2-3)+B(2-2)=1$$
$$A(-1)=1$$
$$A=-1$$
Final answer:
$$\dfrac{1}{x^2-5x+6}=\dfrac{-1}{x-2}+\dfrac{1}{x-3}$$
That can be rewritten as:
$$\boxed{\dfrac{1}{x^2-5x+6}=\dfrac{1}{x-3}-\dfrac{1}{x-2}}$$
Conclusion: Yes it is possible to write rational expressions as a combination of 2 or more fractions with partial fraction decomposition.

If you want to learn more about partial fractions, look it up on Google. I hope my answer helped you.
More information about partial fractions if you want to know:

Partial fraction decomposition becomes very important later on in calculus. To start, let's decompose $\dfrac{3x+20}{x^2+4x}$ into partial fractions.
$$\dfrac{3x+20}{x^2+4x}$$
$$=\dfrac{3x+20}{x(x+4)}$$
Split into two fractions with constants $A$ and $B$ as the numerators:
$$\dfrac{A}{x}+\dfrac{B}{x+4}=\dfrac{3x+20}{x^2+4x}$$
Get rid of the denominators...
$$\dfrac{A(x)(x+4)}{x}+\dfrac{B(x)(x+4)}{x+4}=\dfrac{(3x+20)(x^2+4x)}{x^2+4x}$$
$$A(x+4)+Bx=3x+20$$
This time we will not use the number-substitution to eliminate the variables one at a time, as that method doesn't always work. Instead we will expand the left hand side of the equation.
$$A(x+4)+Bx=3x+20$$
$$Ax+4A+Bx=3x+20$$
Now, we will do something called equating the coefficients. This means that because $Ax+Bx=3x$, then $A+B=3$. Likewise, $4A=20$ (because both do not have an $x$ attached to it). We can easily find out that $A=5$ from simple algebra. Now we will substitute the value of $A$ into $A+B=3$ to solve for $B$.
$$5+B=3$$
$$B=-2$$
The partial fraction decomposition for $\dfrac{3x+20}{x^2+4x}$ is:
$$\boxed{\dfrac{3x+20}{x^2+4x}=\dfrac{5}{x}-\dfrac{2}{x+4}}$$
When integrating this rational expression, it is much easier to integrate $\dfrac{5}{x}-\dfrac{2}{x+4} \ dx$ than it is to integrate $\dfrac{3x+20}{x^2+4x} \ dx$. It is possible to integrate the latter by itself, but it requires many steps, and can get complicated. Let me show you how to integrate the rational expression.
$$\int \dfrac{3x+30}{x^2+4x} \ dx$$
$$=\int \dfrac{5}{x}-\dfrac{2}{x+4} \ dx$$
$$=\int \dfrac{5}{x} \ dx - \int \dfrac{2}{x+4} \ dx$$
$$=5\int \dfrac{1}{x} \ dx - 2\int \dfrac{1}{x+4} \ dx$$
$$=5\ln (x) - 2\ln (x+4) + C$$
Final Answer:
$$\boxed{\int \dfrac{3x+20}{x^2+4x} = 5\ln (x) - 2\ln (x+4) + C}$$

A: If $\quad|x|<1,\quad$ then $\quad\dfrac1{1-x}=\displaystyle\sum_{n=0}^\infty x^n.\quad$ Now, exchange x with $-x$.


Q: Sudden disconnection of second screen and usb keyboard - Ubuntu 20.04 Hardware:
Lenovo Thinkpad x250 with Dokingstation
Intel® Core™ i5-5300U CPU @ 2.30GHz × 4,
Mesa Intel® HD Graphics 5500 (BDW GT2),
64 Bit
External Keyboard connected via USB (Dokingstation)
Second Screen connected with VGA (Dokingstation),
Ubuntu 20.04
Problem:
Suddenly the extended (second) Screen disconnects and so does the USB-Keyboard and the Mouse. This happens sometimes 2 min. sometimes 20 min. or more after Startup while working and on the ext. Screen "No Signal" appears. The primary Screen and Keyboard on the Notebook keeps on working fine. The Mouse is connected through USB to the Dokingstation too, but the mouse keeps on being connected and then a minute or so later disconnects, and this repeats constantly. Sometimes the Keyboard is reconnected some times for longer disconnected. The ext. Screen never reconnects.
I did switch from gdm3 to lightdm, but no change.
This happened since the Update from 19.10 to 20.04.
Any Ideas?

A: I swiped the Harddrive, made a fresh installation with 20.04 and all is working fine now. So the Live-Update from 19.10 to 20.04 may have not worked thoroughly fine. So doing it by iso may work also for others.


Q: can not resolve method getProjection() and getMapCenter() i am implementing long click to get latlang on mapview,
i referred this tutorial. but i am getting error
here is my code:
import com.google.android.gms.vision.barcode.Barcode;
public class MyCustomMapView extends MapView {

    public interface OnLongpressListener {
        public void onLongpress(MapView view, Barcode.GeoPoint longpressLocation);
    }
    static final int LONGPRESS_THRESHOLD = 500;
    private Barcode.GeoPoint lastMapCenter;
    private Timer longpressTimer = new Timer();
    private MyCustomMapView.OnLongpressListener longpressListener;

    public MyCustomMapView(Context context) {
        super(context);
    }

    public void setOnLongpressListener(MyCustomMapView.OnLongpressListener listener) {
        longpressListener = listener;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        handleLongpress(event);

        return super.onTouchEvent(event);
    }
    private void handleLongpress(final MotionEvent event) {

        if (event.getAction() == MotionEvent.ACTION_DOWN) {
            // Finger has touched screen.
            longpressTimer = new Timer();
            longpressTimer.schedule(new TimerTask() {
                @Override
                public void run() {
                    Barcode.GeoPoint longpressLocation = getProjection().fromPixels((int)event.getX(),
                            (int)event.getY()); <--here -->

                    longpressListener.onLongpress(MyCustomMapView.this, longpressLocation);
                }

            }, LONGPRESS_THRESHOLD);

            lastMapCenter = **getMapCenter()**;
        }

        if (event.getAction() == MotionEvent.ACTION_MOVE) {

            if (!getMapCenter().equals(lastMapCenter)) {
                longpressTimer.cancel();
            }

            lastMapCenter = getMapCenter();<-- here -->
        }

        if (event.getAction() == MotionEvent.ACTION_UP) {
            longpressTimer.cancel();
        }

        if (event.getPointerCount() > 1) {
            longpressTimer.cancel();
        }
    }
}

here my getProjection() and getMapCenter() cant resolve, i want to know why its happening, is this method deprecated, or what method i have to use instead,
and i also want to know that why its barcode.GeoPoint,
why my program importing
import com.google.android.gms.vision.barcode.Barcode;     instead of
import com.google.maps.GeoPoint;

A: You can implement GoogleMap.OnMapClickListener and  GoogleMap.OnMapLongClickListener to achieve this
public class CreateFenceActiviy extends AppCompatActivity implements GoogleMap.OnMapClickListener, GoogleMap.OnMapLongClickListener{
    private GoogleMap mGoogleMap;
    private SupportMapFragment mMapFragment;
    private ArrayList<double[]> mLatLongArray =null;
    private Polygon mPolygon;
    private PolygonOptions mPolygonOptions;

     @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.create_fence_activity);
        mLatLongArray = new ArrayList<double[]>();
        if (mGoogleMap == null) {
                mMapFragment = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map_create_fence));
                mGoogleMap = mMapFragment.getMap();
                mGoogleMap.setOnMapClickListener(this);
                mGoogleMap.setOnMapLongClickListener(this);
                mGoogleMap.setOnMarkerClickListener(this);
                isMarkerClicked = false;
            }

    }
    @Override
    public void onMapClick(LatLng point) {
        if(mGoogleMap != null){
            mGoogleMap.animateCamera(CameraUpdateFactory.newLatLng(point));
            isMarkerClicked = false;
        }
    }

    @Override
    public void onMapLongClick(LatLng point) {
        if(mGoogleMap != null) {
            mGoogleMap.addMarker(new MarkerOptions().position(point).title(point.toString()));
            double latitudeNew = point.latitude;
            double longitude = point.longitude;
            mLatLongArray.add(new double[]{latitudeNew, longitude});
            isMarkerClicked = false;
        }
    }
}

XML for Map view will contain this component
<fragment xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/map_create_fence"
        class="com.google.android.gms.maps.SupportMapFragment"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />


Q: Get list of values from grandchildren records I'm trying to access the grandchildren records in a list to avoid duplicate records.  In this example, a tag can only be used once across articles for a given author.  I will use the resulting list of grandchildren records in my clean function to return validation errors.
class Article(models.Model):
    tag = models.ManyToManyField(Tag)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

class Tag(models.Model):

class Author(models.Model):

Right now I can do this:
print(author.articles.first().tag.first())
Travel

I'd like to be able to use something like author.articles.tags.all() to return the list and check the submitted form against it to raise a ValidationError message to the user.
How can this be done efficiently with the basic Many-to-Many setup without creating an intermediate table for the tag relationships?  This is solely in the Admin interface, in case that matters at all.

A: i come from the link you posted on upwork,
the way i understand your question,
what you want to achieve seems to be impossible ,
what i think can work , is to fetch articles related to the author, with their corresponding tags,
after that they are retrieved you do filtering and remove duplicates.
otherwise the tag has nothing to connect it with the author,,

A: The Django ORM is pretty cool when you get used to it, but regular SQL is pretty cool too
# created_at, updated_at, name and tag_val are variables I
# added due to my slight ocd lol

class Author(models.Model):
    name = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

class Tag(models.Model):
    tag_val = models.CharField(max_length=255)
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

class Article(models.Model):
    author = models.ForeignKey(Author,related_name='articles', on_delete=models.CASCADE)
    tags = models.ManyToManyField(Tag, related_name='articles')
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

I can write my query like this, assuming the variable 'author' has been assigned an Author object instance, and get a list of dictionaries [{'tags':1},{'tags':2}] where the value is the auto generated primary key id of the Tag object instance
author.articles.values('tags').distinct()

A: I'm so jealous that's a great answer @since9teen94
Be aware, I will not base my answer in the easiest solution but how we model reality (or how we should do it).
We put tags after things exists right?
In that order I will make your life horrible with something like this:
from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=30, null=False)

class Article(models.Model):
    name = models.CharField(max_length=30, null=False)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)

class Tag(models.Model):
    name = models.CharField(max_length=30, null=False, unique=True)
    articles = models.ManyToManyField(Article)

but believe me you don't want to follow this approach it will make your work harder.
You can search for Articles based on Tags directly
Tag.objects.filter(name='Scify').first().articles.all() # name is unique

The real issue with this is that the reverse lookup is really complex (I mean.. get ready for debug)
Article.objects.filter(
    id__in=list(
        Tag.objects.filter(name='Scify').first().articles.values_list('id', flat=True)
    )
)

I am sure this does not solve your problem and I don't like complex code for no reason but if you're open to suggestions I don't mind to think different and add some options
Edit:
About the author and clean repeated tags.. well you don't have to deal with that and if you want to find all Tag your author has you could loop the tags
for tag in Tag.objects.all():
    if tag.articles.filter(author__name='StackoverflowContributor'):
        print(tag.name)
# > Scify

I am just saying that there are options not that this is the best for you but don't be afraid of the terminal, it's really cool


Q: Multiple filter in single function using angularjs I try to filter two values like this | filter:{voucher_type: selectedName } | filter:{voucher_type: both }
Here both is "B" and selectedName "P or R". Below code work only one filter only.
I want to combine this two filter values together and show the result like voucher_type B + P (Or) R.

    <link rel="stylesheet" type="text/css" href="css/bootstrap.min.css"/>
    <title>search</title>

            <form class="form-search" ng-controller="autocompleteController">
              Selected Ledger: {{selectedLedgers}}

              <input type="text" ng-model="both">

select voucher :<select ng-model="selectedName" ng-options="x for x in names">
                </select>

              <input type="text" ng-model="selectedLedgers" placeholder="Search Ledger" typeahead="c as c.ledger_id +  '-'+ c.ledger_name for c in producers | filter:$viewValue| limitTo:20 | filter:{voucher_type: selectedName1 } | filter:{voucher_type: both }" typeahead-min-length='2' typeahead-on-select='onSelectPart($item, $model, $label)' typeahead-template-url="search" class="form-control" style="width:350px;">

            </form>

Find my demo project here https://jsfiddle.net/basilbkodakk/sk549x4m/2/ .there have 3 company x,y,z .list box show x and y . z is common for x,y .that filter method in angularjs


Q: Should I still respond to html if view is rendered with javascript? I have a Rails application integrated with react, my views are rendered with react, including the html (JSX). I noticed that I had a few format.html responses from back when my views were regular erb views, now that they are not, should I still respond to html just in case (even  though I don't see how a user can use my app if they javascript have disabled)?
Example :
 def destroy
    @comment.destroy
    respond_to do |format|
      format.json { head :no_content }
      format.html { redirect_to @question, notice: 'Comment was deleted.' }
    end
  end

Can I get rid of the html responses?

A: Whether to keep it or not is a personal choice. I sometimes do, but fewer LOC makes for cleaner code. To remove it you have several options. You can leave the respond_to as is and just remove the html eg:
def destroy
  @comment.destroy
  respond_to do |format|
    format.json { head :no_content }
  end
end

but you can also remove the respond_to from each action (even fewer LOC) with something like this:
# put this LOC at the top of your controller, outside of any action
respond_with :json

# then each action is much simpler... you just assume it's always json
def destroy
  @comment.destroy
  head :no_content
end


Q: Python: how to deal with several .pyd dependencies with the same name? I have in my python workspace two Modules which need sip.pyd
Module1.pyd needs sip.pyd (which implements v 8.0-8.1)
Module2.pyd needs sip.pyd (another file, that implements v6.0)
So I can't just choose the newer one, it doesn't work: I have to keep them both!
(RuntimeError: the sip module implements API v6.0 but the fbx module requires API v8.1)

How can I import a module in .pyd extension (a python dll, not editable), and specify which sip.pyd to source?
As for a workaround, I manage to do that:

*

*One sip.pyd is in my root site-packages location.

*If I have to import the module that need the other sip.pyd, I remove root path form sys.path, and I append the precise folder path where the other sip.pyd are.

*I can import my Module and restore previous sys.path.

A: VirtualEnv is done to handle those case.

virtualenv is a tool to create isolated Python environments.

Using virtualenv, you will be able to create 2 environements, one with the sip.pyd in version 8.x another in version 6.0

A: Assuming you don't have a piece of code needing both files at once. I'd recommend the following:

*

*install both files in 2 separate directories (call them e.g. sip-6.0 and sip-8.0), that you'll place in site-packages/

*write a sip_helper.py file with code looking like
sip_helper.py contents:
import sys
import re
from os.path import join, dirname
def install_sip(version='6.0'):
    assert version in ('6.0', '8.0'), "unsupported version"
    keep = []
    if 'sip' in sys.modules:
       del sys.modules['sip']
    for path in sys.path:
        if not re.match('.*sip\d\.\d', path):
            keep.append(path)
    sys.path[:] = keep # remove other paths
    sys.path.append(join(dirname(__file__), 'sip-%s' % version))

*

*put sip_helper.py in site_packages (the parent directory of the sip-6.0 and sip-8.0 directories)

*call sip_helper.install_sip at the startup of your programs

A: I don't know if that works (if a module's name has to match its contents), but can't you just rename them to sip6.pyd resp. sip8.pyd and then do
if need6:
    import sip6 as sip
else:
    import sip8 as sip

?


Q: Draw polygon with hole inside I need to draw a rectangle polygon with a rectangle hole inside. I found this piece of code but I couldn't manage to understand how I can modify to meet my requirement.
 figure()
 p  = [0 0; 0 1; 1 1; 1 0]; %ccw
 pp = [0 0; 1 0; 1 1; 0 1]; %cw
 ph = p + [1.2 0];
 # add hole
 ph(end+1,:) = nan;
 ph = [ph; (pp-[0.5 0.5])*0.5+[1.7 0.5]];
 po = polygon2patch (ph);
 patch (po(:,1), po(:,2), 'b', 'facecolor', 'c');
 axis image

A: The polygon2patch function certainly seems useful, but maybe for only drawing two rectangles, you could also use just two patch commands, and simply set the inner rectangle, i.e. the hole, to white foreground color, like so:
outer = [0 0; 2 0; 2 1; 0 1];
inner = [0.4 0.2; 1.6 0.2; 1.6 0.8; 0.4 0.8];
patch(outer(:, 1), outer(:, 2), 'c');
patch(inner(:, 1), inner(:, 2), 'w');
axis equal;

This will produce such an output:

Hope that helps!


Q: Grouping and Aggregating on multiple time series Im new to python and pandas and have some basic question about how to write a short function which takes a pd.Dataframe and returns relative values grouped by month.
Example data:
import pandas as pd
from datetime import datetime
import numpy as np

date_rng = pd.date_range(start='2019-01-01', end='2019-03-31', freq='D')
df = pd.DataFrame(date_rng, columns=['date'])
df['value_in_question'] = np.random.randint(0,100,size=(len(date_rng)))
df.set_index('date',inplace=True)
df.head()

       value_in_question
date
2019-01-01  40
2019-01-02  86
2019-01-03  46
2019-01-04  75
2019-01-05  35

def absolute_to_relative(df):
    """
    set_index before using
    """
    return df.div(df.sum(), axis=1).mul(100)

relative_df = absolute_to_relative(df)

relative_df.head()

       value_in_question
date
2019-01-01  0.895055
2019-01-02  1.924368
2019-01-03  1.029313
2019-01-04  1.678228
2019-01-05  0.783173

Rather than taking the column sum and devide each row by that,
I would like to have the sum groupby each month. The final df should have the same
shape and form but the row values relate to sum of the month.
old:
             value_in_question
date
"2019-01-01" value/colum_sum * 100

new:
            value_in_question
date
"2019-01-01" value/month_sum * 100

So I tried the following, which returns NA for value_in_question:
def absolute_to_relative_agg(df, agg):
    """
    set_index before using
    """
    return df.div(df.groupby([pd.Grouper(freq=agg)]).sum(), axis=1)

relative_df = absolute_to_relative(df, 'M')
      value_in_question
date
2019-01-01  NaN
2019-01-02  NaN
2019-01-03  NaN
2019-01-04  NaN
2019-01-05  NaN

A: Use GroupBy.transform instead aggregation for Series/DateFrame with same DatatimeIndex like original, so possible division:
def absolute_to_relative_agg(df, agg):
    """
    set_index before using
    """
    return df.div(df.groupby([pd.Grouper(freq=agg)]).transform('sum'))

relative_df = absolute_to_relative_agg(df, 'M')

Another way for call function is DataFrame.pipe:
relative_df = df.pipe(absolute_to_relative_agg, 'M')

print (relative_df)
           value_in_question
date
2019-01-01           0.032901
2019-01-02           0.045862
2019-01-03           0.048853
2019-01-04           0.008475
2019-01-05           0.041376
                      ...
2019-03-27           0.062049
2019-03-28           0.002165
2019-03-29           0.048341
2019-03-30           0.007937
2019-03-31           0.015152

[90 rows x 1 columns]

A: For the sums, you can groupby the index month:
In [31]: month_sum = df.groupby(df.index.strftime('%Y%m')).sum()
    ...: month_sum
    ...:
Out[31]:
        value_in_question
201901               1386
201902               1440
201903               1358

You can then use .map to align the month with the correct rows of your DataFrame:
In [32]: map_sum = df.index.strftime('%Y%m').map(month_sum['value_in_question'])
    ...: map_sum
    ...:
Out[32]:
Int64Index([1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386,
            1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386,
            1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1386, 1440, 1440,
            1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440,
            1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440, 1440,
            1440, 1440, 1440, 1440, 1358, 1358, 1358, 1358, 1358, 1358, 1358,
            1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358,
            1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358, 1358,
            1358, 1358],
           dtype='int64')

Then you just need to do the division:
In [33]: df['value_in_question'].div(map_sum)
Out[33]:
date
2019-01-01    0.012987
2019-01-02    0.018759
2019-01-03    0.000000
2019-01-04    0.056277
2019-01-05    0.019481
                ...
2019-03-27    0.031664
2019-03-28    0.007364
2019-03-29    0.050074
2019-03-30    0.033873
2019-03-31    0.005155
Name: value_in_question, Length: 90, dtype: float64

A: Use Grouper with freq='M'.
The code is:
relative_df = df.groupby(pd.Grouper(freq='M'))\
    .value_in_question.apply(lambda x: x.div(x.sum()).mul(100))

It returns a Series with index the same like in original DataFrame
and values equal to relative value_in_question for the current month.


Q: Can anyone solve the error in Spark databricks My SQL request:
SELECT Incident Number FROM fireIncidents where Incident Date='04/04/2016'

Error in SQL statement:

ParseException:
mismatched input 'Date' expecting {, ';'}(line 1, pos 57)

A: You have a space in Incident Date column.
If you want spark to know the column has space, use ` symbol in start and end of col.
Same as Incident Number col.
SELECT `Incident Number` FROM fireIncidents where `Incident Date`='04/04/2016'

If your Incident Date col is a date, you can cast it to spark format, use
select `Incident Date`, to_date(`Incident Date`, 'dd/MM/yyyy') FROM fireIncidents""").show()

which yields
+-------------+----------------------------------+
|Incident Date|to_date(Incident Date, dd/MM/yyyy)|
+-------------+----------------------------------+
|   04/04/2016|                        2016-04-04|
|   04/04/2016|                        2016-04-04|
|   04/04/2016|                        2016-04-04|
+-------------+----------------------------------+


Q: How to use window lag function to partition the data with multiple sensor types I'm, trying to use the postgres LAG function to calculate a difference in absolute time between two sampling dates for each sensor in the system.
The best I have come up with is to use WINDOW LAG function to calculate a difference from earlier line. However there are two problems with this. The first value is always null. I'd guess I can solve this using a CASE function. Second is that it does not take each sensor value explicitly.
SELECT
    seq_id, stream_id, sensor, "timestamp", oper_value
    "timestamp" - LAG("timestamp",1) OVER (ORDER BY "timestamp") delta
    FROM public.mt_events
    where "type" = 'operational_value_event'
    limit 100;

The data is logged when threshold breached (including hysteresis) and therefore some values are changed more often than other. There are no fixed intervals in when the data is logged.
The end goal to to get a value that have atleast a certain amount of time difference.
Example data:
id stream_id sensor oper_value timestamp
44 100000000    GT1         17 2018-05-16 13:36:21.899821+00
45 100000000    GT2         44 2018-05-16 14:36:21.000000+00
88 100000000    GT1         26 2018-05-18 12:33:22.000000+00
94 100000000    GT1         99 2018-05-18 12:33:23.002000+00

For example if a selection of data with at least time difference of 5 minutes I would like to get the following values:
id stream_id sensor oper_value timestamp
44 100000000    GT1         17 2018-05-16 13:36:21.899821+00
45 100000000    GT2         44 2018-05-16 14:36:21.000000+00
88 100000000    GT1         26 2018-05-18 12:33:22.000000+00

The last GT1 is filtered out since the difference was less than 5 minutes.
Is there any way of doing this effectively using a SQL statement or do I need to write a stored procedure?
Cheers,
 Mario

A: You can use the three-argument form of lag() with partition by:
("timestamp" -
 LAG("timestamp", 1, "timestamp") OVER (PARTITION BY sensor ORDER BY "timestamp")
) as delta

For your ultimate problem, the NULL value for the first row doesn't matter.  You can solve the problem using a subquery:
select *
from (select seq_id, stream_id, sensor, "timestamp", oper_value ,
             lag("timestamp") over (partition by sensor order by timestamp) as prev_timestamp
      from public.mt_events
      where "type" = 'operational_value_event'
     ) t
where delta is null or
      prev_timestamp < timestamp - interval '5 minute';


Q: add typings for missing method (from a npm package) I'm using the package @types/cropperjs
unfortunately it is behind the current cropper.js versions and lacks the method scale.
So far I just manually added the missing method to the d.ts file under node_modules (this is obviously a bad idea, so don't do that! it was just a temp. fix)
I tried to merge the definitions from node_modules with my own declaration.
declare class cropperjs {

  /**
   * Scale the image.
   *
   * @param scaleX The scaling factor to apply on the abscissa of the image.
   * When equal to 1 it does nothing. Default is 1
   * @param scaleY The scaling factor to apply on the ordinate of the image.
   * If not present, its default value is scaleX.
   */
   scale(scaleX: number, scaleY?: number): void;
}

export = cropperjs;
export as namespace Cropper;

the typings from the DefinitlyTyped Repo can be found on github (it looks similar but is too big to display here)
Here's how I import cropper in an angular component.
import * as Cropper from 'cropperjs';
Here's my tsconfig.json (parts of it)
 "typeRoots": [
  "node_modules/@types",
  "node_modules/@angular",
  "src/typings"
],
"types": [
  "jasmine",
  "node",
  "karma",
  "webpack",
   "cropperjs"
]

I tried it with my custom typings folder an with the tripple slash reference notation.
But I can't figure out how I can successfully merge my and DefinitlyTyped's definitions so I can use cropperjs without having to fiddle around in node_module
P.S.
I already opened an issue with the updated definitions on github (no pull request, because at the time had almost no knowledge of git).

A: As far as I know, you can't do that in typescript. Typescript has the concept of declaration merging, which is what allows us to extend types other people wrote, and you can merge interface and namespaces, but not classes. Look here.
If the @types/cropperjs would have been written using interfaces, you could have extended that interface using your own declaration.
Here is an ugly hack you can do for now:
import * as Cropper from 'cropperjs';

interface MyCropper extends Cropper {
  scale(scaleX: number, scaleY?: number): void;
}

function CreateCropper(dom: HTMLImageElement, options: Cropper.CropperOptions): MyCropper {
  return new Cropper(dom, options) as MyCropper;
}

casting is always ugly, but at least you hide it in one place, I think it's reasonable...

A: Just wanted to add another possible "solution". I say "solution" because it's in my opinion quite ugly but then again it's a workaround.
After seeing and reading (see Aviad Hadad's answer) that class merging is not possible and read about typescripts node module resolution
Basically if you import an non-relative path like import * as Cropper from 'cropperjs typescript will look for the appropriate files in a folder named node_modules and it starts in the directory in which the file with the import statement resides. It then traverses up (example taken from the typescript documentation)

*

*/root/src/node_modules/moduleB.ts

*/root/node_modules/moduleB.ts

*/node_modules/moduleB.ts (I assume that's the global node_modules directory)

Since typescript will also look for d.ts files I copied the whole index.d.ts from the @types/cropperjs package, renamed it to cropperjs.d.ts and put it in a folder named /root/src/node_modules. (and added the missing method)
if you trace the resolution with tsc --traceResolution you'll see that typescript will take the d.ts file from the custom node_modules directory.
The advantage with this solution is that you don't have to touch your code. As soon as @types/cropperjs has updated the missing method you can just delete your custom node_modules directory and everything will still work.
Disadvantage is you have to copy and paste code around.


Q: How to remove unused blocks of code from a source code file? Let’s suppose I have a bunch of source code files (C or Delphi, i.e., *.c or *.pas). I want to purge them of blocks of text which are not used in the compilation. Those blocks are:

*

*Comments. They can be removed with regexp. (But, for example, Delphi
uses the preprocessor directives which look like comments (“{ is it
a comment or a directive? }”), so the regexp would not be trivial.)

*But the most tricking part is the blocks of code which are excluded
from the compilation with #ifdef. These blocks have to be removed
too.

So, the question is: “Is there a way to do it with some program or script?” Let’s suppose there is a program that can be given a source code file and a list of defined symbols to distinguish unused blocks of code, and it would spit out the cleansed file I want to get.


Q: Quasar Vue: Set static width content on Grid Style I'm very new in dynamic web programming but I get a little problem with Quasar Grid Gutter.
I have string on array with different word and length, I want to show them in Button with grid style. So I use Grid Gutter to build this. But I want the size of card is always static (etc width: 200), so add style="width: 100px". But if width too small and text length too long, the height is getting weird. If add height:50px the width is not work. Here is a codepen sample.
I try the Offset too but I can set the padding between Button.


Q: Blackberry SQLite optimal performance I've overcome many hurdles while trying to work with SQLite on Blackberry. Now I've reached the point where everything seems to work fine and I'm looking for ways to speed up my queries.
Sometimes my app retrieves a lot of data from a web service call, this data is parsed and stored into my database. A lot of DELETE, INSERT and UPDATE going on. The database calls seem to be taking a lot of time.
I would like to know some best practices when dealing with SQLite. Preferably from people who have experience with it on the Blackberry platform specifically. Any tricks to speed up DELETEs or INSERTs etc....
Links to good tutorials would be great. Or some snippets of useful code even better.
Thanks in advance.
EDIT:
Here is some sample code from Blackberry using transactions.
import net.rim.device.api.ui.*;
import net.rim.device.api.ui.component.*;
import net.rim.device.api.ui.container.*;
import net.rim.device.api.database.*;
import net.rim.device.api.io.*;
public class UsingTransactions extends UiApplication
{
public static void main(String[] args)
{
    UsingTransactions theApp = new UsingTransactions();
    theApp.enterEventDispatcher();
}
public UsingTransactions()
{

}
}

class UsingTransactionsScreen extends MainScreen
{
    Database d;
public UsingTransactionsScreen()
{
   LabelField title = new LabelField("SQLite Using Transactions Sample",
   LabelField.ELLIPSIS |
   LabelField.USE_ALL_WIDTH);
   setTitle(title);
   add(new RichTextField(
          "Updating data in one transaction in MyTestDatabase.db."));
   try
   {
      URI myURI = URI.create("file:///SDCard/Databases/SQLite_Guide/" +
          "MyTestDatabase.db");
      d = DatabaseFactory.open(myURI);

      d.beginTransaction();
      Statement st = d.createStatement("UPDATE People SET Age=7 " +
          "WHERE Name='Sophie'");
      st.prepare();
      st.execute();
      st.close();
      st = d.createStatement("UPDATE People SET Age=4 " +
          "WHERE Name='Karen'");
      st.prepare();
      st.execute();
      st.close();
      d.commitTransaction();
      d.close();
 }
 catch ( Exception e )
 {
      System.out.println( e.getMessage() );
      e.printStackTrace();
 }
  }
}

Is there a reason why they're closing the statement every time?? Isn't it better just to close it once at the end (in a Finally block perhaps??).

A: The standard technique is to use a prepared insert statement, inside a loop inside a transaction. That will give you almost optimal efficiency in most instances. It will speed things up by at least an order of magnitude.

A: I personally don't know many blackberry-specific practices, but these seem to be helpful (sorry I couldn't find code snippets):
"Top 8 SQL Best Practices"
"Best Practice: Optimizing SQLite Database Performance"
Hope these help!

A: You should do one thing is that, create different methods for database handling code.
and simply call these methods from your main code and open and close database also in each and every block. It will reduce redundancy and will be better for your future. This will also helps you in your App performance.


Q: Contact form not sending email and no notification working on contact form for my website. All tree form fields are validating correctly somehow the email is not send but looks page is loading again. Can anyone check my code and tell me where could be a problem here. Would like temail to be sent and notification to the user shown.
Contact form:
<form role="form" id="contactForm">

                 <input type="text" class="form-control" name="name" id="name" placeholder="Wpisz swoje imię, nazwisko" required="required">

                <input type="email" class="form-control" name="email" id="email" placeholder="Enter email" required>

            <textarea id="message" name="message" class="form-control" rows="5" placeholder="Enter your message" required></textarea>

        <button type="submit" id="form-submit" class="btn-block">Wyślij wiadomość</button>

Message Submitted!

    </form>

Java sripts within same html file as form:

PHP file (process.php) :
<?php
$name = $_POST["name"];
$email = $_POST["email"];
$message = $_POST["message"];

$EmailTo = "roger@gth.com.pl";
$Subject = "New Message Received";

// send email
$success = mail($EmailTo, $Subject, $message, $email);

// redirect to success page
if ($success){
   echo "success";
}else{
    echo "invalid";
}

?>

for further dicussion:
my top code:
<!DOCTYPE html>

            <meta http-equiv="content-type" content="text/html; charset=UTF-8">

            <title>my site</title>
            <link rel="shortcut icon" href="img/ico.png">

            <meta http-equiv="X-UA-Compatible" content="IE=edge">
            <meta name="viewport" content="width=device-width, initial-scale=1">
            <meta name="description" content="jakiś wyraz">
            <meta name="keywords" content="">
            <meta name="author" content="strona">

            <link href="bootstrap-assets/css/bootstrap.min.css" rel="stylesheet">

            <link href="plugins/owl-carousel/owl.carousel.css" rel="stylesheet">
            <link href="plugins/owl-carousel/owl.theme.css" rel="stylesheet">
            <link href="plugins/owl-carousel/owl.transitions.css" rel="stylesheet">
            <link href="plugins/Lightbox/dist/css/lightbox.css" rel="stylesheet">
            <link href="plugins/Icons/et-line-font/style.css" rel="stylesheet">
            <link href="plugins/animate.css/animate.css" rel="stylesheet">
            <link href="css/main.css" rel="stylesheet">

            <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">

i notice couple errors in console please help me also to fix it.:
error type: SCRIPT5009: '$' is undefined
on this line:
$("#contactForm").validator().on("submit", function (event) {

error type: SCRIPT5009: '$' is undefined
at the end on own.carousel script here:
});

A: You haven't loaded the jQuery library (or at least prior to attempting to use it based on your  tag from above), add:

before useing the $ function.
After jQuery has resolved, remove the syntax error cased by the extra } in your submitForm function -right in between the ) and the ;.


Q: Is addition on $\mathbb{R}$ unique up to automorphism? Consider the set of real numbers $\mathbb{R}$, which we know is the only complete ordered field up to isomorphism.
If we fix the following axioms for the 'addition' operation $\bot:\mathbb{R}^2\to \mathbb{R}$:

*

*Associativity

*Commutativity

*Identity element 0 (not that there exists some 0 element, but that the identity element is actually the canonical 0).

*All elements have their own unique inverse

[this defines an abelian group over the set $\mathbb{R}$ with identity 0]
and finally

*$\bot$ is distributive over multiplication: $\forall a,b,\lambda\in \mathbb{R}, $ $\lambda\cdot (a\bot b)=(\lambda \cdot a) \bot (\lambda \cdot b).$

Do these axioms uniquely determine addition on $\mathbb{R}$ up to automorphism?

The example of $a\bot b := (a^3+b^3)^{1/3}$ shows that these axioms do not uniquely determine addition. However, the automorphism $f(x)=x^3$ makes this operation still effectively the same as addition. The question is whether all operations $\bot$ which adhere to these axioms have an automorphism with addition.
And as a secondary question, if it turns out that they do:

Is the fifth axiom necessary, or is the only abelian group with identity 0 on the real numbers addition (up to automorphism)?

EDIT: The second part has been answered, and the answer is yes, it is necessary.

A: Your axioms do not determine addition uniquely.  Note that if $K$ is any field and $f:\mathbb{R}^\times\to K^\times$ is an isomorphism of the multiplicative groups, then the operation $(x,y)\mapsto f^{-1}(f(x)+f(y))$ (and $(x,0)\mapsto x$, $(0,y)\mapsto y$) will satisfy your axioms, and will only be equivalent to ordinary addition in your sense if $K$ is isomorphic to $\mathbb{R}$ as a field.
Now note that the abelian group $\mathbb{R}^\times$ is not too hard to understand.  It is the direct sum of the subgroups $\{\pm1\}$ and $\mathbb{R}_+$, and $\mathbb{R}_+$ is a vector space over $\mathbb{Q}$ since every positive real number has an $n$th root for any $n$.  More generally, the same description holds for $K^\times$ if $K$ is any ordered field in which every positive element has an $n$th root for any $n$.  Since two $\mathbb{Q}$-vector spaces of the same uncountable cardinality are isomorphic, it follows that if $K$ is any ordered field of the same cardinality as $\mathbb{R}$ in which every positive element has an $n$th root for any $n$, then $K^\times\cong\mathbb{R}^\times$.
However, such a field need not be isomorphic to $\mathbb{R}$, and so can give rise to a different "addition" on $\mathbb{R}$ satisfying your axioms.  For instance, you could take $K$ to be any non-archimedean real-closed field of cardinality $2^{\aleph_0}$ (e.g., the real closure of $\mathbb{R}(x)$ where $x$ is infinitely large).


Q: Nested 'for' loop in Racket shows error 'not a procedure' I have the following code lines to do bubble sort in Racket. I find the syntax correct but it is still showing error:
(define List (list 1 3 5 7 9 2 4 6 8 0))
(define Left  0)
(define Right 0)

(for ([I (range (- (length List) 1))])
  (for ([J (range (+ I 1) (length List))])
    (set! Left  (list-ref List I))
    (set! Right (list-ref List J))

    (when (> Left Right)
      [(set! List (list-set List I Right))
       (set! List (list-set List J Left ))]
    )
  )
)

The error is:
application: not a procedure;
 expected a procedure that can be applied to arguments
  given: #<void>
  arguments...:
   #<void>
  context...:
   /home/jdoodle.rkt:6:2: for-loop
   /home/jdoodle.rkt:5:0: for-loop
   top-level: [running body]
   eval-one-top12
   begin-loop
   loop

Can't guess it out why. I tested it on https://www.jdoodle.com/execute-racket-online but it didn't work.

A: I found the answer, sorted it out. I must add the expression begin for multiple statements after when. Not the double parentheses.
(for ([I (range (- (length List) 1))])
  (for ([J (range (+ I 1) (length List))])
    (set! Left  (list-ref List I))
    (set! Right (list-ref List J))

    (when (> Left Right)
      (begin
        (set! List (list-set List I Right))
        (set! List (list-set List J Left ))
))))

Or just a series of forms after when:
(for ([I (range (- (length List) 1))])
  (for ([J (range (+ I 1) (length List))])
    (set! Left  (list-ref List I))
    (set! Right (list-ref List J))

    (when (> Left Right)
      (set! List (list-set List I Right))
      (set! List (list-set List J Left ))
)))


Q: Phoenix - client requested channel transport error While running my Phoenix app, I suddenly noticed an error being logged:
The client's requested channel transport version "2.0.0" does not match server's version requirements of "~> 1.0"
It appears after starting the server with mix phoenix.server:
[info] Running MyApp.Endpoint with Cowboy using http://localhost:4000
21 Nov 13:47:19 - info: compiled 4 files into app.js, copied robots.txt in 2.3 sec
[error] The client's requested channel transport version "2.0.0" does not match server's version requirements of "~> 1.0"

and then continues to log the error message every 10 seconds or so, regardless of whether or not I'm making any requests to the server.  Despite this, the app seems to run fine, but it'd be great to resolve this.
Can anyone shed any light on why this would've suddenly started happening, and what I can do to fix it?
Here's some config info from mix.exs:
def application do
 [mod: {MyApp, []},
  applications: [:phoenix, :phoenix_pubsub, :phoenix_html, :cowboy, :logger, :gettext,
                :phoenix_ecto, :postgrex, :comeonin]]
end

defp deps do
  [{:phoenix, "~> 1.2.1"},
   {:phoenix_pubsub, "~> 1.0"},
   {:phoenix_ecto, "~> 3.0"},
   {:postgrex, ">= 0.0.0"},
   {:phoenix_html, "~> 2.6"},
   {:phoenix_live_reload, "~> 1.0", only: :dev},
   {:gettext, "~> 0.11"},
   {:cowboy, "~> 1.0"},
   {:cors_plug, "~> 1.1"},
   {:comeonin, "~> 3.0"},
   {:guardian, "~> 0.14"},
   {:guardian_db, "~> 0.8.0"}]
end


Q: How to convert short array to BitSet with 2 bit precision in Java? I have a short array {0,2,3,1,…} which I would like to convert to a BitSet.
Expected bits in bitset: 00 10 11 01 …
Every two bit in the bitset should represent a short. (2-bit precision)
This should work fine for short values (0,1,2,3).
I know that I can use ByteBuffer and BitSet to access the bits of the numbers but those are formatted into 2 bytes (16 bit). I assume I need to bitshift the values to access the correct bits but I don't know how.
int nBit = 0;
BitSet result = new BitSet();
for (int i = 0; i < numbers.length; i++) {
  ByteBuffer buffer = ByteBuffer.allocate(2);
  buffer.putShort(number);
  BitSet bits = BitSet.valueOf(buffer.array());

  result.set(nBit++, bits.get(?));
  result.set(nBit++, bits.get(?));
}

It there maybe an easier way?

A: My current pragmatic solution which may be okay since only 4 values need to be handled:
public static BitSet transformToBitSet(short[] numbers) {
        BitSet data = new BitSet();
        int nBit = 0;
        for (int i = 0; i < numbers.length; i++) {
            short number = numbers[i];
            switch (number) {
            case 0:
                data.set(nBit++, false);
                data.set(nBit++, false);
                break;
            case 1:
                data.set(nBit++, true);
                data.set(nBit++, false);
                break;
            case 2:
                data.set(nBit++, false);
                data.set(nBit++, true);
                break;
            case 3:
                data.set(nBit++, true);
                data.set(nBit++, true);
                break;
            default:
                throw new RuntimeException("Invalid number encountered. Can't map values >4");
            }
        }
        return data;
    }

A: Here is one way to do it.

*

*set the desired bitLength (used for padding on the left with zero bits);

*initialize the BitSet index to 0.

*The iterate over the values.

*convert each to a bit string.

*pad on the left to achieve the desired bit length

*then set the bits based on the numeric value of the bit

BitSet b = new BitSet();
short[] vals = { 0, 2, 3, 1 };

int bitLength = 2;
int idx = 0;
for (short v : vals) {
    String bits = Integer.toBinaryString(v);
    bits = "0".repeat(bitLength - bits.length())+bits;
    for (char c : bits.toCharArray()) {
        b.set(idx++, c - '0' == 1);
    }
}
System.out.println(b)

prints
2,4,5,7


Q: Direct X 11 Texturing FX file error X3004 undiclared identifier "input" I am trying to texture a cube but when i try to run the progam the fx file thows error X3004 undiclared identifier "input" but input is declared near the top so i don't understand whats going wrong. I have tried for 4 day's plz help.
This code includes diffuce lighting as well as texturing. i believe that output.tex=input.tex is the problem but im not sure.
Texture2D txDiffuse : register(t0);
SamplerState samLinear : register(s0);

float4 textureColour = txDiffuse.Sample(samLinear, input.Tex);

struct VS_INPUT
{

    float4 Pos : POSITION;
    float2 Tex : TEXCOORD0;

};

struct PS_INPUT
{
    float4 Pos : SV_POSITION;
    float2 Tex : TEXCOORD0;
};

//--------------------------------------------------------------------------------------
// Constant Buffer Variables
//--------------------------------------------------------------------------------------
cbuffer ConstantBuffer : register( b0 )
{
    matrix World;
    matrix View;
    matrix Projection;

    float4 DiffuseMtrl;
    float4 DiffuseLight;
    float3 LightVecW;

}

//--------------------------------------------------------------------------------------
struct VS_OUTPUT
{
    float4 Pos : SV_POSITION;
    float4 Color : COLOR0;
    float2 Tex : TEXCOORD0;
};

//--------------------------------------------------------------------------------------
// Vertex Shader
//--------------------------------------------------------------------------------------
//guroud shading with diffuse lighting
VS_OUTPUT VS(float4 Pos : POSITION, float3 NormalL : NORMAL)
{
    VS_OUTPUT output = (VS_OUTPUT)0;

    output.Pos = mul(Pos, World);
    output.Pos = mul(output.Pos, View);
    output.Pos = mul(output.Pos, Projection);

    // Convert from local space to world space
    // W component of vector is 0 as vectors cannot be translated
    float3 normalW = mul(float4(NormalL, 0.0f), World).xyz;
        normalW = normalize(normalW);

    // Compute Colour using Diffuse lighting only
    float diffuseAmount = max(dot(LightVecW, normalW), 0.0f);
    output.Color.rgb = diffuseAmount * (DiffuseMtrl * DiffuseLight).rgb;
    output.Color.a = DiffuseMtrl.a;

    return output;

    output.Tex = input.Tex;
}

//--------------------------------------------------------------------------------------
// Pixel Shader
//--------------------------------------------------------------------------------------
float4 PS( VS_OUTPUT input ) : SV_Target
{
    return input.Color;
}

error
Framework.fx(12,53-57): error X3004: undeclared identifier 'input'

A: You're trying to sample a texture (on line 4) outside of any function. Where do you expect this code to run, in the vertex shader (VS) or the pixel shader (PS)?
Remove line 4 and change your pixel shader to:
return txDiffuse.Sample(samLinear, input.Tex);

You seem to have some structures that aren't used at all (VSINPUT, PSINPUT). The last line of the vertex shader won't compile either because you're using "input.Tex" and the vertex shader has no variable called "input". If you're not going to use them, change the first line of the VS to:
VS_OUTPUT VS(float4 Pos : POSITION, float3 NormalL : NORMAL, float2 Tex : TEXCOORD0)

and the end of the shader to be:
output.Color.a = DiffuseMtrl.a;
output.Tex = Tex;
return output;


Q: Intelij uses 100% of CPU -> vmware is extremely slow I'm getting an usage 100% when the Intelij is running. After 20 min I cannot do anything on VMWARE and then I am forced to supsend or restart VM.
I tried to remove rm /var/crash/* but it did not help.
May you please advice me how to resolve the slowness problems?


Q: Deduping a StringBuilder List of Items in C# I have a situation where I need to dedupe a list of columns in a SQL select statement that is being generated with a StringBuilder. I need to return a StringBuilder object as well.
The solution I came up with works but it looks like a dang nightmare. Can someone suggest a cleaner way to achieve this?
//The SQL statement is being passed to my code as a StringBuilder
//This is just scaffolding to fake that input.
StringBuilder items = new StringBuilder();
items.Append("SELECT ");
items.Append("Apple,");
items.Append("Carrot,");
items.Append("Pear,");
items.Append("Orange,");
items.Append("Apple");
items.Append(" From fruit_table");
//End scaffolding

//My code start:
//Chop off the non-important parts
items.Replace("SELECT ", "");
items.Replace(" From fruit_table", "");

//Convert string to list, seperating on commas
List<string> itemList = items.ToString().ToUpper().Split(',').ToList<string>();

//Found a handy "distinct" method in LINQ library
itemList = itemList.Distinct().ToList();

//Wipe out the original stringbuilder. For clarity and consistency with some other code, I'd like to reuse the same stringBuilder that was passed to me.
items.Clear();

//Rebuild my stringbuilder, now deduped
items.Append("SELECT ");
itemList.ForEach(x => items.Append(x + ","));
//Remove that comma after last fruit item
items.Remove((items.Length - 1), 1);
items.Append(" FROM fruit_table");

//Not really going to output to console, but you
//get the idea.
Console.WriteLine(items.ToString());
Console.ReadLine();

Thank you in advance for any assistance!

A: If you are stuck with starting with the StringBuilder then I think you've pretty much worked out what you need to do.
I would make it a little cleaner like this though:
var prefix = "SELECT ";
var suffix = " From fruit_table";
var result =
    String.Format("{0}{2}{1}",
        prefix,
        suffix,
        String.Join(",",
            items
                .ToString()
                .Replace(prefix, "")
                .Replace(suffix, "")
                .Split(',')
                .Select(x => x.Trim())
                .Distinct()));
items.Clear();
items.Append(result);

Before:
SELECT Apple,Carrot,Pear,Orange,Apple From fruit_table

After:
SELECT Apple,Carrot,Pear,Orange From fruit_table

If you know that there are no spaces between the names of the columns, then this is slightly cleaner:
var result =
    String.Format("{0}{2}{1}",
        prefix,
        suffix,
        String.Join(",",
            items
                .ToString()
                .Split(' ')[1]
                .Split(',')
                .Distinct()));

A: Here's another way to do it without having to hard-code the prefix and suffix elements:
// Encapsulate the behavior in an extension method we can run
// directly on a StringBuilder object
public static StringBuilder DeduplicateColumns(this StringBuilder input) {
    // Assume that we can split into large "chunks" on spaces
    var sections = input.ToString().Split(' ');
    var resultSections = new List<string>();

    foreach (var section in sections) {
        var items = section.Split(',');

        // If there aren't any commas, spit this chunk back out
        // Otherwise, split on the commas and get distinct items
        if (items.Count() == 1)
            resultSections.Add(section);
        else
            resultSections.Add(string.Join(",", items.Distinct()));
    }

    return new StringBuilder(string.Join(" ", resultSections));
}

Test code:
var demoStringBuilder = new StringBuilder
    ("SELECT Apple,Carrot,Pear,Orange,Apple From fruit_table");
var cleanedBuilder = demoStringBuilder.DeduplicateColumns();

// Output: SELECT Apple,Carrot,Pear,Orange From fruit_table

Here's a fiddle: link


Q: Add notes to latex beamer I need to add notes for presentation like we add Microsoft PowerPoint 'click to add notes'.  Is there some way to do it using latex beamer?

A: You can write everything you want between frame environment into a note command. With the option [itemize] everything you write into the note will look like an itemize list.
%\documentclass[notes]{beamer}       % print frame + notes
\documentclass[notes=only]{beamer}   % only notes
%\documentclass{beamer}              % only frames

\title[Your Short Title]{Your Presentation}
\author{You}
\institute{Where You're From}
\date{\today}

\begin{document}

\begin{frame}
  \titlepage
\end{frame}

\begin{frame}
    \frametitle{Introduction}

\begin{itemize}
  \item Your introduction goes here!
  \item Use \texttt{itemize} to organize your main points.
\end{itemize}

\end{frame}

\note{Everything you want}

\begin{frame}
    \frametitle{Development}

    Lot of interesting things

\end{frame}

\note[itemize]{
\item point 1
\item point 2
}

\begin{frame}
    \frametitle{Development}

    Lot of interesting things

\end{frame}

\end{document}

See here on write latex : https://www.writelatex.com/181070qqjrgq


Q: MySQL to google charts PHP         <?php
        $con=mysql_connect("xxxx.xxxx.xxxx.xx","Myuser","Mypass") or die("Failed to connect with database!!!!");
        mysql_select_db("data", $con);

        $sth = mysql_query("SELECT * FROM data");

        $data = array (
      'cols' => array(
        array('id' => 'date', 'label' => 'Date ', 'type' => 'datetime'),
        array('id' => 'temp1', 'label' => 'Temp 1', 'type' => 'number'),
        array('id' => 'temp2', 'label' => 'Temp 2', 'type' => 'number')
    ),
    'rows' => array()
);

while ($res = mysql_fetch_assoc($sth))
    // array nesting is complex owing to to google charts api
    array_push($data['rows'], array('c' => array(
        array('v' => $res['date']),
        array('v' => $res['temp1']),
        array('v' => $res['temp2'])
    )));
}
?>

I am having problem finishing this, echo count($bar_chart_rows_arr) AND echo count($task_submissions_arr) is showing corresponding good results (number of rows in table). The chart frame is showing but there are no table/chart data. Any suggestions ?
output html:
   6060

A: Your PHP code is producing JSON in an incorrect format for the Google Visualization API.  Try this instead:
<?php
$con=mysql_connect("xxxx.xxxx.xxxx.xx","Myuser","Mypass") or die("Failed to connect with database!!!!");
mysql_select_db("data", $con);

$sth = mysql_query("SELECT * FROM data");

$data = array (
    'cols' => array(
        array('id' => 'date', 'label' => 'Date ', 'type' => 'datetime'),
        array('id' => 'temp1', 'label' => 'Temp 1', 'type' => 'number'),
        array('id' => 'temp2', 'label' => 'Temp 2', 'type' => 'number')
    ),
    'rows' => array()
);

while ($res = mysql_fetch_assoc($sth))
    // array nesting is complex owing to to google charts api
    array_push($data['rows'], array('c' => array(
        array('v' => $res['date']),
        array('v' => $res['temp1']),
        array('v' => $res['temp2'])
    )));
}
?>

and then in your javascript:
var bar_chart_data = new google.visualization.DataTable(<?php echo json_encode($data); ?>);

A: From the code you've originally posted - change
$task_submissions_arr[][] = $res;

to
$task_submissions_arr[] = $res;

A: Thanks for all your help in the design, I had several mistakes but the crucial mistake was that I used the wrong format for date, datetime from MySQL database, when I changed it from date / datetime to string the code was complete!
$table['cols']=array(
        array('label' => 'Date', type=>'string'),
        array('label' => 'Temp 1', type=>'number'),
        array('label' =>'Temp 2', type=>'number'),
);

Jason result:
new google.visualization.DataTable({"cols":[{"label":"Date","type":"string"},{"label":"Temp 1","type":"number"},{"label":"Temp 2","type":"number"}],"rows":[{"c":[{"v":"2013-10-05 20:41:00"},{"v":10.75},{"v":4}]}


Q: How do I access the value of a slot in a Svelte 3 component? I've been playing around with Svelte 3. I'm trying to create a basic Link component that's used like this:
<Link to="http://google.com">Google</Link>

My component renders a normal HTML  tag with a favicon in front of the link text:

  <img src={imageURL} alt={`${title} Icon`} />
  <slot />

The title variable I'm showing in the alt attribute for my  tag needs to be the text value of the unnamed slot. This is a really basic example, but is there any way to get the value of a slot like this?

A: In the mean time I found another (even better and not so hacky) way:

  <slot/>

A: This hack will work.
Add a hidden span or div to bind the slot text:

    <slot/>

And update your code like this:

  {text}


Q: How do I specify a type bound for Float and Double on a generic type in Scala? I am  writing some simple Vector and Matrix classes. They look like this:
// Vector with Floats
case class Vector3f(x: Float, y: Float, z: Float) {
  def +(v: Vector3f) = Vector3f(x + v.x, y + v.y, z + v.z)
}

// Vector with Doubles
case class Vector3d(x: Double, y: Double, z: Double) {
  def +(v: Vector3d) = Vector3d(x + v.x, y + v.y, z + v.z)
}

If I go on with further methods and classes like Point3f/d, Vector4f/d, Matrix3f/d, Matrix4f/d ... this is going to be a lot of work. Uff...
So I thought generics could possible help here and remove redundancy from my code base. I thought of something like this:
// first I define a generic Vector class
case class Vector3[@specialized(Float, Double) T](x: T, y: T, z: T) {
   def +(v: Vector3[T]) = new Vector3[T](x + v.x, y + v.y, z + v.z)
}

// than I use some type aliases to hide the generic nature
type Vector3f = Vector3[Float]
type Vector3d = Vector3[Double]

The idea is that the scala compiler generates specialized classes for Vector3[Float] and Vector3[Double] similar as a C++ template would do. Unfortunately I have to put some type bound on the type parameter [T] of class Vector3 such that the operator + is defined on T. My question: How can I write Vector3[Float] that it has the same performance characteristics as Vector3f?
Context: I would like to use the Vector3f / Vector3d classes in collision detection code ... so performance does matter for me.

A: Use a context bound of Fractional:
case class Vector3[@specialized(Float, Double) T : Fractional](x: T, y: T, z: T)  { ...

then within the body of the class, get an instance of the arithmetic operators:
  val fractOps = implicitly[Fractional[T]]

lastly import its members into the scope of the class:
  import fractOps._

Thereafter you can write ordinary infix operations on values of type T used within the class. Sadly, you will have to use fractOps.div(a, b) instead of a / b for division.


Q: calculating how many lines of code in ipython notebook just for curiosity sake - is there a way to find how many lines of code you've written in your ipython notebook? I have multiple lines per box, so I can't just count the number of boxes I have...


Q: XSLT to sum product of two attributes I have the following XML source structure:
<turnovers>
    <turnover repid="1" amount="500" rate="0.1"/>
    <turnover repid="5" amount="600" rate="0.5"/>
    <turnover repid="4" amount="400" rate="0.2"/>
    <turnover repid="1" amount="700" rate="0.05"/>
    <turnover repid="2" amount="100" rate="0.15"/>
    <turnover repid="1" amount="900" rate="0.25"/>
    <turnover repid="2" amount="1000" rate="0.18"/>
    <turnover repid="5" amount="200" rate="0.55"/>
    <turnover repid="9" amount="700" rate="0.40"/>
</turnovers>

I need an XSL:value-of select statement that will return the sum of the product of the rate attribute and the amount attribute for a given rep ID. So for rep 5 I need ((600 x 0.5) + (200 x 0.55)).

A: <xsl:stylesheet
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
  <xsl:template match="/turnovers">
    <val>
      <!-- call the sum function (with the relevant nodes) -->
      <xsl:call-template name="sum">
        <xsl:with-param name="nodes" select="turnover[@repid='5']" />
      </xsl:call-template>
    </val>
  </xsl:template>

  <xsl:template name="sum">
    <xsl:param name="nodes" />
    <xsl:param name="sum" select="0" />

    <xsl:variable name="curr" select="$nodes[1]" />

    <!-- if we have a node, calculate & recurse -->
    <xsl:if test="$curr">
      <xsl:variable name="runningsum" select="
        $sum + $curr/@amount * $curr/@rate
      " />
      <xsl:call-template name="sum">
        <xsl:with-param name="nodes" select="$nodes[position() > 1]" />
        <xsl:with-param name="sum"   select="$runningsum" />
      </xsl:call-template>
    </xsl:if>

    <!-- if we don't have a node (last recursive step), return sum -->
    <xsl:if test="not($curr)">
      <xsl:value-of select="$sum" />
    </xsl:if>

  </xsl:template>
</xsl:stylesheet>

Gives:
<val>410</val>

The two <xsl:if>s can be replaced by a single <xsl:choose>. This would mean one less check during the recursion, but it also means two additional lines of code.

A: In plain XSLT 1.0 you need a recursive template for this, for example:
  <xsl:template match="turnovers">
    <xsl:variable name="selectedId" select="5" />
    <xsl:call-template name="sum_turnover">
      <xsl:with-param name="turnovers" select="turnover[@repid=$selectedId]" />
    </xsl:call-template>
  </xsl:template>

  <xsl:template name="sum_turnover">
    <xsl:param name="total" select="0" />
    <xsl:param name="turnovers"  />
    <xsl:variable name="head" select="$turnovers[1]" />
    <xsl:variable name="tail" select="$turnovers[position()>1]" />
    <xsl:variable name="calc" select="$head/@amount * $head/@rate" />
    <xsl:choose>
      <xsl:when test="not($tail)">
        <xsl:value-of select="$total + $calc" />
      </xsl:when>
      <xsl:otherwise>
        <xsl:call-template name="sum_turnover">
          <xsl:with-param name="total" select="$total + $calc" />
          <xsl:with-param name="turnovers" select="$tail" />
        </xsl:call-template>
      </xsl:otherwise>
    </xsl:choose>
  </xsl:template>

A: This should do the trick, you'll need to do some further work to select the distinct repid's
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:template match="/">
        <xsl:variable name="totals">
            <product>
                <xsl:for-each select="turnovers/turnover">
                    <repid repid="{@repid}">
                        <value><xsl:value-of select="@amount * @rate"/></value>
                    </repid>
                </xsl:for-each>
            </product>
        </xsl:variable>
        <totals>
            <total repid="5" value="{sum($totals/product/repid[@repid='5']/value)}"/>
        </totals>
    </xsl:template>

</xsl:stylesheet>

A: In XSLT 1.0 the use of FXSL makes such problems easy to solve:
<xsl:stylesheet version="1.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:f="http://fxsl.sf.net/"
 xmlns:ext="http://exslt.org/common"
 exclude-result-prefixes="xsl f ext"
 >
 <xsl:import href="zipWith.xsl"/>
 <xsl:output method="text"/>

  <xsl:variable name="vMultFun" select="document('')/*/f:mult-func[1]"/>

    <xsl:template match="/">
      <xsl:call-template name="profitForId"/>
    </xsl:template>

    <xsl:template name="profitForId">
      <xsl:param name="pId" select="1"/>

      <xsl:variable name="vrtfProducts">
          <xsl:call-template name="zipWith">
            <xsl:with-param name="pFun" select="$vMultFun"/>
            <xsl:with-param name="pList1" select="/*/*[@repid = $pId]/@amount"/>
            <xsl:with-param name="pList2" select="/*/*[@repid = $pId]/@rate"/>
          </xsl:call-template>
      </xsl:variable>

      <xsl:value-of select="sum(ext:node-set($vrtfProducts)/*)"/>
    </xsl:template>

    <f:mult-func/>
    <xsl:template match="f:mult-func" mode="f:FXSL">
     <xsl:param name="pArg1"/>
     <xsl:param name="pArg2"/>

     <xsl:value-of select="$pArg1 * $pArg2"/>
    </xsl:template>
</xsl:stylesheet>

When this transformation is applied on the originally posted source XML document, the correct result is produced:
310
In XSLT 2.0 the same solution using FXSL 2.0 can be expressed by an XPath one-liner:
sum(f:zipWith(f:multiply(),
          /*/*[xs:decimal(@repid) eq 1]/@amount/xs:decimal(.),
          /*/*[xs:decimal(@repid) eq 1]/@rate/xs:decimal(.)
          )
     )

The whole transformation:
<xsl:stylesheet version="2.0"
 xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
 xmlns:xs="http://www.w3.org/2001/XMLSchema"
 xmlns:f="http://fxsl.sf.net/"
 exclude-result-prefixes="f xs"
>
 <xsl:import href="../f/func-zipWithDVC.xsl"/>
 <xsl:import href="../f/func-Operators.xsl"/>

 <!-- To be applied on testFunc-zipWith4.xml -->
 <xsl:output omit-xml-declaration="yes" indent="yes"/>

 <xsl:template match="/">
   <xsl:value-of select=
   "sum(f:zipWith(f:multiply(),
              /*/*[xs:decimal(@repid) eq 1]/@amount/xs:decimal(.),
              /*/*[xs:decimal(@repid) eq 1]/@rate/xs:decimal(.)
              )
         )
    "/>
 </xsl:template>
</xsl:stylesheet>

Again, this transformation produces the correct answer:
310
Note the following:

*

*The f:zipWith() function takes as arguments a function fun() (of two arguments) and two lists of items having the same length. It produces a new list of the same length, whose items are the result of the pair-wise application of fun() on the corresponding k-th items of the two lists.

*f:zipWith() as in the expression takes the function f:multiply() and two sequences of corresponding "ammount" and "rate" attributes. The sesult is a sequence, each item of which is the product of the corresponding "ammount" and "rate".

*Finally, the sum of this sequence is produced.

*There is no need to write an explicit recursion and it is also guaranteed that the behind-the scenes recursion used within f:zipWith() is never going to crash (for all practical cases) with "stack overflow"

A: <?xml version="1.0" encoding="UTF-8"?>
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
      xmlns:xs="http://www.w3.org/2001/XMLSchema"
      exclude-result-prefixes="xs"
      version="2.0">

   <xsl:variable name="repid" select="5" />

   <xsl:template match="/">
      <xsl:value-of select=
         "sum(for $x in /turnovers/turnover[@repid=$repid] return $x/@amount * $x/@rate)"/>
   </xsl:template>

</xsl:stylesheet>

You can do this if you just need the value and not xml.

A: The easiest way to do it in XSLT is probably to use programming language bindings, so that you can define your own XPath functions.


Q: How to remove space before and after any numbers? How to remove space before and after any numbers?
for e.g. "     3,340  ".
I want this number to look like this "3,340".

A: Use the TRIM function.
Example:  =TRIM(" 3,340 ") results in "3,340".

A: Thanks Steven for your response. I already tried TRIM function but dint work, however now I have the answer to this question now, so I wanted it to share with you all. Below is the combination of 2 function, it gave me desired output.
=TRIM(SUBSTITUTE(D2,CHAR(160),""))


Q: Code API default signature gsuite email in admin I am not sure how to input the code and location input the code for gsuite. So it is set up as default for each employee


Q: passing data to dynamically created ascx user control I want to display user control which produces different set of data depending on values which are being passed to it.
No. of UserControls are decided at run-time

*

*Now it dint Hit in Page_Load of ascx.cs
Default.aspx
<%@ Register Src="~/UserControl/SquareEUA.ascx" TagName="Square" TagPrefix="EUA" %>

Default.aspx.cs
    protected void Page_Load(object sender, EventArgs e)
    {
    string[] Property;
    foreach (string sPropID in Property)
    {
SquareEUA userControl = (SquareEUA)Page.LoadControl("~/UserControl/SquareEUA.ascx");
        userControl.ID = "MyControl_" + sPropID.Trim();
        userControl.sCustID = CustomerID;
        userControl.sCustPropID = sPropID.Trim();
        userControl.Visible = true;
        divControls.Controls.Add(userControl);
        userControl.Dispose();
    }
    }

SquareEUA.ascx
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="SquareEUA.ascx.cs" Inherits="UserControl.SquareEUA" %>

     // Some HTML Markup

SquareEUA.ascx.cs
public partial class SquareEUA : System.Web.UI.UserControl
{
public string sCustID { get; set; }
public string sCustPropID { get; set; }
    protected void Page_Load(object sender, EventArgs e)
    {
        // Some Code
        // Didnt Hit Breakpoint Here;
    }
}

A: you need to cast your usercontrol as the actual class SquareEUA to access that class's properties
SquareEUA userControl = (SquareEUA)(Page.LoadControl("~/UserControl/SquareEUA.ascx"));

that should do the trick (you should add some error handling, null check, etc.)
edit: seems I missed a parenthesis around (Page...


Q: Inequality for moments of sums Suppose the random variables $X_i$ are independent and satisfy $E[X_i] = 0$. Then the following inequality holds:
$$E\left[\left(\sum \limits_{i = 1}^n X_i\right)^4\right] = \sum \limits_{i = 1}^n E[X_i^4] + 3\sum \limits_{i \ne j} E[X_i^2X_j^2] \le 3\left(\sum \limits_{i = 1}^n E[X_i^4] + \sum \limits_{i \ne j} \sqrt{E[X_i^4]}\sqrt{E[X_j^4]}\right) = 3\left(\sum \limits_{i = 1}^n \sqrt{E[X_i^4]}\right)^2$$
Now I would like to generalize this inequality to moments of order 6 [or higher]. My best guess is that the inequality
$$E\left[\left(\sum \limits_{i = 1}^n X_i\right)^6\right] \le C \left(\sum \limits_{i = 1}^n E[X_i^6]^{1/3}\right)^3$$
holds, where $C$ is an absolute constant.
Can someone provide a proof/ source for the last inequality? Or perhaps a source for a similar inequality?
The "similar inequality" should provide at least $E\left[\left(\sum \limits_{i = 1}^n X_i\right)^6\right] = O(n^3)$ in the i.i.d. case.

A: The inequality is actually correct. It follows from Theorems 3 in a Rosenthal paper from 1970 (Israel J. Math. 8, 273-303).
Rosenthal proves the following inequality for $p > 2$ and independent, centered Random variables $X_i \in L^p$:
$$E\left[\left|\sum \limits_{i = 1}^n X_i\right|^p\right] \le C(p) \max\left\{\sum \limits_{i = 1}^n E[ \left|X_i\right|^p], \left(\sum \limits_{i = 1}^n E[X_i^2]\right)^{p/2}\right\}.$$
The inequality in my original post follows from two applications of Jensen's inequality:
$$\left(\sum \limits_{i = 1}^n E[\left|X_i\right|^p]\right)^{2/p} = n^{2/p} \left(\sum \limits_{i = 1}^n \frac{1}{n}E[\left|X_i\right|^p]\right)^{2/p} \le n^{2/p - 1} \sum \limits_{i = 1}^n E[\left|X_i\right|^p]^{2/p} \le \sum \limits_{i = 1}^n E[\left|X_i\right|^p]^{2/p}$$
$$E[X_i^2] \le E[\left|X_i\right|^p]^{2/p}$$


Q: Linux: Join two lines with an equal value in the SAME file I have a file that looks like this:
1 51 Brahui A C A A T
1 51 Brahui A C A G T
3 51 Brahui A C A G C
3 51 Brahui A C G A T
5 51 Brahui A C G A T
5 51 Brahui A C G G C
7 51 Brahui A C G A T
7 51 Brahui A C G G T
9 51 Brahui A C G G T
9 51 Brahui A C G G T
And I want to generate an output file whereby if the first column/field are of equal value then I want to merge the two lines together with a "/" character as a delimiter. For example:
1 51 Brahui A/A C/C A/A A/G T/T
3 51 Brahui A/A C/C A/G G/A C/T
Is there a way that I can do that?
P.S.The columns starting from $4 are actually 2,834 long (i.e. $4-$2841) so I don't think it will be practical to physically enter $4, $5, $6, etc.. Is there a way to do this?

A: pearl.229>awk '{a=$1;
          b=$4;
          c=$5;
          d=$6;
          e=$7;
          f=$8;
          getline;
          if(a==$1)
          print a,$2,$3,b"/"$4,c"/"$5,d"/"$6,e"/"$7,f"/"$8}' file3
    1 51 Brahui A/A C/C A/A A/G T/T
    3 51 Brahui A/A C/C A/G G/A C/T
    5 51 Brahui A/A C/C G/G A/G T/C
    7 51 Brahui A/A C/C G/G A/G T/T
    9 51 Brahui A/A C/C G/G G/G T/T
    pearl.230>

A: I like using fmt.  It makes the code prettier.
[ghoti@pc ~]$ cat doit
#!/usr/bin/awk -f

BEGIN {
  fmt="%s %s %s %s/%s %s/%s %s/%s %s/%s %s/%s\n";
}

one == $1 {
  split(last,a);
  printf(fmt, $1,$2,$3, a[4],$4, a[5],$5, a[6],$6, a[7],$7, a[8],$8);
}

{ last = $0; one = $1; }

[ghoti@pc ~]$ ./doit input.txt
1 51 Brahui A/A C/C A/A A/G T/T
3 51 Brahui A/A C/C A/G G/A C/T
5 51 Brahui A/A C/C G/G A/G T/C
7 51 Brahui A/A C/C G/G A/G T/T
9 51 Brahui A/A C/C G/G G/G T/T
[ghoti@pc ~]$


Q: Explain Traverse[List] implementation in scalaz-seven I'm trying to understand the traverseImpl implementation in scalaz-seven:
def traverseImpl[F[_], A, B](l: List[A])(f: A => F[B])(implicit F: Applicative[F]) = {
  DList.fromList(l).foldr(F.point(List[B]())) {
     (a, fbs) => F.map2(f(a), fbs)(_ :: _)
  }
}

Can someone explain how the List interacts with the Applicative? Ultimately, I'd like to be able to implement other instances for Traverse.

A: An applicative lets you apply a function in a context to a value in a context. So for instance, you can apply some((i: Int) => i + 1) to some(3) and get some(4). Let's forget that for now. I'll come back to that later.
List has two representations, it's either Nil or head :: tail. You may be used to fold over it using foldLeft but there is another way to fold over it:
def foldr[A, B](l: List[A], acc0: B, f: (A, B) => B): B = l match {
   case Nil => acc0
   case x :: xs => f(x, foldr(xs, acc0, f))
}

Given List(1, 2) we fold over the list applying the function starting from the right side - even though we really deconstruct the list from the left side!
f(1, f(2, Nil))

This can be used to compute the length of a list. Given List(1, 2):
foldr(List(1, 2), 0, (i: Int, acc: Int) => 1 + acc)
// returns 2

This can also be used to create another list:
foldr[Int, List[Int]](List(1, 2), List[Int](), _ :: _)
//List[Int] = List(1, 2)

So given an empty list and the :: function we were able to create another list. What if our elements are in some context? If our context is an applicative then we can still apply our elements and :: in that context. Continuing with List(1, 2) and Option as our applicative. We start with some(List[Int]())) we want to apply the :: function in the Option context. This is what the F.map2 does. It takes two values in their Option context, put the provided function of two arguments into the Option context and apply them together.
So outside the context we have (2, Nil) => 2 :: Nil
In context we have: (Some(2), Some(Nil)) => Some(2 :: Nil)
Going back to the original question:
// do a foldr
DList.fromList(l).foldr(F.point(List[B]())) {
  // starting with an empty list in its applicative context F.point(List[B]())
  (a, fbs) => F.map2(f(a), fbs)(_ :: _)
  // Apply the `::` function to the two values in the context
}

I am not sure why the difference DList is used. What I see is that it uses trampolines so hopefully that makes this implementation work without blowing the stack, but I have not tried so I don't know.
The interesting part about implementing the right fold like this is that I think it gives you an approach to implement traverse for algebric data types using catamorphisms.
For instance given:
trait Tree[+A]
object Leaf extends Tree[Nothing]
case class Node[A](a: A, left: Tree[A], right: Tree[A]) extends Tree[A]

Fold would be defined like this (which is really following the same approach as for List):
def fold[A, B](tree: Tree[A], valueForLeaf: B, functionForNode: (A, B, B) => B): B = {
  tree match {
    case Leaf => valueForLeaf
    case Node(a, left, right) => functionForNode(a,
        fold(left, valueForLeaf, functionForNode),
        fold(right, valueForLeaf, functionForNode)
      )
  }
}

And traverse would use that fold with F.point(Leaf) and apply it to Node.apply. Though there is no F.map3 so it may be a bit cumbersome.

A: This not something so easy to grasp. I recommend reading the article linked at the beginning of my blog post on the subject.
I also did a presentation on the subject during the last Functional Programming meeting in Sydney and you can find the slides here.
If I can try to explain in a few words, traverse is going to traverse each element of the list one by one, eventually re-constructing the list (_ :: _) but accumulating/executing some kind of "effects" as given by the F Applicative. If F is State it keeps track of some state. If F is the applicative corresponding to a Monoid it aggregates some kind of measure for each element of the list.
The main interaction of the list and the applicative is with the map2 application where it receives a F[B] element and attach it to the other F[List[B]] elements by definition of F as an Applicative and the use of the List constructor :: as the specific function to apply.
From there you see that implementing other instances of Traverse is only about applying the data constructors of the data structure you want to traverse. If you have a look at the linked powerpoint presentation, you'll see some slides with a binary tree traversal.

A: List#foldRight blows the stack for large lists. Try this in a REPL:
List.range(0, 10000).foldRight(())((a, b) => ())

Typically, you can reverse the list, use foldLeft, then reverse the result to avoid this problem. But with traverse we really have to process the elements in the correct order, to make sure that the effect is treated correctly. DList is a convenient way to do this, by virtue of trampolining.
In the end, these tests must pass:
https://github.com/scalaz/scalaz/blob/scalaz-seven/tests/src/test/scala/scalaz/TraverseTest.scala#L13
https://github.com/scalaz/scalaz/blob/scalaz-seven/tests/src/test/scala/scalaz/std/ListTest.scala#L11
https://github.com/scalaz/scalaz/blob/scalaz-seven/core/src/main/scala/scalaz/Traverse.scala#L76


Q: Issue with deploying Azure project using Powershell 2 I used the Azure training kit command
New-Deployment
    -serviceName <YOUR_SERVICE_NAME_LOWER_CASE>
    -subscriptionId <YOUR_SUBSCRIPTION_ID>
    -certificate (get-item cert:\CurrentUser\MY\<YOUR_CERTIFICATE_THUMBPRINT>)
    -slot staging
    –package <PACKAGE_LOCATION>
    -configuration <CONFIGURATION_LOCATION>
    -label "v2.0"
    –storageServiceName <YOUR_STORAGE_SERVICE_NAME_LOWER_CASE>

to deploy my Azure app. It was able to upload package to the blob but when Create a new deployment it shows error as:
New-Deployment : Cannot access a closed Stream.
At line:1 char:15
+ New-Deployment <<<<  -serviceName mytodo -subscriptionId xxxxxxxxx
8ad-360cdbdc361f -certificate (get-item cert:\CurrentUser\MY\xxxxxxxx
6DD27E3DFF5F7FE24A3FBF) -slot staging -package MyTodo.cspkg -configuration Serv
iceConfiguration.cscfg -label "v1.0" -storageServiceName xxxxx
    + CategoryInfo          : CloseError: (:) [New-Deployment], ObjectDisposed
   Exception
    + FullyQualifiedErrorId : Microsoft.WindowsAzure.Samples.ManagementTools.P
   owerShell.Services.HostedServices.NewDeploymentCommand

A: Do you have a local proxy (e.g. Fiddler) running? If so, you'll need to disable it.
Also, check the certificate is installed properly and in the right place: follow, to the letter, the instructions here:
http://msdn.microsoft.com/en-us/gg271300
in particular noting there are no line breaks or spaces in the path for (get-Item cert:\CurrentUser\MY\XXXXX).