text:
Q: Angular Close Slide in Panel When Click Outside I have a simple component with the job of sliding in as an overlay from the right side and covering 40% of the screen. How do I make it disappear when the user clicks outside of it?
side-overlay.component.html

    <ng-content />

side-overlay.component.ts
@Component({
    selector: 'datona-side-overlay',
    templateUrl: './side-overlay.component.html',
    styleUrls: ['./side-overlay.component.scss'],
})
export class SideOverlayComponent {
    @Input() open: Boolean = false;
}

side-overlay.component.scss
.sidebar-layout {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 999;
    top: 0;
    right: 0;
    overflow-x: hidden;
    transition: 0.3s;
}

.sidebar.open {
    width: 40%;
}

A: One way to get the click event outside of your component is to use the document and listen for clicks there. If the click happens on an element different from the sidebar, then close it
@HostListener('document:click', ['$event'])
onDocumentClick(event: MouseEvent) {
  const sidebarElement = document.querySelector('.sidebar');
  if (!sidebarElement.contains(event.target)) {
    this.open = false;
  }
}

Another way would be to handle this behavior outside this component, on the level of the parent. You have two divs, one for the sidebar and one for the content of the page. If the user clicks on the content div then update the open attibute to false
// in parent component html

  <app-side-overlay [open]="isSidebarOpen"></app-side-overlay>

// in parent component .ts
isSidebarOpen: boolean = true;

handleContentClick() {
  this.isSidebarOpen = false;
}

Depends on the way you want your app structured, I would personally go with the second way.

A: You could use a curtain like so:
side-overlay.component.html

HELLO

side-overlay.component.scss
.sidebar-layout {
    height: 100%;
    width: 0;
    position: fixed;
    z-index: 999;
    top: 0;
    right: 0;
    overflow-x: hidden;
    transition: 0.3s;
    background: maroon;
}

.sidebar.open {
    width: 40%;
}

.curtain {
    position: absolute;
    width: 100vw;
    height: 100vh;
    z-index: 2;
    top: 0;
    left: 0;
}

side-overlay.component.ts
import { Component, Input } from '@angular/core';

@Component({
  selector: 'datona-side-overlay',
  templateUrl: './side-overlay.component.html',
  styleUrls: ['./side-overlay.component.scss']
})
export class AppComponent {
  @Input() open: Boolean = true;

  closeSidebar() {
    this.open = false;
  }
}


text:
Q: Can't get Mule Studio Salesforce connector to connect, verified SF login and Security Token I created a new demo project, from their canned demos, which only has 3 components.  I filled in my force.com developer login.  But any time I touch the SF icon in the diagram, or try to change any settings, I get:
"Getting DataSense metadata types failed: Invalid usernane, password, security token; or user locked out"
What I did:

*

*Fresh install of MuleSoft's Mule Studio.

*Software updates

*Verified login on Force web site

*Verified App login with "Force.com Explorer" (username, password, security token)

*Even tried changing security token and password and re-verified.

*For mulesoft Salesforce connector properties, I originally just updated 3 fields on the Connections tab: Username, Password, Security Token.

*Later I also tried updating the URL field to https://test.salesforce.com

*Not using any proxy info.

*I also waited over the weekend, in case my failed attempts had caused a lockout timer, but same thing this morning.

Again, I'm trying to do the simplest thing possible: Start with fresh install, new template project, fill in my credentials, and boom!
I'm guessing there's some other property that I need to set, but relatively new to both Mule and Force, so really don't know what else to check.

A: If you use the the 6.0 connector, the problem is your studio + ESB version.
I was having the same with the Studio of October and ESB v.3.5.2.
Solution:
- Studio 5.0.1
- ESB 3.6 EE

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ Convex hull using Graham scan algorithm So i need to make a Convex hull using Graham scan algorithm, but i have problem, i get this kinda convex:

void draw_line(Line l, Canvas& canvas) {
  canvas.draw_line(l.a, l.b);
}

double drandom(){
  return rand() * 1. / RAND_MAX;
}

bool is_convex(const vector<PairXY> vertex){}

void draw_picture(Canvas & canvas) {
  vector <PairXY> vertex;
  vector <PairXY>:: const_iterator iter = vertex.begin();
  srand((unsigned)time(0));

Here i add random points of convex
  for (int i=5;i!=0;i--) {
  vertex.push_back(PairXY(drandom()*640,drandom()*480));
  }

Here i find the first and lowest point from which to start.
  for (int i=0;i!=5;i++) {
    if (vertex[i].y > vertex[i+1].y)
       vertex.push_back(vertex[i]);
  }

Here i sort all the remaining points.
  for (int m=1;m!=4;m++){
    for (int i=m;i!=5;i++) {
      if (vertex[i].x > vertex[i+1].x)
         vertex.push_back(vertex[i]);
    }
  }

  vector<PairXY>::const_iterator i=vertex.begin(), j=i;

Here i draw the convex.
  for(;++i != vertex.end(); j++)
      draw_line(Line(*j, *i), canvas);
      if (j != vertex.end())
        draw_line(Line(*j, *vertex.begin()), canvas);

}

Could somebody tell me what i am doing wrong?

A: Did you check your understanding of what push_back() does?
It seems like you think that vertex.push_back(vertex[i])  would move element i to the end. It doesn't. It pushes a copy of the element onto vertex.
That's your first problem in finding the lowest y. Your x test is not going to work either.
Maybe you could have two vectors - the original, unmodified, and a working vector that you place points into after testing them.
I also don't see where you implement the Graham scan sort by angle... you skipped that here right?
Style issue: you should also rewrite loop limits in terms of vector.size() or use iterators.


text:
Q: FeatureCounts - correct GTF file for matching to gene name (not gene_id) I am analysing data in C. elegans using featureCounts and am having problems mapping to gene_name rather than gene_id. I have downloaded the following .gtf file from WormBase https://downloads.wormbase.org/releases/WS280/species/c_elegans/PRJNA13758/c_elegans.PRJNA13758.WS280.canonical_geneset.gtf.gz.
When I try to map to gene_name featureCounts says that gene_name is not found in the 9th column of the .gtf file. FeatureCounts works fine mapping to gene_id with the following code:
featureCounts -p -t exon -g gene_id -a /mnt/shared/projects/uosa/Helder_Ferreira/polya_rna_sequencing/reference_genome/c_elegans.PRJNA13758.WS280.canonical_geneset.gtf -Q 10 -s 2 -o all_samples_counts.txt *.sorted.bam

I can see gene_name in the gtf file when I do head .gtf so I believe it should be possible to map to gene_name rather than gene_id (although maybe I'm mistaken!)
Is there a way to map to gene_name rather than gene_id? Or is it easier to convert to gene_name after featureCounts? I am not sure how to go about that (I can see information about human/mice but not C. elegans). Any help would be much appreciated!


text:
Q: AttributeError: instance has no attribute 'function' class f:
def f1(self, x):
    return x
def f2(self, x):
    return 2.0*x
def f3(self, x, function=f1):
    return self.function(x)

then
>>>f0=f()
>>>f0.f3(1)

the error is:
"AttributeError: f instance has no attribute 'function'"

How can i fix it if i still wanna f3() to select a function of f1 or f2 in this class?

A: You can use .getattr():
class f:
    def f1(self, x):
        return x

    def f2(self, x):
        return 2.0 * x

    def f3(self, x, function="f1"):
        return getattr(self, function)(x)

Usage:
f0 = f()
print(f0.f3(1))  # prints 1
print(f0.f3(1, "f2"))  # prints 2.0


text:
Q: Convolution exercise, is this really ok? Let $f$ be a function such as, for every $\alpha > 0$,
$$\omega (\alpha) = | \lbrace x \in \mathbb{R}^n : |f(x)| > \alpha \rbrace | \leq c (1 + \alpha)^{-p}$$
Prove that $f \in L^{r}(\mathbb{R}^n)$, $\;$ if $\;$ $0 < r < p$.
This is what I have done:
Knowing that: $\displaystyle || f ||^p_p = p \int^{\infty}_0 t^{r-1} \omega (t) dt$ , for $p > 0$.
We can make: $\displaystyle ||f||^{r}_{r} = r \int^{\infty}_{0} t^{r-1} \omega (t) dt$.
But for every $\;$ $t > 0$ $\;$ we got: $\displaystyle ||f||^{r}_{r} \leq r \int^{\infty}_{0} t^{r-1} \frac{c}{(1+t)^{p}} dt$.
Then: $\displaystyle ||f||^{r}_{r} \leq cr \int^{\infty}_{0} \frac{t^{r-1}}{(1+t)^{p}} dt$.
And working the expression:
$\displaystyle \frac{t^{r-1}}{(1+t)^{p}} \leq \frac{t^{r-1}}{t^{p}} = \frac{1}{t^{p-(r-1)}} \leq \frac{1}{t^s}$.
Where $s = p-(r-1) > 1$ , cause $r < p \Rightarrow r-1 < p-1 \Rightarrow 1 < p-(r-1)$.
Finally, $\displaystyle ||f||^{r}_{r} \leq \int^{\infty}_{0} \frac{1}{t^s} < \infty $.
Now, here is my doubt... is this ok? jaja


text:
Q: How do I get the total number of rows in a Dojo EnhancedGrid? I need to make sure there is at least one row before saving.  I've tried the following but this does not reflect what is in the grid on the screen.
var storeUOM = dijit.byId('gridUOM').store;
if (storeUOM._arrayOfAllItems.length == 0) {
    if (errors.length > 1) errors += '\n';
    errors += 'Must setup at least one unit of measure';
}

For example the grid may start with 4 rows and the user deletes them all.  This code still returns a length of 4.

A: Actually the following code from that link works perfectly!  I does not reload the store from the URL it just returns the size of the current store.
var storeUOM = dijit.byId('gridUOM').store;
function size(size, request) {
   if (size == 0) {
      if (errors.length > 1) errors += '\n';
      errors += 'Must setup at least one unit of measure';
   }
}
storeUOM.fetch({query: {}, onBegin: size, start: 0, count: 0});

A: var totalRows = dijit.byId('gridUOM').rowCount ;


text:
Q: Xcode Firebase get authenticated user while logged in as someone else Anyone know how I can get the user id for a certain user in Auth?
Let's say I am logged in with current user jalla@gmail.com, then I can get userid by
let userId = FIRAuth.auth()?.currentUser?.uid

But if I want to get the userId of the other user jarra@gmail.com while I am logged in as jalla@gmail.com.
How can I do that?

This is how I create a new user:
FIRAuth.auth()?.createUser(withEmail: txtUsername.text!, password: txtPassword.text!, completion: {
            user, error in

            if error != nil {
                print("error: " + error.debugDescription)
            }
            else{
                print("User created")
                self.login()
            }
        })

Which result in the authenticated user in the image attached.
I also have a Users table, but this has nothing to do with authenticating users for login.

The thing is that I need to programatically add new authenticated users. Which is ok, but how can I query data from the Authenticated table? I need to do it because I add the authenticated uid to each user roots in the database (see User table image)

A: For each user, create a record in your Firebase Database and store uid for each user so that you can retrieve that uid once you need it.
If you will query uid information by using the email information of the said user (i.e. jarra@gmail.com in your case), it might be best to store user information including uid under a key of respective user's email.

A: If you are logging in code rather than the console, one option is to leverage a /users node.
With Firebase, it's common practice to have a /users node that stores information about your users.
users
  uid_001
    email: "dr@who.com"
    name:  "Dr. Who"
    fav_food: "Jelly Babies"
  uid_002
    email: "homer@simpsons.com"
    name: "Homer Simpson"
    fav_food: "Doughnuts"

The uid's used as the key to each user node are the ones created by Firebase when the user is created.
From there, it's a snap to query for the email address which will retrieve the node in question, the parent key being the uid of the user.


text:
Q: How to solve this limit problem?-$\lim_{n\to \infty}\ \left(\frac{\ n!}{(mn)^n}\right)^{\frac{1}{n}}$ I need to find the value of-
$$\lim_{n\to \infty}\ \left(\frac{\ n!}{(mn)^n}\right)^{\frac{1}{n}}$$
where $m {\in} R$
I don't know how to even start. Would someone explain it step by step, also which type of indeterminate form is this?
Is there a simpler to solve this ? i.e. without any high mathematics theorem etc.?

A: Use Stirling's approximation for $n!$
$n!\approx \sqrt{2\pi n}( \frac ne)^n$
$$\lim_{n\to \infty} \left(\frac{\sqrt{2\pi n}}{(em)^n}\right)^{\frac 1n}$$
$$\frac {1}{em} \lim_{n\to \infty} (2\pi n)^{\frac 1{2n}}$$
Let the above limit (excluding constant) be $L$
$$\log L= \lim_{n\to \infty}\frac{\log (2\pi n)}{2n}$$
L'Hopital's rule here

A: You don't need Stirling.
$ \left(\dfrac{\ n!}{(mn)^n}\right)^{\frac{1}{n}}
=\dfrac{(n!)^{1/n}}{mn}
$
so all you need is that
$\dfrac{(n!)^{1/n}}{n}
\to \dfrac{1}{e}
$
to get that the limit is
$\dfrac1{em}
$.
$\dfrac{(n!)^{1/n}}{n}
\to \dfrac{1}{e}
$
follows from
$\left(\dfrac{n}{e}\right)^n
< n!
<\left(\dfrac{n}{e}\right)^{n+1}
$.
These, in turn,
can be proved by induction from
$\left(1+\dfrac1{n}\right)^n
< e
<\left(1+\dfrac1{n}\right)^{n+1}
$.

A: let $a_n = \frac {n!}{(mn)^n}$.
by the root-frac analogy we know that for every $a_n$ if the limit of the series $b_n = \frac{a_{n+1}}{a_n}$ exist it is equal to the limit of the series $c_n = \sqrt[n]{a_n}$. so lets calculate the limit of the series $b_n = \frac{a_{n+1}}{a_n}$
$b_n = \frac{a_{n+1}}{a_n} =  \frac {(n+1)!}{(m((n+1)))^{(n+1)}} : \frac {n!}{(mn)^n} = m^{-1}(\frac{n}{n+1})^n$
we know that the limit of $(\frac{n}{n+1})^n$ (n goes to infinity) is $e^{-1}$ then the limit of $b_n$ (since m is a constant different than 0) is $m^{-1}e^{-1} = \frac{1}{me}$
final result: $\frac{1}{me}$

A: $$\lim_{n\to\infty}\left(\frac{n!}{(mn)^n}\right)^{\frac{1}{n}}=\lim_{n\to\infty}\exp\left[\ln\left(\left(\frac{n!}{(mn)^n}\right)^{\frac{1}{n}}\right)\right]=$$
$$\lim_{n\to\infty}\exp\left[\frac{\ln\left(\frac{n!}{(mn)^n}\right)}{n}\right]=\exp\left[\lim_{n\to\infty}\frac{\ln\left(\frac{n!}{(mn)^n}\right)}{n}\right]=$$

Apply l'Hôpital's rule:

$$\exp\left[\lim_{n\to\infty}\frac{\psi^{(0)}(1+n)-\ln(mn)-1}{1}\right]=$$
$$\exp\left[\lim_{n\to\infty}\left(\psi^{(0)}(1+n)-\ln(mn)-1\right)\right]=$$
$$\exp\left[\left(0-\ln(m)-1\right)\right]=\exp\left[-\ln(m)-1\right]=\frac{1}{me}$$

*

*To find this limit $\lim_{n\to\infty}\left(\psi^{(0)}(1+n)-\ln(mn)-1\right)$, notice:

$$\lim_{n\to\infty}\left(\psi^{(0)}(1+n)-\ln(mn)-1\right)=$$
$$\lim_{n\to\infty}\left(\psi^{(0)}(1+n)-\ln(mn)\right)-1=$$
$$\lim_{n\to\infty}\ln\left(\frac{\exp\left[\psi^{(0)}(1+n)\right]}{mn}\right)-1=\ln\left(\frac{1}{m}\right)-1$$


text:
Q: Grep/Sed replace small text in large .sql file I have a large .sql file of size ~ 220 MB.
Now in that I have a TRIGGER statement in that file, which uses a different user than the mysql database user, i am trying to import database with, so it gives below error when trying to import database:
ERROR 1142 (42000) at line 9732: TRIGGER command denied to user 'user_name'@'localhost' for table 'sales_flat_creditmemo'

Now how can I find all lines containing the TRIGGER statements and change "user_name" to mysql user "username_actual" in the whole file without even opening it. Opening this file in Geany also causes the Geany to crash.

A: You can use a combination of grep and sed for in-place replacement, without actually opening the file.
grep -Iril 'TRIGGER' sql_file | xargs sed -i 's/user_name/username_actual/g'

The purposes of the flags are:-
-I -> to ignore binary files while  doing grep on files. ( may not be applicable here)
-r -> recursive search under all sub-levels of directories
-i -> Ignore case (case insensitive search)
-l -> Just print the file-name in which the match is found.
Check more in the man grep page.
There is also one cool alternate way of using Vim in Ex mode for performing the substitution in-place.
ex -sc '/TRIGGER/s/user_name/username_actual/|x' file

Also one last solution using sed alone for in-place replacement
sed -i '/TRIGGER/s/user_name/username_actual/g'


text:
Q: Operator norm convergence and pointwise convergence I just want to make sure I am understanding this correctly. I want to show that operator norm convergence implies pointwise convergence.
Suppose we are looking at the space $L(X,Y)$ i.e the space of all linear operator from X to Y. Suppose that $S_m = \Sigma_{n = 1}^{n = m} T_n \rightarrow T$. Then the reason that operator norm convergence implies pointwise convergence is the following:
By definition we have $\|S_m - T\|_{op} \longrightarrow 0$ as $m \longrightarrow \infty$.  So by definition
$$| \Sigma_{n = 1}^m \ sup_{x \neq 0} \frac{T_n(x)}{\|x\|} - sup_{x \neq 0} \frac{T(x)}{\|x\|}| \longrightarrow 0$$
Thus we have that $$ \big|\Sigma_{n = 1}^m T_n(x) - T(x)| \big| = \big|\Sigma_{n = 1}^m T_n(\frac{x}{\|x\|})\|x\| - T(\frac{x}{\|x\|})\|x\|\big| \longrightarrow 0$$
Thus we are done. Is it good ?

A: Usually $L(X,Y)$ stands for the space of all continuous linear operators between normed spaces $X$ and $Y$. It it well-known that for $A\in L(X,Y)$ we have $\|A(x)\|\le \|A\|\cdot \|x\|$. Hence $\|T_n(x)-T(x)\|\le\|T_n-T\|\cdot \|x\|$. That is why operator convergence $T_n\to T$ implies pointwise convergence $T_n(x)\to T(x)$ for any $x$.

A: I think you may be mistaken as to what $\|S_m -T \|$ means. Things like $\sup_{x \neq 0} \frac{T_n(x)}{\|x\|}$ aren't well defined, because there's no order on the vector space $Y$. The definition of the norm of operator $S_m-T$ (at least one of the equivalent definitions) is actually
$$
\| S_m -T \| = \sup_{x \neq 0} \frac{\| S_m(x) - T(x) \|}{\|x\|}.
$$
So for any $x \neq 0$, you would necessarily have $\| S_m -T \| \geq \frac{\| S_m(x) -T(x) \|}{\|x\|}$. In other words $\| S_m( x) -T(x) \| \leq \| x\| \|S_m-T\|$ holds for any $x \in X$. This inequality gives you pointwise convergence if norm convergence holds.


text:
Q: Add link to windows 8 store app
Possible Duplicate:
Links with URIs of schemes other than http/https are broken

I can't add link to windows store app, since MS is using the ms-windows-store: protocol. For example this link works in browser, it opens the Windows store with our application.
ms-windows-store:PDP?PFN=WebMarketing.Coolinarika_tp6yaakah33yj

But if I put it as a link, Stack Overflow is complaining that
http://ms-windows-store:PDP?PFN=WebMarketing.Coolinarika_tp6yaakah33yj

is not a valid link. Note the http added in front. If I try it with
ms-windows-store://PDP?PFN=WebMarketing.Coolinarika_tp6yaakah33yj

it still is not recognized as a link by the SO engine.

A: That's because it's not a valid link anywhere except in Windows 8.
This doesn't seem worth fixing - we don't support every possible link protocol out there and I don't think your example really needs to be a link either. You're showing the link format for the OP and that seems sufficient.


text:
Q: Unable to display received messages with SMACK api in JAVA I have made a simple client using SMACK api and OpenFire on localhost. As of now, I have two users say X and Y. Whenever anyone logs in to the client, there is a send button which sends a message to user Y. I've checked the XMPP debug manager and I'm able to send/receive messages there. However, I'm unable to display those messages in a JLabel that I have alloted for displaying the messages. If the User Y hits the send button, as per the functionality it sends a message to himself and that comes up on the JLabel. But when user X hits the send button, the message is received, however it is not displayed/updated on the Y's JLabel.
Interestingly, everything works as it should with gtalk configuration.
The structure is as follows:
WelcomeUser.java:
Is the welcome form with username and password prompt. On hitting the login button :
it sets the ChatBoard class visible and passes on the username password to the constructor of ChatBoard.
Code:
chBoard=new ChatBoard(username.getText(),password.getText());
                chBoard.setVisible(true);
                setVisible(false);

Here is the code for ChatBoard.java:
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Collection;

import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.border.EmptyBorder;

import org.jivesoftware.smack.Chat;
import org.jivesoftware.smack.ConnectionConfiguration;
import org.jivesoftware.smack.MessageListener;
import org.jivesoftware.smack.Roster;
import org.jivesoftware.smack.RosterEntry;
import org.jivesoftware.smack.XMPPConnection;
import org.jivesoftware.smack.XMPPException;
import org.jivesoftware.smack.packet.Message;

public class ChatBoard extends JFrame implements MessageListener {

    private static final long serialVersionUID = 1L;
    private JPanel contentPane;
    static String username, password;
    static XMPPConnection connection;
    private JTextField textField;
    static JLabel board = new JLabel("");
    static Chat chat;

    public void sendChat() {
        try {
            chat = connection.getChatManager().createChat(
                    "userY@my-pc/Smack", this);
            chat.sendMessage("Hello, This is " + username);
        } catch (XMPPException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

    }

    /**
     * Create the frame.
     */
    public ChatBoard(String user, String pass) {

        username = user;
        password = pass;

        ////
                   ///JFrame creation code ommited for this thread.
        // ////////////////////////////////////////////

        XMPPConnection.DEBUG_ENABLED = true;

        ConnectionConfiguration config = new ConnectionConfiguration(
                "127.0.0.1");

        connection = new XMPPConnection(config);

        try {
            connection.connect();
            System.out.println("Connected...");
        } catch (XMPPException e) {

            e.printStackTrace();
            System.out.println("Not Connected. Error :" + e.getMessage());
        }

        try {
            connection.login(username, password);
            System.out.println("Logged in...");
        } catch (XMPPException e) {

            e.printStackTrace();
            System.out.println("Not Logged in. Error :" + e.getMessage());
        }

        Roster roster = connection.getRoster();
        Collection<RosterEntry> entries = roster.getEntries();

        System.out.println("\n\n" + entries.size() + " buddy(ies):");
        for (RosterEntry r : entries) {
            System.out.println(r.getUser());
        }

        // /////////////////////////////////

    }

    @Override
    public void processMessage(Chat arg0, Message arg1) {
        // TODO Auto-generated method stub

        board.setText(board.getText() + arg1.getBody());
        System.out.println(arg1.getFrom() + ":" + arg1.getBody().toString());

    }

}

I'm new to this, so forgive me if there are any silly mistakes. Your help would be really appreciated.
Misc. Details: OpenFire 3.7.1 on localhost with SMACK 3.2.2

A: Have a look at the bottom of http://www.igniterealtime.org/builds/smack/docs/latest/documentation/messaging.html. For incoming chats from another user you have to override ChatManagerListener
Can you set a breakpoint on processMessage and does it hit that breakpoint? If so it might just be a matter of making sure the:
board.setText()

occurs on the Swing event dispatch thread
So try making your processMessage like this :
@Override
public void processMessage(Chat arg0, Message arg1) {
    // TODO Auto-generated method stub

    try
    {
        SwingUtilities.invokeAndWait(new Runnable()
        {

            @Override
            public void run()
            {
                board.setText(board.getText() + arg1.getBody());
            }
        });
    }
    catch (InvocationTargetException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (InterruptedException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    System.out.println(arg1.getFrom() + ":" + arg1.getBody().toString());

}

A: I added this code in chatBoard just at the end of the constructor mentioned in my code and it seems to work now :-) Thanks alex.p!
connection.getChatManager().addChatListener(new ChatManagerListener() {

                public void chatCreated(final Chat chat, final boolean createdLocally) {

                    chat.addMessageListener(new MessageListener() {

                        public void processMessage(Chat chat, Message message) {

                            //JOptionPane.showMessageDialog(null, "Rec: For " + chat.getParticipant() + " from " + message.getFrom() + "\n" + message.getBody());

                            String sender=message.getFrom();

                            String senderNames=sender;

                            System.out.println("Received message: " + (message != null ? message.getBody() : "NULL"));

                            board.setText(board.getText()+"\n "+ message.getFrom()+" : "+ message.getBody());
                            //PrivateChatManager.receiveMessage(sender, senderNames, message.getBody());

                        }

                    });

                }
        });

A: Hope this code can help you:
public void processMessage(Chat aChat, Message aMessage) {

    final XmppBot bot = this.xmppBot;
    final Chat chat = aChat;
    final Message message = aMessage;

    log.debug("message received, type {}", message.getType().toString());

    if (message.getBody() != null) {

        Runnable runnable = new Runnable() {

            public void run() {

                Thread.currentThread().setName("Chat: "+chat.getParticipant()+ " Message: "+ message.getBody());

                PrintWriter threadPrintWriter = null;

                threadPrintWriter = new PrintWriter(new ChatWriter(chat));

                bot.getContext().setChat(chat);
                bot.getContext().setPrintWriter(threadPrintWriter);

                bot.processCommand(message.getBody());

                bot.getContext().removeMultiUserChat();
                bot.getContext().removePrintWriter();

            }
        };

        Thread t = new Thread(runnable);
        t.start();
    }

}


text:
Q: Including Eigen in my project redefines the standard int to Eigen::DenseIndex - how to use the normal ints? I'm trying to create a vector to input some data from a .txt file, but I get the error:
no operator ">>" matches these operands

operand types are: std::ifstream >> std::vector<Eigen::DenseIndex, std::allocator<Eigen::DenseIndex>>

My code is:
dataIn.open("data.txt");
vector<int> hnew;
dataIn >> hnew;
dataIn.close();

data.txt is just a long vector of space separated ints. What can I do?

A: Eigen::DenseIndex is just a type alias for int. It's not the problem here.
The compiler is warning you don't have an overload
template <typename T, typename A>
std::istream & operator >>(std::istream &, std::vector<T. A> &)

There isn't one provided by default. You can use istream_iterator to construct your hnew like this:
dataIn.open("data.txt");
vector<int> hnew(istream_iterator<int>(dataIn), istream_iterator<int>());


text:
Q: Should I use interfaces in Python (so my code will be more testable and following good practices)? I've never coded in Python. In languages like C# or Java a lot of people write interfaces for (almost) every class so the code can be more easily testable (by implementing IoC) or other reasons and is considered good practice by many.
I'm confused because Python don't have built in interfaces as the other languages I've worked with, but there are some libraries that give similar options.
Is using interfaces considered good practice in Python programmers' world and should I use them?

A: The type systems of Python on the one hand and C# and Java on the other hand work in a fundamentally different way.
C# and Java use a nominal type system: Two types are the same if they have the same name. Additionally, they use strong typing: assignment (and parameter passing) between references is only allowed if the target type is in the set of types formed by enumerating the source's type and declared sub-types.
Python on the other hand uses a structural type system: Two types are considered compatible if you can do the same operations on them. This is also called duck-typing (if it quacks like a duck and walks like a duck, then you can treat it as a duck).
Furthermore, type declarations for function parameters and return types are a relatively new addition to Python and they are not actively used by the Python runtime environment.
As Python doesn't require the match in type names and doesn't actively check type matches on function calls, there has traditionally been much less incentive to use interface declarations in Python than in C#/Java. And due to the structural typing, there is still no need to explicitly mention a class implements interface X. A function that is documented to need an argument of type X will accept anything that is structurally compatible with X, not just classes that explicitly mention implementing X.
Thus, interfaces in Python are useful documentation tools, but they are not needed to support Dependency Injection or Mocking in testcases, like they are in C# and Java.


text:
Q: dpi & dppx chromium browsers issue Hi guys today i got an issue with css bootstrap, whenever i change the extension of my index from .html to .php this error come out in chromium browsers:

Consider using 'dppx' units instead of 'dpi', as in CSS 'dpi' means dots-per-CSS-inch, not dots-per-physical-inch, so does not correspond to the actual 'dpi' of a screen. In media query expression: only screen and (-webkit-min-device-pixel-ratio: 1.5), only screen and (min-resolution: 144dpi)

I'm using Bootstrap as CSS framework (bootstrap.min.css & bootstrap.responsive.css)
I'm using no dpi or dppx in my stylesheet that's why i'm confused.
CSS Line that i think the problem is in: html{font-size:100%;-webkit-text-size-adjust:100%;-ms-text-size-adjust:100%;}
and this is my stylesheet (i'm just including css files) :
@import url(font-awesome.css);
@import url(bootstrap.min.css);
@import url(bootstrap-responsive.css);
@import url(responsive-slider.css);
@import url(theme.css);

I have already tried this in my stylesheet file: min-size:144dpi;min-size:1.5dppx; but the problem still in.
please if you need anything just ask me, my html script is too long i can't past it here also i'm sure there is no problem with my Html, just the issue of size unti in chromium browsers.

A: Problem solved, the problem was in my include "file.php" and if anyone else had the same problem i suggest to use

dpi & dppx unit size in the same stylesheet

goodluck


text:
Q: Trapping ADO Provider cannot be found error in Delphi I have an application written in Delphi that uses an iSeries ODBC connection.
There are some workstations where I do not want to install the iSeries software, and on these workstations, I won't be updating any of these databases anyway.
Is there a way I can trap when this error message is generated?  At that point, I can just set a variable like NoUpload to true and not allow the connection on the workstation.
It appears to happen before I ever attempt to even open one of the tables - just by having the ConnectionString set when the application starts fires the message.
Thanks in advance!

A: You can check the existing ADO providers of the system with ADODB.GetProviderNames

A: Ideally, you should look for an option to check your condition without an exception being raised. So Sir Rufo's answer is a good place to start.
Another option might be to not include the Provider in the ConnectionString, but set it independently via the Provider property at run-time (most likely only after confirming that it's supported).
However, since you mentioned you're getting an exception before you even attempt to open a table, there are a few things to check (assuming you've been setting up your components at design time):

*

*Have any data sets accidentally been left Active at design time?

*Has the Connection been left active at design time?

*Are there any options in the ConnectionString that could immediately trigger the error?

Failing the above you could provide a hook for application exceptions. (And really more of a last ditch effort.)
Declare a handler method using with the following signature: TExceptionEvent = procedure (Sender: TObject; E: Exception) of object;. And assign it to Application.OnException. E.g.
procedure Handle(ASender: TObject; E: Exception);
begin
  if ISeriesNotInstalledError(E) then
  begin
    FNoUpload := True;
  end
  else
  begin
    Application.ShowException(E);
  end;
end;

NOTE: There are some important considerations in following this approach. Since you see this as a standard Use Case, you don't want to be bothering your users with messages. This is also much better than a localised exception handler (a common programming error) because if a caller routine triggers this error you don't want the caller to mistakenly run as if nothing went wrong; when quite clearly something did.


text:
Q: Powershell can't load Windows.Markup.XamlReader I just took the sample code from foxdeploy.com to create a PowerShell script with GUI.
It works on a Windows 10 machine, but for some reason it doesn't on a Windows 7 or Windows Server 2008 R2, where it should be running at the end (not this code but the final PS script with GUI).
Here's the code:
#ERASE ALL THIS AND PUT XAML BELOW between the @" "@
$inputXML = @"
<Window x:Class="WpfApplication2.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WpfApplication2"
        mc:Ignorable="d"
        Title="FoxDeploy Awesome Tool" Height="416.794" Width="598.474" Topmost="True">
    <Grid Margin="0,0,45,0">
        <Image x:Name="image" HorizontalAlignment="Left" Height="100" Margin="24,28,0,0" VerticalAlignment="Top" Width="100" Source="C:\Users\Stephen\Dropbox\Docs\blog\foxdeploy favicon.png"/>
        <TextBlock x:Name="textBlock" HorizontalAlignment="Left" Height="100" Margin="174,28,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="282" FontSize="16"><Run Text="Use this tool to find out all sorts of useful disk information, and also to get rich input from your scripts and tools"/><InlineUIContainer>
                <TextBlock x:Name="textBlock1" TextWrapping="Wrap" Text="TextBlock"/>
            </InlineUIContainer></TextBlock>
        <Button x:Name="button" Content="get-DiskInfo" HorizontalAlignment="Left" Height="35" Margin="393,144,0,0" VerticalAlignment="Top" Width="121" FontSize="18.667"/>
        <TextBox x:Name="textBox" HorizontalAlignment="Left" Height="35" Margin="186,144,0,0" TextWrapping="Wrap" Text="TextBox" VerticalAlignment="Top" Width="168" FontSize="16"/>
        <Label x:Name="label" Content="ComputerName" HorizontalAlignment="Left" Height="46" Margin="24,144,0,0" VerticalAlignment="Top" Width="138" FontSize="16"/>
        <ListView x:Name="listView" HorizontalAlignment="Left" Height="156" Margin="24,195,0,0" VerticalAlignment="Top" Width="511" FontSize="16">
            <ListView.View>
                <GridView>
                    <GridViewColumn Header="Drive Letter" DisplayMemberBinding ="{Binding 'Drive Letter'}" Width="120"/>
                    <GridViewColumn Header="Drive Label" DisplayMemberBinding ="{Binding 'Drive Label'}" Width="120"/>
                    <GridViewColumn Header="Size(MB)" DisplayMemberBinding ="{Binding Size(MB)}" Width="120"/>
                    <GridViewColumn Header="FreeSpace%" DisplayMemberBinding ="{Binding FreeSpace%}" Width="120"/>
                </GridView>
            </ListView.View>
        </ListView>

    </Grid>
</Window>

"@

$inputXML = $inputXML -replace 'mc:Ignorable="d"','' -replace "x:N",'N'  -replace '^<Win.*', '<Window'

[void][System.Reflection.Assembly]::LoadWithPartialName('presentationframework')
[xml]$XAML = $inputXML
#Read XAML

    $reader=(New-Object System.Xml.XmlNodeReader $xaml)
  try{$Form=[Windows.Markup.XamlReader]::Load( $reader )}
catch{Write-Host "Unable to load Windows.Markup.XamlReader. Double-check syntax and ensure .net is installed."}

#===========================================================================
# Store Form Objects In PowerShell
#===========================================================================

$xaml.SelectNodes("//*[@Name]") | %{Set-Variable -Name "WPF$($_.Name)" -Value $Form.FindName($_.Name)}

Function Get-FormVariables{
if ($global:ReadmeDisplay -ne $true){Write-host "If you need to reference this display again, run Get-FormVariables" -ForegroundColor Yellow;$global:ReadmeDisplay=$true}
write-host "Found the following interactable elements from our form" -ForegroundColor Cyan
get-variable WPF*
}

Get-FormVariables

#===========================================================================
# Actually make the objects work
#===========================================================================

Function Get-DiskInfo {
param($computername =$env:COMPUTERNAME)

Get-WMIObject Win32_logicaldisk -ComputerName $computername | Select-Object @{Name='ComputerName';Ex={$computername}},`
                                                                    @{Name='Drive Letter';Expression={$_.DeviceID}},`
                                                                    @{Name='Drive Label';Expression={$_.VolumeName}},`
                                                                    @{Name='Size(MB)';Expression={[int]($_.Size / 1MB)}},`
                                                                    @{Name='FreeSpace%';Expression={[math]::Round($_.FreeSpace / $_.Size,2)*100}}
                                                                 }

$WPFtextBox.Text = $env:COMPUTERNAME

$WPFbutton.Add_Click({
$WPFlistView.Items.Clear()
start-sleep -Milliseconds 840
Get-DiskInfo -computername $WPFtextBox.Text | % {$WPFlistView.AddChild($_)}
})
#Sample entry of how to add data to a field

#$vmpicklistView.items.Add([pscustomobject]@{'VMName'=($_).Name;Status=$_.Status;Other="Yes"})

#===========================================================================
# Shows the form
#===========================================================================
write-host "To show the form, run the following" -ForegroundColor Cyan
$Form.ShowDialog() | out-null

The script seems to fail at line 49 at the $Form.FindName
$xaml.SelectNodes("//*[@Name]") | %{Set-Variable -Name "WPF$($_.Name)" -Value $Form.FindName($_.Name)}

What I noticed so far, is that $Form doesn't return anything on Windows 7 while on Windows 10 it returns some properties. So I think the real problem is at line 42:
 try{$Form=[Windows.Markup.XamlReader]::Load( $reader )}
catch{Write-Host "Unable to load Windows.Markup.XamlReader. Double-check syntax and ensure .net is installed."}

And when I execute the script just to line 43, it returns the catch-message.
So how can I fix this? The latest .NET version is installed and I guess the syntax should be alright because it works on Wondows 10.

A: I had the same problem. I have designed a form in VS 2015 Enterprise. The XAML was exactly the same as your (Tutorial from FoxDeploy). On my personal client (Windows 7, Powershell 4.0, .NET Framework 4.0) it was working fine. But when I was trying to launch the the script on a Windows Server 2008 R2 (Powershell 2.0, .NET 3.5) I ran into the same problem as you did. Updateing the .NET & Powershell version was not a opinion, bencause its a productive system where customers are using services. So I found a workaround to run my XAML on this environment:
I edited the XAML "window" tag from this:
<Window x:Class="WpfApplication2.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApplication2"
    mc:Ignorable="d"
    Title="FoxDeploy Awesome Tool" Height="416.794" Width="598.474" Topmost="True">

to this:
<Window
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="FoxDeploy Awesome Tool" Height="416.794" Width="598.474" Topmost="True">

After this as a last step I had to run the powershell in single threaded apartment mode.
powershell -sta

Powershell ISE is already by default in this mode.
I can't explain why removed code made this error happening on the system but maybe I can help some other guys who have to fight with XAML & Powershell on an "old" windows environment.

A: [Windows.Markup.XamlReader] requires the PresentationFramework assembly so add the following code at the beginning of your file:
Add-Type -Assembly PresentationFramework

A: I know it's several years late. But i just ran into this issue playing around with WPF/Powershell.
I ended up going through and removing each item in groups , and then one by one, to see if it was one of the objects causing this error.
Turned out that when i was designing my WPF in visual studio i double clicked one, which i knew i did... just didnt think it would mess anything up.
The " TextChanged="EndHour_txtBox_Copy_TextChanged" line is what was throwing this erorr for me. Just something to look out for in the future. Not all WPF items work out of the box.


text:
Q: Webkit: Encoding I created a html file with gvim on Ubuntu. When I open this file on Windows with Safari or Google Chrome it's not showing é ë correctly. When I check the encoding on my windows box with vim :set encoding? it returns latin1 and on Ubuntu this returns utf-8.
Could anybody explain why this is happening and how I can fix this?

A: *

*Make sure that you're actually saving the file as UTF-8.

*Is this in your <head>?
<meta http-equiv="content-type" content="text/html; charset=UTF-8">

*How are you serving the file? If you're using an actual HTTP server (rather than just opening a local .html file) make sure to serve it with the right headers:
Content-Type: text/html; charset=UTF-8

If none of these help, could you show us the actual file (even a Dropbox download link would help)?

A: You need to consider how Chrome is supposed to know which encoding to use.
Usually, this is with an HTTP header or a <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1"> if you don't have control over the headers.
I imagine in your case you have neither.  If you've not set the source code encoding using e.g. magic comment headers like # vim: set fileencoding=<encoding name> , then the encoding your editor reports will depend on the system defaults.  And in any case, you browser won't know how to interpret that.


text:
Q: Is it possible to freeze a dataclass object in __post_init__() or later? I'm wondering whether it's possible to "freeze" a dataclass object in post_init() or even after an object was defined.
So instead of:
@dataclass(frozen=True)
class ClassName:
    var1: type = value

Having something like:
@dataclass
class ClassName:
     var1: type = None
def __post_init__(self):
     self.var1 = value
     FREEZE()

Or even sth like:
a = ClassName()
FREEZE(a)

Possible or not and why?

A: No, it isn't. But "frozen" can be subverted trivially, just use:
@dataclass(frozen=True)
class ClassName:
     var1: type = value
def __post_init__(self):
    object.__setattr__(self, 'var1', value)


text:
Q: How to highlight current menu item in bootstrap in Laravel? working with laravel 5.6 and I have following sidebar.blade.php file sidebar.blade.php

     App Settings
     My Ads
     Support
     Sandbox Account
     QuickStart Overview
     Documentation

now I need highlight current menu item in above sidebar.blade.php file how can do it? current jquery codes is working only highlight in same page but when I go using link other page current link it is not highlight (as an example if I go to myads link from home page in myads page myads menu is not highlight)
Edit
hope to use this sidemenu blade file as include file with other blade files

A: For example, if your URL has sites/*/edit you can check it in this way.
is('sites/*/edit') ? 'active' : '' }}">

A: use My Helper Functions which I have Created for Handling all the situations of the active menu
https://gist.github.com/AManojKiran/56a9fd3332795edec8cc80b4dd4928d3


text:
Q: @Autowired and configuring beans different way I have
public class Foo
{
}

and I have
public class Bar
{

    @Autowired
    Foo foo;

}

Now, I want to be able to configure Foo differently. So, Bar will have the Foo which will use one Resource and Baz will have the Foo with different Resource.
I tried to add it in .xml:
<bean id="Foo1" class="com.something.Foo" >
  <constructor-arg value="#{ appProperties.resourece1 }"/>
</bean>

<bean id="Foo2" class="com.something.Foo" >
  <constructor-arg value="#{ appProperties.resourece2 }"/>
</bean>

I created a constructor
public class Foo
{

    public Foo(Resource resource)
    {
    }
}

And I used
 @Autowired @Qualifier("Foo1")
 Foo foo;

However, it throws No default constructor found; nested exception is java.lang.NoSuchMethodException: com.ssomething.Foo.()
So, it looks like it ignores .xml at all.
What is the right way of solving this, because it looks like I am doing something wrong? Should I dump @Autowired at all in such case?


text:
Q: Element font-family must be declared when i open a project from github ,the folder from res folder has a xml resource product_famliy.xml but android studio has a error:
Information:Gradle tasks [clean, :app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies]
E:\googledownload\PaperPlane-master\app\src\main\res\font\product_family.xml
Error:Error: Unsupported type 'font'
Error:Execution failed for task ':app:mergeDebugResources'.
> E:\googledownload\PaperPlane-master\app\src\main\res\font\product_family.xml: Error: Unsupported type 'font'
Information:BUILD FAILED
Information:Total time: 21.311 secs
Information:2 errors
Information:0 warnings
Information:See complete output in console

<?xml version="1.0" encoding="utf-8"?>
<font-family xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">

    <font
        android:fontStyle="normal"
        android:fontWeight="400"
        android:font="@font/product_sans_regular"
        app:fontStyle="normal"
        app:fontWeight="400"
        app:font="@font/product_sans_regular"/>

    <font
        android:fontStyle="italic"
        android:fontWeight="400"
        android:font="@font/product_sans_italic"
        app:fontStyle="italic"
        app:fontWeight="400"
        app:font="@font/product_sans_italic"/>

</font-family>

A: I guess you need Android Studio 3.0

A: It is a new feature in new Android O version (android 26).
To get it working with fonts in XML you need to have installed Android Studio 3.x and compile with the newest verion (26).
In addition see here: https://developer.android.com/preview/features/working-with-fonts.html


text:
Q: Getting error when using addTo in bootstrap to preload db I have the following classes: SAMPLE_TYPE and SAMPLE_PARAMETER. Each sample can have many parameters. In my bootstrap I have created a parameter and the sample:
 def r = new SampleParameter(name: "Color", value:"Red").save(failOnError: true)
 def b = new SampleType(sampleName: "Blood")
        .addToSampleType(r)
        .save(failOnError: true)

I keep getting an error 'no signature of method com.SampleType.addToSampleType() is applicable for argument types
I just want to add a parameter to a sample

A: At first glance it looks to me like you're trying to add a SampleParameter (variable named r) as a SampleType.  Maybe the method should be .addToSampleParameter(r)?  If that's not the case can you please post a copy of your domian classes?


text:
Q: Ruby on Rails: How to pass variable between controller functions? I need to use params[:number] from the new function in the create function, how would I go about doing this?
def new
   @test_suite_run = TestSuiteRun.new

    @tests = Test.find(:all, :conditions => { :test_suite_id => params[:number] })
end

def create
    @test_suite_run = TestSuiteRun.new(params[:test_suite_run])

    @tests = Test.find(:all, :conditions => { :test_suite_id => //I need the same params[:number] here})
end

EDIT: I guess I am confused as the differences between new and create then. I am taking in the parameter :number by passing it to new.
new_test_suite_run_path(:number => ts.id)
I am then using it to generate the form. I don't understand what to do in the create function then. If I remove the create function in the controller, when I submit the form in new, it gives me an error saying that there is no create action in the controller. Does that mean I have to move everything in new to the create function? How would that be possible, would I have to create a create.html.erb and move all my form information?

A: You can use Flash:
http://api.rubyonrails.org/classes/ActionDispatch/Flash.html

The flash provides a way to pass temporary objects between actions.
  Anything you place in the flash will be exposed to the very next
  action and then cleared out.

def new
   @test_suite_run = TestSuiteRun.new
   @tests = Test.find(:all, :conditions => { :test_suite_id => params[:number] })

   flash[:someval] = params[:number]
end

def create
    @test_suite_run = TestSuiteRun.new(params[:test_suite_run])

    @tests = Test.find(:all, :conditions => { :test_suite_id => flash[:someval] })
end

A:
I guess I am confused as the differences between new and create then.

Let's address this issue first.
new method generates a view for a form where Rails build a TestSuiteRun instance. This instance exists only memory temporally.
create method takes the data entered in the form, and actually saves the instance created into database permanently.
I don't think you need to change your new method.
Try changing your create method to this.
def create
  @test_suite_run = TestSuiteRun.new(params[:test_suite_run])
  @test_suite_run.save
end


text:
Q: Libgdx - collisions between two moving circles I've many circles randomly spawned in my screen and moving in different directions. I'm now dealing with collisions between them. The code below just compare any circle on the screen with any other one and should detect collisions by the classic formula. It more or less works, my issue is that I need to use a "magic number" discovered by tries and I can't figure out the reason.
(Every circle has the same radius)
Code:

Target item1, item2;
    int magicNumber = 40;
    float dX, dY;
    for (int i = len; --i >= 0;) {
        item1 = activeTargets.get(i);
        for(int j = len; --j >= 0;){
            if(i!=j) {
                item2 = activeTargets.get(j);
                dX = (item1.getPosition().x > item2.getPosition().x) ? item1.getPosition().x - item2.getPosition().x : item2.getPosition().x - item1.getPosition().x;
                dY = (item1.getPosition().y > item2.getPosition().y) ? item1.getPosition().y - item2.getPosition().y : item2.getPosition().y - item1.getPosition().y;
                if ( (dX*dX) + (dY*dY) < (magicNumber*4*item1.body.radius*item1.body.radius) ) {
               // if(item1.body.overlaps(item2.body)) {
                    if(!activeTargets.get(i).collide && !activeTargets.get(j).collide ) {
                        activeTargets.get(i).collide = true;
                        activeTargets.get(j).collide = true;
                        Gdx.app.log("COLLIDE", "Collision between " + activeTargets.get(i).color.toString() + " and " + activeTargets.get(j).color.toString());
                    }
                }
            }
        }
    }


text:
Q: PHP Regex - To accept all UTF-8 characters, No trailing spaces, Excluding a symbol, with a range between 2-16 length I am having trouble trying to figure out the correct PHP regex to match these conditions:

*

*Accepts all UTF-8 Characters

*Accepts Numbers

*Accepts a string that is between the range of 2-16 characters

*Excludes the "@" symbol

*Accepts all other symbols for example: "!#$%^&*))¶¡ª£"

*Allows a single space between characters, but not multiple

*Does not pass with trailing spaces for example:

"Hello World!" //should be true
" Hello World! " //should be false
"Hello   World!" //should be false
The following examples should fail:
"a" //should fail because the length is less than 2
"whatsup@gmail.com" //should be false because of @ symbol
The following examples should pass:
"£ª¡™ƒ˚å 象形字 123" //should be true
What's up? 123" //should be true
"!#$%^&*(){}-_+" //should be true
So far what I have is:
/^((?!@).)*$/
This PHP regular expression currently accepts characters, excludes the @ symbol, and includes numbers.
Any help will be greatly appreciated!

A: You can use this lookahead based regex to satisfy all the conditions:
/^(?=.{2,16}$)[^@\s]+(?:\h[^@\s]+)*$/gum

RegEx Demo


text:
Q: why the loading sign doesn't appear when i running the code on chrome "works on firefox"? I had a function to fill google maps in my html page and I call function
popUpLoadingScreen()
{
    $("#mapLoadingUIId").css("display","block");
}

function dismissLoadingScreen()
{
    $("#mapLoadingUIId").css("display", "none");
}

to show loading message while the markers rendered on the map but it didn't appear, and when I put a break point to know what's the problem the sign appears but in the normal run it doesn't appear so I what to know where is the problem?
the HTML part:

    Loading...

The css part:
.mapLoadingUI {
display:none;
position: fixed;
left: 324px;
top: 48px;
min-width: 1500px;
min-height: 100px;
z-index: 9999;
background-color:#87cefa;
z-index:1000;
text-align:center;
line-height: 100px;
font-family: Arial;
font-size: 14px;
font-weight: 500;
font-style: normal;
font-stretch: normal;
}

The js that call the functions:
function renderWells(wells) {
    popUpLoadingScreen();
    //some code to run
    dismissLoadingScreen();
}

A: Probably the code runs too fast and you are not able to see the message (It explains why you are still able to see it by putting a breakpoint). Consider also that the map rendering could be asynchronous and renderWells execution is completed before the actual map loading.
Take a look to the gmaps events documentation and check the available events you can handle in order to figure out when the loading is complete.
Documentation: https://developers.google.com/maps/documentation/javascript/events

A: The dismissLoadingScreen() method is probably being called much before you intend it. Check you code for which stage are you dismissing the loader. I think its too early.


text:
Q: Load debug layers in VS 2015 (VK_ERROR_LAYER_NOT_PRESENT) I am currently trying to force Visual Studio to use the debug layer dlls for Vulkan, but somehow it is unable to load the libraries.
My steps were those:

*

*Clone https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers/blob/master/BUILD.md

*Build for Visual Studio 2015 (Release and Debug)

*In my Vulkan Application i put this into the Environment variable (for x64 - Debug) (Project Settings -> Debugging): VK_LAYER_PATH=F:\Projects\Vulkan-LoaderAndValidationLayers\build\layers\Debug
When i start my application it runs until it tries to create the Instance, where it returns VK_ERROR_LAYER_NOT_PRESENT and i can see in the output window of Visual Studio that the dlls were indeed not loaded at all. If i just put the "normal" path to the Vulkan binaries in the path above it works fine again. I already checked that there are also the .json files present. This problem is also present if i try to use the Release-DLLs from the LoaderAndValidationLayers folder.
What am i doing wrong? Does anyone have any idea how to make this work?
EDIT: I found out that VK_LAYER_LUNARG_threading seems to be the problem. If i use VK_LAYER_LUNARG_standard_validation it does not load anything. If i just specify all layers included manually (described here: https://vulkan.lunarg.com/app/docs/v1.0.3.1/layers) without the VK_LAYER_LUNARG_threading layer it does work fine. Any idea why this might be?

A: Ok i think i found the problem. But i am still not 100% certain of why this occurs.
I compared the two VkLayer_threading.json files and noticed that the names differ (i suspect a name change from version 1.0.3 to 1.0.5).

*

*1.0.3 ("name": "VK_LAYER_LUNARG_threading") -> 1.0.5 ("name": "VK_LAYER_GOOGLE_threading")

But even though i am also using the debug vulkan-1.lib loader library out of the Vulkan-LoaderAndValidationLayers repo (https://github.com/KhronosGroup/Vulkan-LoaderAndValidationLayers) it is still unable to load the right library.
My strongest guess at the moment is that since the SDK for Windows is still on version 1.0.3.1 it also still uses the old name inside the meta-layer (VK_LAYER_LUNARG_threading) and thus is not finding the newly named layer. I edited the .json file for the moment and it works again.
EDIT: I just confirmed my guess. After installing the recently released 1.0.5 SDK-update for Windows, i had to undo my above renaming to get it working again. So be careful when using the most up-to-date version of the LoaderAndValidationLayers repo, because it could contain changes which are not yet reflected in the available SDK version.

A: Looks like they've slightly changed names of the layers.
Here is the list that works for me:
const char* enabledLayerNames[] = {
    "VK_LAYER_GOOGLE_threading",
    "VK_LAYER_GOOGLE_unique_objects",
    "VK_LAYER_LUNARG_api_dump",
    "VK_LAYER_LUNARG_device_limits",
    "VK_LAYER_LUNARG_draw_state",
    "VK_LAYER_LUNARG_image",
    "VK_LAYER_LUNARG_mem_tracker",
    "VK_LAYER_LUNARG_object_tracker",
    "VK_LAYER_LUNARG_param_checker",
    "VK_LAYER_LUNARG_screenshot",
    "VK_LAYER_LUNARG_swapchain",
//     "VK_LAYER_LUNARG_vktrace",
};

(I just took "name" fields from "C:\VulkanSDK\1.0.5.0\Bin\VkLayer_*.json" files.)
"VK_LAYER_LUNARG_vktrace" is commented, because it provokes an  error VK_ERROR_INITIALIZATION_FAILED ("Initialization of an object could not be completed for implementation-specific reasons") on my rig.
You might also want to check if HKEY_LOCAL_MACHINE\SOFTWARE\Khronos\Vulkan\ExplicitLayers registry key has correct paths to the *.json files
My environment setup:

*

*GPU Nvidia GeForce GT 730M (Kepler)

*OS: Windows 10 x64

*I've first installed fresh Nvidia driver v 364.51 (tick "clean installation")

*uninstalled LunarG VulkanSDK 1.0.3 along with remains (with Revo Uninstaller)

*then installed LunarG VulkanSDK 1.0.5

P.S. I haven't edited any files, nor registry. I haven't even recompiled for VS 2015. And it all still links and works somehow.
P.P.S. My physical device reports API version 1.0.4.


text:
Q: How to prove this function?
The third question:
the left side is $f(f(x))$,and the right side is $2f(x)$
So, we need prove $f(f(x))=2f(x)$
use the $f(x)=\lfloor 2x \rfloor$
So double $\lfloor 2x \rfloor=2 \lfloor 2x \rfloor$
And I do not know how to slove it!
Thank you for answering!

A: $$f(x) = \lfloor 2x \rfloor \in \mathbb{Z}$$
Hence $2f(x) \in \mathbb{Z}$.
Hence $$f(f(x))=\lfloor 2f(x)\rfloor=2f(x)$$


text:
Q: Conditional Redirect with htaccess I have a site: blog.example.com.
I want blog.example.com to go to example.com/news
But I want blog.example.com/tag/mytag or blog.example.com/category/mycategory to go to example.com/tag/mytag or example.com/category/mycategory
So far I have my .htaccess like this but of course it doesnt work:
RewriteEngine on
RewriteRule ^(.*)$ http://www.example.com/$1 [R=301,L]
RewriteRule ^(.*)$ http://www.example.com/news/ [R=301,L]

A: You can use this in root .htaccess of blog.example.com:
RewriteEngine on

RewriteRule ^/?$ http://www.example.com/news [R=301,L]
RewriteRule ^(.+)$ http://www.example.com/$1 [R=301,L,NE]


text:
Q: NSMutableSet Set Minus Set Not Working I must be missing something fundamental - hopefully someone can point it out to me.
I have two NSSets. Set A contains 40 NSNumber values and set B contains 20 NSNumber values. Set A contains all of set B's 20 values plus 20 other values not shared by the sets.
What I'd like is to do: NSSet *newSet = Set A - Set B, where the new set only contains the 20 values from set A not contained in set B. Although I am using 'minusSet', my new set always contains all 40 of the original values. I have logged the contents of each set A and B to make sure that they contain the contents that I described above.
Here is my code:
1) Create set A (contains 40 NSNumbers)
NSMutableSet *fetchedThreadIds = [NSMutableSet setWithArray:[threadedJsonMessages valueForKey:@"tid"]];

2) Create set B (contains 20 NSNumbers which are also in set A)
NSSet *savedThreads = threadIdsForSavedThreads([fetchedThreadIds allObjects]);

3) Attempt to subtract set B from set A:
[fetchedThreadIds minusSet:savedThreads];

4) Add all remaining objects to new array:
threadIdsForMessageFetch = [fetchedThreadIds allObjects];

However, threadIdsForMessageFetch contains 40 objects rather than 20. When I print each set I get:
Set A
{(
2540000000136987400,
2540000000141777055,
2540000000144609986,
2540000000125243232,
2540000000144610000,
2320000003021796109,
2540000000144375484,
2540000000136185765,
2540000000135311778,
2540000000135311816,
2540000000124128112,
2540000000125012438,
2480000001401011569,
2540000000144610015,
2540000000135311744,
2540000000139755359,
2540000000135311848,
2540000000143846308,
2540000000145732667,
2540000000143985955,
2540000000136185740,
2540000000135756434,
2540000000134373148,
2540000000140816249,
2540000000130860748,
2540000000127140093,
2540000000143526120,
2540000000102176392,
2540000000144609962,
2540000000128826163,
2540000000136185694,
2540000000133208691,
2540000000144555891,
2540000000138091838,
2540000000130179358,
2540000000126098342,
2540000000145162237,
2540000000131688927,
2540000000136185715,
2540000000143526101
)}

Set B
{(
2540000000136987400,
2540000000138091838,
2540000000143985955,
2540000000144555891,
2540000000140816249,
2540000000145732667,
2540000000144609986,
2540000000144610000,
2540000000144609962,
2540000000144610015,
2540000000141777055,
2540000000143526101,
2540000000143526120,
2480000001401011569,
2540000000136185694,
2540000000145162237,
2540000000143846308,
2320000003021796109,
2540000000144375484,
2540000000139755359
)}

New Array:
<__NSArrayI 0xc4b8e40>(
2540000000136987400,
2540000000141777055,
2540000000144609986,
2540000000125243232,
2540000000144610000,
2320000003021796109,
2540000000144375484,
2540000000136185765,
2540000000135311778,
2540000000135311816,
2540000000124128112,
2540000000125012438,
2480000001401011569,
2540000000144610015,
2540000000135311744,
2540000000139755359,
2540000000135311848,
2540000000143846308,
2540000000145732667,
2540000000143985955,
2540000000136185740,
2540000000135756434,
2540000000134373148,
2540000000140816249,
2540000000130860748,
2540000000127140093,
2540000000143526120,
2540000000102176392,
2540000000144609962,
2540000000128826163,
2540000000136185694,
2540000000133208691,
2540000000144555891,
2540000000138091838,
2540000000130179358,
2540000000126098342,
2540000000145162237,
2540000000131688927,
2540000000136185715,
2540000000143526101
)

The counts of A and B before the minus set call are as follows:
2014-05-14 22:37:00.900 App[35877:60b] fetchedThreadIdsCount = 40
2014-05-14 22:37:00.900 App[35877:60b] savedThreadsCount = 20

A: I tried this and it worked so I'm guessing there is other code that is missing or the NSNumbers really aren't the same, just the printed representation is the same.
NSMutableSet *fetchedThreadIds = [NSMutableSet setWithObjects:@1, @2, @3, @4, nil];
NSSet *savedThreads = [NSSet setWithObjects:@2, @3, nil];
NSLog(@"fetchedThreadIds: %@", fetchedThreadIds);
NSLog(@"savedThreads: %@", savedThreads);

[fetchedThreadIds minusSet:savedThreads];
NSLog(@"fetchedThreadIds: %@", fetchedThreadIds);
NSArray *threadIdsForMessageFetch = [fetchedThreadIds allObjects];
NSLog(@"threadIdsForMessageFetch: %@", threadIdsForMessageFetch);

NSLog output:

fetchedThreadIds: {(
      3,
      2,
      1,
      4 )}
  savedThreads: {(
      3,
      2 )}
  fetchedThreadIds: {(
      1,
      4 )}
  threadIdsForMessageFetch: (
      1,
      4 )

Posted as an answer mainly for formatting.


text:
Q: repository of available rails engines Is there a repository where you can find all the available rails engines?
something like the appstore for rails engines?
I have seen some references to http://rails-engines.org/ but that has only 2 or 3 engines.
Thanks.

A: It's not exclusively for rails engines, but Ruby Toolbox is a good repository of various tools.


text:
Q: How to update the database in Symfony 4? When I give the following command:
php bin/console doctrine:schema:update --force
the database gets updated, but afterwards this command:
php bin/console doctrine:schema:validate
keeps saying that the database is not in sync (see below screenshot).
What am I missing/doing wrong?

A: Depending on the database type and OS, the test may give some "false negatives", which means that your db is already ok but Doctrine doesn't quite understand. It happened to me in several projects, regardless of Symfony version (which means, Symfony 2,3 and 4).
Besides, in Symfony 4 you can use migrations as explained in the docs, that is:
bin/console make:migration

this command will create a migration file inside src/Migrations, but won't touch the db.
To understand what's going on (from Doctrine's oint of view) you may have a look at the migration file: it's a PHP class with two methods (up() and down()).
The up() method will contain the query/queries needed to align the database with your mapping files.
To apply all the pending migrations, run:
bin/console doctrine:migrations:migrate


text:
Q: How to do a groupBy by a given column but still keep all the rows of the original DataFrame? I want to do a groupBy and aggregate by a given column in PySpark but I still want to keep all the rows from the original DataFrame.
For example lets say we have the following DataFrame and we want to do a max on the "value" column then we would get the result below.
Original DataFrame
+--+-----+
|id|value|
+--+-----+
| 1|    1|
| 1|    2|
| 2|    3|
| 2|    4|
+--+-----+

Result
+--+-----+---+
|id|value|max|
+--+-----+---+
| 1|    1|  2|
| 1|    2|  2|
| 2|    3|  4|
| 2|    4|  4|
+--+-----+---+

A: You can do it simply by joining aggregated dataframe with original dataframe
aggregated_df = (
    df
    .groupby('id')
    .agg(F.max('value').alias('max'))
)

max_value_df = (
    df
    .join(aggregated_df, 'id')
)

A: Use window function
 df.withColumn('max', max('value').over(Window.partitionBy('id'))).show()

+---+-----+---+
| id|value|max|
+---+-----+---+
|  1|    1|  2|
|  1|    2|  2|
|  2|    3|  4|
|  2|    4|  4|
+---+-----+---+


text:
Q: How to get data from Firestore in flutter? I want to create a Welcome Message where the user's name is placed in the top left corner when logged in. I succeeded in getting user.email and user.uid using final FirebaseAuth auth = FirebaseAuth.instance; and User? user = FirebaseAuth.instance.currentUser;, but I don't know how to get user's other data(especially name).
My code is:
  final FirebaseAuth auth = FirebaseAuth.instance;
  User? user = FirebaseAuth.instance.currentUser;

  ...

    Widget loginMessage() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
          children: [
            Text(
            // I want to username at here.
              '${user.email}님, \n환영합니다 :)',
              style: TextStyle(
                fontSize: titleLarge,
                fontFamily: 'semi-bold',
              ),
            ),
            TextButton(
              onPressed: () {
                _signOut().then(
                  (value) => Get.to(
                    () => HomeScreen(),
                  ),
                );
              },
              child: Text('로그아웃'),
            ),
          ],
        ),
        marginHeight22,
        Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            // 로그인버튼
            GestureDetector(
              onTap: () {
                Get.to(() => LoginScreen());
              },
              child: Container(
                decoration: BoxDecoration(
                  color: primaryColor20,
                  border: Border.all(
                    color: primaryColor20,
                  ),
                  borderRadius: BorderRadius.all(
                    Radius.circular(12.0),
                  ),
                ),
                height: 48,
                width: MediaQuery.of(context).size.width * 0.9,
                child: Center(
                  child: Text(
                    '내 정보 수정',
                    style: TextStyle(
                      color: primaryColor50,
                      fontFamily: 'semi-bold',
                      fontSize: titleSmall,
                    ),
                  ),
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

A: Hey for storing other user details you have to create a collection in the firebase database just sharing how I do
so I have a collection called users where the document ID is the user uid generated by firebase and it has various fields like name, avatar, username etc.
So for the above scenario, the query is like
FirebaseFirestore.instance.collection('users').doc(userUid).snapshots();

To display the data from the snapshot
DocumentSnapshot document = snapshot.data!.docs.map().data()! as Map<String, dynamic>;
return ListTile(title: Text(data['username']));


text:
Q: Spring Injection isn't working in Jersey Filter - @InjectParam Equivalent in jersey2 I'm trying to inject an object in Jersey-Filter using spring injection.
If I try the @Inject method, then I'm ending up with an exception
SEVERE: StandardWrapper.Throwable
MultiException stack 1 of 2
java.lang.IllegalStateException: Could not find an active context for org.jvnet.hk2.spring.bridge.api.SpringScope
        at org.jvnet.hk2.internal.ServiceLocatorImpl._resolveContext(ServiceLocatorImpl.java:2058)
        at org.jvnet.hk2.internal.ServiceLocatorImpl.access$000(ServiceLocatorImpl.java:120)
        at org.jvnet.hk2.internal.ServiceLocatorImpl$2.compute(ServiceLocatorImpl.java:186)
        at org.jvnet.hk2.internal.ServiceLocatorImpl$2.compute(ServiceLocatorImpl.java:182)

If I try using @InjectParam that its defined in Jersey 1.x however I'm using Jersey 2.17 in which this annotation is not found.
Any idea how to perform this spring injection in jersey-filter?
What's does the exception mean?
Could not find an active context for org.jvnet.hk2.spring.bridge.api.SpringScope

A: Update Edit:
Additionally you can provide a constructor injection. Jersey's constructor injection worked for me in Filter's rather than Field Injections
Old :
I implemented this by Injecting the javax.servlet.ServletContext inside the filter and using that to get the beanIds using WebApplicationContextUtils
public class LoginFilter implements ContainerRequestFilter {

    @Context private HttpServletRequest servletRequest;

    @Context private HttpServletResponse servletResponse;

    @Context private ServletContext servletContext;

public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        try {

            WebApplicationContext springContext =
                    WebApplicationContextUtils.getWebApplicationContext(servletContext);

            CookieAuthenticator     cookieAuthenticator = springContext.getBean(CookieAuthenticator.class);

            LoginInterceptorHelper  loginInterceptorHelper = springContext.getBean(LoginInterceptorHelper.class);

            HttpSession session = request.getSession(true);

            UserSummary user = (UserSummary) session.getAttribute(WebConstants.USER_DETAIL);

And By including a spring listener so spring initialization happens first.
<listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

This works.
But instead of injection I'm explicitly loading the dependencies.
Is there any better way to do this?


text:
Q: Sci Fi movie with a pen writing the pages of someone's life I've done countless Google searches trying to find this movie which I saw on Netflix a couple years ago. I'm not sure of the release date of the film.
One scene I remember is where the guy is sitting in his room and the TV turns on by itself and it's a woman looking at him. She is in a parallel reality / dimension and she is also in her room when her TV turns on and he is there. At first they are scared but then they start talking to each other. She gives him her phone number and he calls her but a secretary of an office building answers the phone instead. He then looks up the number and drives all the way to the office building to find a lone pen writing the pages of someone's life (I'm not sure if it was his life or the woman's life). I think he grabs the pen and starts writing something else on it and eventually the man and woman are together in the same universe (?)
Anyway I thought it was a good movie and I was trying to recommend it to a friend but I can't find it.

A: Are you thinking of The Frame (2014)?
From the plot summary on Wikipedia:
the guy is sitting in his room and the TV turns on by itself and it's a woman looking at him. She is in a parallel reality / dimension and she is also in her room when her TV turns on and he is there.

Home after collecting his pay for the recent heist, Alex stashes it in a hidden wall safe and turns on the TV to eat dinner. We see he's intently watching a television show which happens to be the scene with Sam the paramedic we just saw happen in real time. Sam is the star of the show called Urban Hope.
Sam, home after her therapist visit, sits eating dinner in front of the TV and watches Alex's recent heist and escape with the intensity of a true fan. Alex's show is called Thieves and Saints.

At first they are scared but then they start talking to each other.

Late one evening, as the two have their televisions on they realize that they are broadcast live from their living rooms on the others TV set. They say hello, panic, and turn off their TVs.

He then looks up the number and drives all the way to the office building to find a lone pen writing the pages of someone's life (I'm not sure if it was his life or the woman's life). I think he grabs the pen and starts writing something else
You may have swapped the roles in your memory; it appears that Sam drives to the production company.

She springs into action remembering she had found the Thieves and Saints production company address and drives there only to be stopped by her Therapist who has been looking for her, fearing she is not mentally well. She runs past him into the building and to the floor of the Thieves and Saints writer's office. A 60's-dressed secretary sits in a small lobby staring at a phone and asks how Sam is doing. Sam goes through the only door in the room and finds herself in a vacuous room – on one side extending to infinite black and the other with spools feeding into a typing machine. She exits the other side which takes her back into the secretary's office and has the same short conversation as if on a repeating loop.
Finally she summons the courage to walk toward the typing machine in the vacuous room and sees a projection image above the machine showing Alex on the floor of his apartment. The typing machine deposits the final page for "Thieves and Saints: Episode 50". Sam picks up the script and flips through, seeing everything that had happened up to this point in his show. Sam is able to write onto the script and change Alex's fate, reviving him from death.

eventually the man and woman are together in the same universe

Alex finally reaches for his violin. As he plays, the melody of her humming and his strings combine to merge their two worlds.


text:
Q: R- Subtract values of all rows in a group from previous row in different group and filter out rows In R say I had the data frame:
data

frame object  x      y
1     6       150    100
2     6       149    99
3     6       148    98
3     6       140    90
4     6       148.5  97
4     6       142    93
5     6       147    96
5     6       138    92
5     6       135    90
6     6       146.5  99
1     7       125    200
2     7       126    197
3     7       127    202
3     7       119    185
4     7       117    183
4     7       123    199
5     7       115    190
5     7       124    202
5     7       118    192
6     7       124.5  199

I want to output the object which is the closest in the previous frame based on the (x,y) coordinates and filter out the other objects. I want to find the difference in the x and y between all the objects in a given frame and the single object in the previous frame and keep the closest object while removing the rest. The object that is kept would then serve as reference for the next frame. The frames with only one object would be left as is. The output should be one object per frame:
data

frame object  x      y
1     6       150    100
2     6       149    99
3     6       148    98
4     6       148.5  97
5     6       147    96
6     6       146.5  99
1     7       125    200
2     7       126    197
3     7       127    202
4     7       123    199
5     7       124    202
6     7       124.5  199

A: We can create a for loop that applies the criteria to a single object, and then use group_by %>% summarize to apply it to every object:
library(dplyr)

keep_closest_frame = function(data) {
  frames = split(data, dd$frame)
  for(i in seq_along(frames)) {
    if(nrow(frames[[i]]) != 1 & i == 1) {
      stop("First frame must have exactly 1 row")
    }
    if(nrow(frames[[i]]) == 1) next
    dists = with(frames[[i]], abs(x - frames[[i - 1]][["x"]]) + abs(y - frames[[i - 1]][["y"]]))
    frames[[i]] = frames[[i]][which.min(dists), ]
  }
  bind_rows(frames)
}

data %>%
  group_by(object) %>%
  summarize(keep_closest_frame(across()))
# # A tibble: 12 × 4
# # Groups:   object [2]
#    object frame     x     y
#     <int> <int> <dbl> <int>
#  1      6     1  150    100
#  2      6     2  149     99
#  3      6     3  148     98
#  4      6     4  148.    97
#  5      6     5  147     96
#  6      6     6  146.    99
#  7      7     1  125    200
#  8      7     2  126    197
#  9      7     3  127    202
# 10      7     4  123    199
# 11      7     5  124    202
# 12      7     6  124.   199

A: This is a cumulative operation, so it'll take an iterative approach. Here's a simple function to do one operation, assuming it's for only one object.
fun <- function(Z, fr) {
  prevZ <- head(subset(Z, frame == (fr-1)), 1)
  thisZ <- subset(Z, frame == fr)
  if (nrow(prevZ) < 1 || nrow(thisZ) < 2) return(Z)
  ind <- which.min( abs(thisZ$x - prevZ$x) + abs(thisZ$y - prevZ$y) )
  rbind(subset(Z, frame != fr), thisZ[ind,])
}

fun(subset(dat, object == 6), 3)
#    frame object     x   y
# 1      1      6 150.0 100
# 2      2      6 149.0  99
# 5      4      6 148.5  97
# 6      4      6 142.0  93
# 7      5      6 147.0  96
# 8      5      6 138.0  92
# 9      5      6 135.0  90
# 10     6      6 146.5  99
# 3      3      6 148.0  98

(The order is not maintained, it can easily be sorted back into place as needed.)
Now we can Reduce this for each object within the data.
out <- do.call(rbind,
  lapply(split(dat, dat$object),
         function(X) Reduce(fun, seq(min(X$frame)+1, max(X$frame)), init=X)))
out <- out[order(out$object, out$frame),]
out
#      frame object     x   y
# 6.1      1      6 150.0 100
# 6.2      2      6 149.0  99
# 6.3      3      6 148.0  98
# 6.5      4      6 148.5  97
# 6.7      5      6 147.0  96
# 6.10     6      6 146.5  99
# 7.11     1      7 125.0 200
# 7.12     2      7 126.0 197
# 7.13     3      7 127.0 202
# 7.16     4      7 123.0 199
# 7.18     5      7 124.0 202
# 7.20     6      7 124.5 199


text:
Q: Cant add sub query aliases in mysql Hey guys am new to mysql actually ...I am new understanding the concept of aliases..
When i have tried
(select 'kund' as mlech,'sdd' as sa);

it works just fine..It runs succesfully
But when i try to add subliases like
(select 'kund' as mlech,'sdd' as sa) as bab;

it throws me error like
#1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax
Can you tell me why i cant add an alias for a sub query..
Thanks for the help..

A: Your syntax is fine if you are doing an actual subquery - you just need to use it as an actual subquery, ie:
SELECT bab.* FROM (select 'kund' as mlech,'sdd' as sa) as bab;
What you are doing is creating a derived table, and giving it the name 'bab'. It really only makes sense to do this in the context of referring to the results of that subquery, in another query.


text:
Q: Setting Hadoop number of mapper with input split not working I am trying to run a hadoop job multiple times with different number of mapper and reducer. I have set the configuration :

*

*mapreduce.input.fileinputformat.split.maxsize

*mapreduce.input.fileinputformat.split.minsize

*mapreduce.job.maps

My filesize is 1160421275, when i tried to configure it with 4 mappers and 3 reducers in this code:
Configuration conf = new Configuration();
FileSystem hdfs = FileSystem.get(conf);
long size = hdfs.getContentSummary(new Path("input/filea").getLength();
size+=hdfs.getContentSummary(new Path("input/fileb").getLength();
conf.set("mapreduce.input.fileinputformat.split.maxsize", String.valueOf((size/4)));
conf.set("mapreduce.input.fileinputformat.split.minsize", String.valueOf((size/4)));
conf.set("mapreduce.job.maps",4);
....
job.setNumReduceTask(3);

The size/4 gives 290105318. The execution of the job gives the output below:
2016-11-19 12:30:36,426 INFO  [main] input.FileInputFormat (FileInputFormat.java:listStatus(287)) - Total input paths to process : 1
2016-11-19 12:30:36,535 INFO  [main] input.FileInputFormat (FileInputFormat.java:listStatus(287)) - Total input paths to process : 4
2016-11-19 12:30:36,572 INFO  [main] mapreduce.JobSubmitter (JobSubmitter.java:submitJobInternal(396)) - number of splits:7

The number of splits is 7, not 4, and the Output of the success job is:
File System Counters
    FILE: Number of bytes read=18855390277
    FILE: Number of bytes written=14653469965
    FILE: Number of read operations=0
    FILE: Number of large read operations=0
    FILE: Number of write operations=0
Map-Reduce Framework
    Map input records=39184416
    Map output records=36751473
    Map output bytes=787022241
    Map output materialized bytes=860525313
    Input split bytes=1801
    Combine input records=0
    Combine output records=0
    Reduce input groups=25064998
    Reduce shuffle bytes=860525313
    Reduce input records=36751473
    Reduce output records=1953960
    Spilled Records=110254419
    Shuffled Maps =21
    Failed Shuffles=0
    Merged Map outputs=21
    GC time elapsed (ms)=1124
    CPU time spent (ms)=0
    Physical memory (bytes) snapshot=0
    Virtual memory (bytes) snapshot=0
    Total committed heap usage (bytes)=6126829568
Shuffle Errors
    BAD_ID=0
    CONNECTION=0
    IO_ERROR=0
    WRONG_LENGTH=0
    WRONG_MAP=0
    WRONG_REDUCE=0
File Input Format Counters
    Bytes Read=0
File Output Format Counters
    Bytes Written=77643084

The map shows that it processed 21 shuffled maps. I want it to processed just 4 mappers. For the reducer it gives the correct number of files with the total number of 3. Are my mapper split size settings wrong?

A: I believe you are using TextInputFormat.

*

*If you have multiple files, then at least one mapper will be spawned for each file.  If file size (not cumulative but individual) is more than block size (which you have tweaked by setting min and max) again more mappers will be spawned.

*Try using combineTextInputFormat, that will help you in acheiving what you want, but still may be not exactly 4.

*Look at logic of InputFormats that you are using to determine, how many mappers will be spawned.


text:
Q: Why does one "stand there like a lemon"? I was standing around like a lemon the other day (meaning, standing doing nothing when I ought to have been a little more active) when it occurred to me to wonder, why does one stand there like a lemon? Does anyone know the origin of this term?
I know that when you buy a poor-quality car it is said to be a lemon. Why does this particular fruit have such negative connotations?

A: Maybe its origin will explain it pretty much.
It came from "Standing around like a lost lemon". Phrase Finder here:

Standing around like a lost lemon" is cited in Eric Partridge, "A Dictionary of Catch Phrases American and British" as a "more ladylike version" of "standing about like a spare prick at a wedding," defined as "unwanted, useless, idle, esp. with a hint of painfully embarrassed superfluity."

The reason "lemon" is used here, is because "lemon" in slang means :

slang  a person or thing considered to be useless or defective

The reason "lemon" has a negative connotation could possibly be because:

"worthless thing," 1909, Amer.Eng. slang; from lemon (1), perhaps via criminal slang sense of "a person who is a loser, a simpleton," which is perhaps from the notion of someone a sharper can "suck the juice out of." A pool hall hustle was called a lemon game  (1908); while to hand someone a lemon  was British slang (1906) for "to pass off a sub-standard article as a good one." Or it simply may be a metaphor for something which "leaves a bad taste in one's mouth."

A: It's not exactly an origin or first use, but here's the earliest usage I could find.
On being questioned about what was meant, the speaker there expanded by saying "kind of soppy". I agree with the hearer, who replied that this particular metaphorical usage didn't seem very witty or telling.
Having said that, the expression did start to get used more often in the 1980s. Still only a couple of hundred usages in this NGram for there like a lemon, but almost all of them are preceded by some variant of the verbs stand or sit.
In most cases the emphasis is on being kept waiting, with nothing to occupy one's time, rather than OP's implied voluntarily choosing to be idle. The implication being that the subject is unable to do anything about the enforced waiting.
I do not believe this particular usage owes much if anything to the (originally British) slang meaning of a lemon as a poor-quality troublesome purchase (normally a car). Here's the second earliest usage I could find, which again defines the expression in terms of soppiness/ineffectuality. The most common thing done with lemons is to squeeze them; the the metaphorical usage alludes to the fact that we don't expect lemons to resist such treatment.


text:
Q: Why there is no `Cofunctor` typeclass in Haskell? Monads get fmap from Functor typeclass. Why comonads don't need a cofmap method defined in a Cofunctor class?

A: For reference,
class Functor w => Comonad w where
  extract :: w a -> a
  duplicate :: w a -> w (w a)
  extend :: (w a -> b) -> w a -> w b

instance Applicative m => Monad m where
  return :: a -> m a
  (>>=) :: m a -> (a -> m b) -> m b

join :: Monad m => m (m a) -> m a

Note that given extract and extend you can produce fmap and duplicate, and that given return and >>= you can produce fmap, pure, <*>, and join. So we can focus on just pure+>>= and extract+extend.
I imagine you might be looking for something like
class InverseFunctor f where
  unmap :: (f a -> f b) -> a -> b

Since the Monad class makes it easy to "put things in" while only allowing a sort of hypothetical approach to "taking things out", and Comonad does something opposed to that, your request initially sounds sensible. However, there is a significant asymmetry between >>= and extend that will get in the way of any attempt to define unmap. Note in particular that the first argument of >>= has type m a. The second argument of extend has type w a—not a.

A: Actually, you're wrong: there is one!
https://hackage.haskell.org/package/acme-cofunctor

A: Functor is defined as:
class Functor f where
    fmap :: (a -> b) -> (f a -> f b)

Cofunctor could be defined as follows:
class Cofunctor f where
    cofmap :: (b -> a) -> (f b -> f a)

So, both are technically the same, and that's why Cofunctor does not exist. "The dual concept of 'functor in general' is still 'functor in general'".
Since Functor and Cofunctor are the same, both monads and comonads are defined by using Functor. But don't let that make you think that monads and comonads are the same thing, they're not.
A monad is defined (simplifying) as:
class Functor m => Monad where
    return :: a -> m a
    (>>=) :: m a -> (a -> m b) -> m b

whether a comonad (again, simplified) is:
class Functor w => Comonad where
    extract :: w a -> a
    extend :: (w a -> b) -> w a -> w b

Note the "symmetry".

Another thing is a contravariant functor, defined as:
import Data.Functor.Contravariant
class Contravariant f where
    contramap :: (b -> a) -> (f a -> f b)


text:
Q: How many (Maximum) DB2 multi row fetch cursor can be maintained in PLI/COBOL program? How many (Maximum) DB2 multi row fetch cursor can be maintained in PLI/COBOL program as part of good performance?
I have a requirement to maintain 4 cursors in PLI program but I am concerned about number of multi fetch cursors in single program.
Is there any other way to check multi row fetch is more effective than normal cursor? I tried with 1000 records but I couldn't see the running time difference.

A: IBM published some information (PDF) about multi-row fetch performance when this feature first became available in DB2 8 in 2005.  Their data mentions nothing about the number of cursors in a given program, only the number of rows fetched.
From this I infer the number of multi-row fetch cursors itself is not of concern from a performance standpoint -- within reason.  If someone pushes the limits of reason with 10,000 such cursors I will not be responsible for their anguish.
The IBM Redbook linked to earlier indicates there is a 40% CPU time improvement retrieving 10 rows per fetch, and a 50% CPU time improvement retrieving 100+ rows per fetch.  Caveats:

The performance improvement using multi-row fetch in general depends
  on:

*

*Number of rows fetched in one fetch

*Number of columns fetched
  (more improvement with fewer columns), data type and size of the
  columns

*Complexity of the fetch. The fixed overhead saved for not
  having to go between the database engine and the application program
  has a lower percentage impact for complex SQL that has longer path
  lengths.

  If the multi-row fetch reads more rows per statement, it results in
  CPU time improvement, but after 10 to 100 rows per multi-row fetch,
  the benefit is decreased. The benefit decreases because, if the cost
  of one API overhead per row is 100% in a single row statement, it gets
  divided by the number of rows processed in one SQL statement. So it
  becomes 10% with 10 rows, 1% with 100 rows, 0.1% for 1000 rows, and
  then the benefit becomes negligible.

The Redbook also has some discussion of how they did their testing to arrive at their performance figures.  In short, they varied the number of rows retrieved and reran their program several times, pretty much what you'd expect.


text:
Q: How can I attach a policy to a resource (in this case a PubSub topic)? resource "google_pubsub_topic" "topic" {
  name   = "argo-events"
}

resource "google_service_account" "argo_events_pubsub_publish" {
  account_id   = "pubsub-publish"
}

resource "google_project_iam_member" "argo_events_pubsub_publish" {
  role   = "roles/pubsub.editor"
  member = "serviceAccount:${google_service_account.argo_events_pubsub_publish.email}"
}

This will create a service account with editor permissions on all PubSub infrastructure of the project.
How can I attach the policy (resulting from Service Account + roles/pubsub.editor) to the initially created topic?
(Such that the Service Account has permissions from roles/pubsub.editor but only on the initially created topic named "argo-events".)

The question was written under the assumption that terraform implements the policy attachment analogous to GCPs generic concept.

A: There are a couple of ways to attach a policy to a topic or a subscription. Interestingly the approach is not generic but specific to what resource you want to bind to (in this case a pubsub topic) and there are at least three ways how to do it:

*

*https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/pubsub_topic_iam

*https://registry.terraform.io/providers/hashicorp/google/latest/docs/resources/pubsub_subscription_iam
In this case a solution could look like this:
data "google_iam_policy" "topic" {
  binding {
    role = "roles/pubsub.publisher"
    members = [
      "serviceAccount:${google_service_account.argo_events_pubsub_publish.email}",
    ]
  }
}

resource "google_pubsub_topic_iam_policy" "policy" {
  topic = google_pubsub_topic.topic.name
  policy_data = data.google_iam_policy.topic.policy_data
}


text:
Q: after ajax call the form submit using target blank not working I am having user registration form which performs the user registration such as storing user data etc.. after that form is submited via Javascript using _target=blank. but it popup is blocked. After form submit, it will be redirected to open a PDF.
Could you please advice that how to avoid popup blocker?

A: The popup blocker will prevent any new windows that are not a direct result of a user click. You must use some javascript to open a window and then set the form's action to the new window.
// attach a click event handler to your submit button
<input type="submit" value="Register" onclick="submitToBlankWindow();" />

// create a javascript function to launch the new window and set the form's action
function submitToBlankWindow() {
    window.open('about:blank','blankwindow');
    document.findElementById('myFormId').action = "blankwindow";
}

Hope it helps!


text:
Q: GZipStream or DeflateStream class? The MSDN documentation tells me the following:

The GZipStream class uses the gzip
  data format, which includes a cyclic
  redundancy check value for detecting
  data corruption. The gzip data format
  uses the same compression algorithm as
  the DeflateStream class.

It seems GZipStream adds some extra data to the output (relative to DeflateStream). I'm wondering, in what type of a scenario would it be essential to use GZipStream and not DeflateStream?

A: Deflate is just the compression algorithm.  GZip is actually a format.
If you use the GZipStream to compress a file (and save it with the extension .gz), the result can actually be opened by archivers such as WinZip or the gzip tool.  If you compress with a DeflateStream, those tools won't recognize the file.
If the compressed file is designed to be opened by these tools, then it is essential to use GZipStream instead of DeflateStream.
I would also consider it essential if you're transferring a large amount of data over an unreliable medium (i.e. an internet connection) and not using an error-correcting protocol such as TCP/IP.  For example, you might be transmitting over a serial port, raw socket, or UDP.  In this case, you would definitely want the CRC information that is embedded in the GZip format in order to ensure that the data is correct.

A: Well, i was completely wrong in my first answer. I have looked up in Mono source code and found that GZipStream class actually redirects its read/write(and almost any other) calls to an appropriate calls of methods of an internal DeflateStream object:
public override int Read (byte[] dest, int dest_offset, int count)
{
    return deflateStream.Read(dest, dest_offset, count);
}

public override void Write (byte[] src, int src_offset, int count)
{
    deflateStream.Write (src, src_offset, count);
}

The only difference, is that it always creates a DeflateStream object with a gzip flag set to true.
This is certainly not an answer to you question, but maybe it'll help a bit.

A: While GZipStream seems to be using DeflateStream to do decompression, the two algorithms don't seem to be interchangeable. Following test code will give you an exception:
        MemoryStream wtt=new MemoryStream();
        using (var gs=new GZipStream(wtt,CompressionMode.Compress,true))
        {
            using (var sw=new StreamWriter(gs,Encoding.ASCII,1024,true))
            {
                sw.WriteLine("Hello");
            }
        }
        wtt.Position = 0;
        using (var ds = new DeflateStream(wtt, CompressionMode.Decompress, true))
        {
            using (var sr=new StreamReader(ds,Encoding.ASCII,true,1024,true))
            {
                var txt = sr.ReadLine();
            }
        }

A: GZipStream is the same as DeflateStream but it adds some CRC to ensure the data has no error.

A: Dito as per Aaronaught

Note one other important difference as per
http://www.webpronews.com/gzip-vs-deflate-compression-and-performance-2006-12:

I measured the DeflateStream to 41% faster than GZip.

I didn't measure the speed, but I measured the file size to be appx. the same.