Q:

Difference between private property and method holding static value?

Private variable
class Input {
    private
        $form;

    public function __construct (Form $form) {
        $this->form = $form;
    }

    public function getForm () {
        return $this->form;
    }
}

Method with static variable
class Input {
    public function __construct (Form $form) {
        $this->getForm($form);
    }

    public function getForm (Form $set_form = null) {
        static $form;

        if (!$form && $set_form !== null) {
            $form = $set_form;
        } else if ($form && $set_form) {
            throw new \ErrorException('Form has been already set.');
        }

        return $form;
    }
}

I prefer the latter because $form property is not included when you are dumping the Input object. Because of their circular relation (not shown in the example), it makes the output unreadable.
What are the disadvantages of using the latter approach VS the latter?

A:

A static variable in a method is constant across all instances of the class, a private property is simply not accessible from outside the class, but unique to each instance of it. They're not the same at all. If you need a property which is unique to each classes instance, there's no replacement for a property. It's also much more readable and idiomatic than your static workaround for the same thing.
Learn to read var_dumps better if that's your only reason to use static variables.


Q:

Is there a way(formula) to calculate absolute size of flex elements described with flex-grow, flex-shrink and flex basis?

I made a small demo
http://html5.by/blogdemo/flexbox/flex-grow-shrink-basis-stackoverflow.html
there are 2 flex items in flex container

flex: 1 2 1000px;
flex: 1 1 100px;

absolute width of flex container - 500px;
finally, you can see, that width of flex elements are:

421px
79px

My question: Is there a way to mathematically describe calculated sizes (with formula)?

A:

The closest thing to a formula is just the algorithm in the spec:
http://www.w3.org/TR/css3-flexbox/#resolve-flexible-lengths
I don't think it can easily be described in a formula. You can cover easy cases with a formula, but it gets a bit more complex (and requires multiple loops of the algorithm) when elements have min-width or max-width constraints.
SIDE NOTE: the flexbox spec will likely soon make a small change to flex-grow and flex-shrink behavior, so that they're treated more like a percentage when their sum is less than 1. (So e.g. flex-grow: 0.1 would never give you more than 10% of the free space, even if you're the only child.)  That proposal is described here: http://lists.w3.org/Archives/Public/www-style/2013Oct/0246.html


Q:

How to evaluate all derivatives of a polynomial at a point with FFT?

I found this problem:

Evaluating all derivatives of a polynomial at a point
Given a polynomial A(x) of degree-bound n, its tth derivative is
  defined by

From the coefficient representation $(a_0, a_1, . . . , a_{n-1})$ of A(x) and
  a given point $x_0$, we wish to determine A(t) ($x_0$) for t = 0, 1, . . . ,
  n - 1.

I know the vector of the coefficients has to be used and I also know that the derivative of a term $ax^n$ is $a*n*x^{n-1}$, but where do I go from there?
I can only think of the naïve scheme to evaluate this: Find the first derivative ($O(n)$), evaluate it using Horner's method ($O(n)$). Repeat this for all deterivaties, giving $(O(n^2)$).

A:

Hint: Taking the derivative has a certain, simple diagonal effect on the Fourier transform, that hopefully was covered in class. Hence if you compute the Fourier transform of the original function, you "know" the Fourier transform of all its derivatives as well. Given the Fourier transform, there is a formula for the value of the actual function. In your case, in order to compute the value of all derivatives of the function at a point, you multiply some matrix by the vector of Fourier coefficients. This matrix looks suspiciously similar to the DFT matrix, so hopefully you can compute the matrix-vector product in time $O(n\log n)$.


Q:

NoClassDefFoundError: org/springframework/web/client/RestClientException in ECLIPSE RCP and SPRINGFRAMEWORK

Hi RCP developers,
I'm facing a problem with my product.
When I launch it, i got this :
org.eclipse.e4.core.di.InjectionException: java.lang.NoClassDefFoundError: org/springframework/web/client/RestClientException
Caused by: java.lang.NoClassDefFoundError: org/springframework/web/client/RestClientException
I'm using a REST templates from SPRINGFRAMEWORK to catch the results from a REST API, and i try to display that in a Treeview using JFACE.
All springframewok jar's are correctly added to the project.
Could anyone help please?
Thanks in advance !
Ismail

A:

A NoClassDefFoundError specifies that you had the class available at compile time but missing during runtime. In your case org.springframework.web-3.0.5.RELEASE jar seems to be missing in the classpath. If you still face issues, debug following this :
http://javareferencegv.blogspot.com/2013/10/debugging-javalangnoclassdeffounderror.html


Q:

PDE Separation Of Variables: Laplace Equation Problem

I am having trouble with this problem. Here is the problem:
I might need some tips on how to go through this problem. I have a sense on solving the cases for the separation constant, but I am having trouble on how to do it in this scenario. Here's the question:
Solve Laplace’s equation
$[u_{xx}+u_{yy} = 0.]$ (This equation should be in polar form)
inside a circular annulus $R_1 < r < R_2$ with boundary conditions: $\varphi(R_1,\theta) = 0$ and
$\frac{\partial \varphi}{\partial r} (R_2,θ) = f(θ)$
I understand the process of Separation Of Variables and the Laplace Equation. The point I am stuck on at the moment is evaluating the Boundary Condition and the Initial Condition.
Also, this is my first time on this website and I am trying to get familiar with it. I might need some tips on how to input in these figures correctly.

A:

The usual separation of variables in polar coordinates produces
$$\phi \left( r,\theta \right) =\sum _{n=0}^{\infty } \left( A_{{n}}\sin
 \left( n\theta \right) +B_{{n}}\cos \left( n\theta \right)  \right)
 \left( {r}^{n}C_{{n}}+{r}^{-n}E_{{n}} \right) +F\ln  \left( r
 \right)$$
which is rewritten as
$$\phi \left( r,\theta \right) =\sum _{n=1}^{\infty } \left( A_{{n}}\sin
 \left( n\theta \right) +B_{{n}}\cos \left( n\theta \right)  \right)
 \left( {r}^{n}C_{{n}}+{r}^{-n}E_{{n}} \right) +G+ F\ln  \left( r
 \right)$$
Applying the boundary condition at $r=R_1$  we obtain
$$\sum _{n=1}^{\infty } \left( A_{{n}}\sin \left( n\theta \right) +B_{{n
}}\cos \left( n\theta \right)  \right)  \left( {R_{{1}}}^{n}C_{{n}}+{R
_{{1}}}^{-n}E_{{n}} \right) +F\ln  \left( R_{{1}} \right) +G =0
$$
From this last equation we derive that $G=-Fln(R_1)$  and
$${R_{{1}}}^{n}C_{{n}}+{R_{{1}}}^{-n}E_{{n}}= 0$$
Then we have
$$ E_{{n}}=-{R_{{1}}}^{2\,n}C_{{n}} $$
The solution takes the form
$$\phi \left( r,\theta \right) =\sum _{n=1}^{\infty } \left( A_{{n}}\sin
 \left( n\theta \right) +B_{{n}}\cos \left( n\theta \right)  \right)
 \left( {r}^{n}-{r}^{-n}{R_{{1}}}^{2\,n} \right)-Fln(R_1)+Fln(r)
$$
Applying the boundary condition at $r=R_2$ we obtain
$$\sum _{n=1}^{\infty } \left( A_{{n}}\sin \left( n\theta \right) +B_{{n
}}\cos \left( n\theta \right)  \right) n \left( {R_{{2}}}^{n-1}+{R_{{2
}}}^{-n-1}{R_{{1}}}^{2\,n} \right)+F/R_2 =f \left( \theta \right)
$$
Finally the constants $F$, $A_n$ and $B_n$ are determined using the standard expressions of Fourier series.


Q:

Mozilla WebExtension API storage - Debugging with and without breakpoints leads to different output

Hello guys,

i am trying to implement an add-on for the Mozilla-Firefox Browser.
The following script shows one backgorund script I already successfully integrated. It uses the Mozilla WebExtension API storage. It gets executed but the log on the browser console suprises me.
I get alternating logged nothing and:
bla
bla
bla

If and only if I set breakpoints on significant lines (especially the last 5 lines) of my code in Debugging-Mode I get always the expected result:
bla

How is it that the output depends on setting breakpoints.
I have no idea what is happening and can not find any similar problems on the internet. Can somebody explain to me what is happening and what I can do to prevent the wrong output?
storeManager.js:
var localStore = chrome.storage.local;
var StoreManager = function(){};

StoreManager.prototype.addItem = function(type, item){
    var thisRef = this;

    localStore.get(type,
        function(obj){
            if(chrome.runtime.lasterror){
                console.log(chrome.runtime.lastError);
            }else{
                var oldArr = obj[type];

                if(oldArr === undefined)
                    oldArr = [];

                if(oldArr.indexOf(item) !== -1)
                    return;

                oldArr.push(item);
                thisRef.setItem(type, oldArr);
            }
        }
    );
}

StoreManager.prototype.removeItem = function(type, item){
    var thisRef = this;

    localStore.get(type,
        function(obj){
            if(chrome.runtime.lasterror){
                console.log(chrome.runtime.lastError);
            }else{
                var oldArr = obj[type];

                if(oldArr === undefined)
                    return;

                var index = oldArr.indexOf(item);
                if(index === -1)
                    return;

                oldArr.splice(index, 1);
                thisRef.setItem(type, oldArr);
            }
        }
    );
}

StoreManager.prototype.setItem = function(type, item){
    localStore.set({ [type] : item },
        function(){
            if(chrome.runtime.lasterror){
                console.log(chrome.runtime.lastError);
            }
        }
    );
}

StoreManager.prototype.visitItems = function(type, visit){
    localStore.get(type,
        function(obj){
            if(chrome.runtime.lasterror){
                console.log(chrome.runtime.lastError);
            }else{
                var oldArr = obj[type];

                if(oldArr !== undefined){
                    for(var i=0; i<oldArr.length; i++){
                        visit(oldArr[i]);
                    }
                }
            }
        }
    );
}

function justLog(str){
    console.log(str);
}

var sm = new StoreManager();
sm.visitItems("lol", justLog);
sm.addItem("lol", "bla");
sm.visitItems("lol", justLog);
sm.removeItem("lol", "bla");
sm.visitItems("lol", justLog);

manifest.json:
{
    "manifest_version": 2,
    "name": "Addon",
    "version": "0.0",

    "description": "no desc",

    "background": {
        "scripts": [
            "storeManager.js"
        ]
    },

    "permissions": [
        "storage"
    ]
}

A:

storage.local.set() is asynchronous. The data isn't guaranteed to be visible to a call to get() until the callback is invoked (or if you use browser.storage.local, set() will return a Promise and the data will be guaranteed to be written when that Promise resolves).
Your code is inherently full of race conditions.  The calls to addItem() and removeItem() are racing against the calls to visitItems(), by setting breakpoints you let one path or the other "win" the race.
If you expect deterministic results, I would suggest using the Promise variants of storage.local and writing your code as a series of chained handlers.


Q:

What's the name of Perl distribution units?

Package is a namespace. Module is a file with Perl code. cpan and cpanm are probably package managers. When I do cpanm XML::LibXML I install what exactly?

A:

Distribution (or "dist" for short).
The name for a Perl distribution unit is distribution, so cpanm XML::LibXML installs the XML-LibXML distribution, because it includes the specified XML::LibXML module.
Example 1

Example 2

Note that linux distributions usually have a package manager such as apt or yum, and many Perl distributions are made available as packages for those package managers. Someone using those package managers might refer to Perl distributions as packages, but that's not standard Perl jargon.

A:

When you download a package with a name like "UseFull::Munger"
You will at the very least get a file UseFull/Munger.pm installed in your perl library.
You could also get a set of modules used to implement the main module: "/UseFull/Munger/dyslexic.pm".
The module may be a wrapper around a C library (like LibXML) in which case you will get some binaries installed such as  "auto/XML/LibXML/LibXML.so".
If cpan needs to build a wrapper for a library you will get some "UseFull/Munger/SlickClib/SlikClib.xs" files which tell CPAN how to build the perl wrapper.
In addition, if the developer is nice, you may get lots of ".pod" document ion on how to use the module.


Q:

Accessing properties of objects in an ArrayList

I need to build a method to find the sum of the areas of the rectangles in a given ArrayList of rectangles.
public class Homework {
public static void main(String[] args) {
    ArrayList<Rectangle> test = new ArrayList<Rectangle>();
    test.add(new Rectangle(10, 20, 30, 40));
    test.add(new Rectangle(10, 10, 30, 40));
    test.add(new Rectangle(20, 20, 40, 50));
    test.add(new Rectangle(20, 10, 50, 30));
    System.out.println(areaSum(test));
    System.out.println("Expected: 5900.0");
    System.out.println(areaAverage(test));
    System.out.println("Expected: 1475.0");
}

public static double areaSum(ArrayList<Rectangle> rects){
    //work goes here
}

What I have so far is:
public static double areaSum(ArrayList<Rectangle> rects){
    double totalArea = 0;
    for (Rectangle r : rects) {
        double area = (x + width) * (y + height);
        totalArea = totalArea + area;
    }
    return totalArea;
}

How can I pull the dimensions of the rectangles from the ArrayList built by the tester block? I'm sort of new to the field, this is a homework assignment and I can't seem to figure it out.

A:

Change line that calculates the area to:
double area = r.getWidth() * r.getHeight();


Q:

Using a:hover to display a div

I'm trying to display a div class but it won't show. I'm not sure what I'm doing wrong. Here's what I'm doing.
So, I have a table. The point of this is to hover on one of the tables contents and show a display with more details of the link hovered. In this case "Hover Me!"
file.html

Hover Me!

 /*Just to keep the table short */

This is a Hover

 /*EO HoverPopUp */

 /*EO bigBody */

style.css
div.hoverPopUp {
    display:none;
    width:auto;
    height:auto;
    border:dotted purple;
}

a.hoverHereToPopUp:hover + div.hoverPopUp {
    display: block;
}

I added some styles to attempt to debug my issue:
a.hoverHereToPopUp {
    color:red;
    border:green dotted;
}

a.hoverHereToPopUp:hover {
    color:white;
    border:yellow dashed;
}

The hover is changing the color but the div isn't showing.
What am I doing wrong?
Viewing this on chrome.
The Hover is inside a table. which is inside a DisplayDiv, in that container there's another divContainer for the popUp. So, BIG box has 2 Small Boxes, one with the Hover(a table) and another(a div) for the Pop Up. Is this the problem????

A:

If I understand correctly, the hidden div needs to be inside the div which gets the hover.
Something like this:

    Hover over me

This is hidden

See: http://jsfiddle.net/webbymatt/URwNz/
The current way you have your markup means this will not work with CSS. What you need to do is put the hidden area INSIDE the hoverable div. Like this:

          Hover Me!

This is a Hover

 /*Just to keep the table short */

Then with your CSS
.hoverHereToPopUp p {
  display: none;
}
.hoverHereToPopUp:hover p {
  display: block;
}


Q:

Get HTTP Method from a joinPoint

I need to get the http method like POST/PATCH/GET/etc from a joinPoint in an aspect.
@Before("isRestController()")
    public void handlePost(JoinPoint point) {
        // do something to get for example "POST" to use below
        handle(arg, "POST", someMethod::getBeforeActions);
    }

From point.getThis.getClass(), I get the the controller that this call is intercepted. Then if I get the method from it and then annotations. That should be good enough right?
So point.getThis().getClass().getMethod(point.getSignature().getName(), ???)
How do i get Class paramaterTypes?

A:

Following code gets the required controller method annotation details
    @Before("isRestController()")
public void handlePost(JoinPoint point) {
    MethodSignature signature = (MethodSignature) point.getSignature();
    Method method = signature.getMethod();

    // controller method annotations of type @RequestMapping
    RequestMapping[] reqMappingAnnotations = method
            .getAnnotationsByType(org.springframework.web.bind.annotation.RequestMapping.class);
    for (RequestMapping annotation : reqMappingAnnotations) {
        System.out.println(annotation.toString());
        for (RequestMethod reqMethod : annotation.method()) {
            System.out.println(reqMethod.name());
        }
    }

    // for specific handler methods ( @GetMapping , @PostMapping)
    Annotation[] annos = method.getDeclaredAnnotations();
    for (Annotation anno : annos) {
        if (anno.annotationType()
                .isAnnotationPresent(org.springframework.web.bind.annotation.RequestMapping.class)) {
            reqMappingAnnotations = anno.annotationType()
                    .getAnnotationsByType(org.springframework.web.bind.annotation.RequestMapping.class);
            for (RequestMapping annotation : reqMappingAnnotations) {
                System.out.println(annotation.toString());
                for (RequestMethod reqMethod : annotation.method()) {
                    System.out.println(reqMethod.name());
                }
            }
        }
    }
}

Note : This code can be further optimized. Shared as an example to demonstrate the possibilities


Q:

For which values of $k$ the matrix is not diagonalizable over $\Bbb R$?

I'm not quite sure how to start this exercise. What are the steps I should follow in order to solve it?

For which values of $k$ the matrix is not diagonalizable over $\Bbb R$?
$$\begin{pmatrix} k+3 & 0 & 0 \\ -k-3 & k & k+3 \\ -k-3 & k & k+3 \end{pmatrix}$$

A:

This is my first answer so I apologize if it's not the best looking answer.
Let $A = \begin{pmatrix} k+3 & 0 & 0 \\ -k-3 & k & k+3 \\ -k-3 & k & k+3 \end{pmatrix}$
We'll find the eigenvalues of the matrix:
$ 0=|A - \lambda I| = \begin{vmatrix} k+3 & 0 & 0 \\ -k-3 & k & k+3 \\ -k-3 & k & k+3 \end{vmatrix}$
$= (k+3-\lambda)(k^2+3k-\lambda k - \lambda k - 3\lambda + \lambda ^2-k^2-3k)= \lambda(k+3-\lambda)(\lambda - (2k+3))
$
Therefore:
$
\lambda_1 = 0, \lambda_2 = k+3, \lambda_3 = 2k+3
$
Now, we'll find the corresponding eigenvectors:
For $\lambda_1 = 0$:
$
(A-0*I) = \begin{pmatrix} k+3 & 0 & 0 \\ -k-3 & k & k+3 \\ -k-3 & k & k+3 \end{pmatrix} \rightarrow \cdots \rightarrow\begin{pmatrix} k+3 & 0 & 0 \\ 0 & k & k+3 \\ 0 & 0 & 0 \end{pmatrix}$
$\begin{pmatrix} k+3 & 0 & 0 \\ 0 & k & k+3 \\ 0 & 0 & 0 \end{pmatrix}\begin{pmatrix} x\\y\\z\end{pmatrix} =  \begin{pmatrix} 0\\0\\0\end{pmatrix} \Rightarrow
\begin{cases}
(k+3)x=0 \\ ky=(-k-3)z
\end{cases} \Rightarrow \begin{cases}
x=0 &(k \ne -3) \\ y=\frac{-k-3}{k}z & (k \ne0) \\ z= Free
\end{cases} \Rightarrow \begin{pmatrix} 0\\\frac{-k-3}{k}\\1\end{pmatrix}
$
For $\lambda_2 = k+3$:
$
(A-(k+3)*I) = \begin{pmatrix} 0 & 0 & 0 \\ -k-3 & -3 & k+3 \\ -k-3 & k & 0 \end{pmatrix} \rightarrow \cdots \rightarrow\begin{pmatrix} 0 & 0 & 0 \\ 0 & -3-k & k+3 \\ -k-3 & k & 0 \end{pmatrix}$
$\begin{pmatrix} 0 & 0 & 0 \\ 0 & -3-k & k+3 \\ -k-3 & k & 0 \end{pmatrix}\begin{pmatrix} x\\y\\z\end{pmatrix} =  \begin{pmatrix} 0\\0\\0\end{pmatrix} \Rightarrow
\begin{cases}
(-k-3)y=(-k-3)z \\ (-k-3)x=-ky
\end{cases} \Rightarrow \begin{cases}
x=\frac{-k}{-k-3}z &(k \ne -3) \\ y=z \\ z= Free
\end{cases} \Rightarrow \begin{pmatrix} \frac{k}{k+3}\\1\\1\end{pmatrix}
$
For $\lambda_3 = 2k+3$:
$
(A-(2k+3)*I) = \begin{pmatrix} -k & 0 & 0 \\ -k-3 & -k-3 & k+3 \\ -k-3 & k & -k \end{pmatrix} \rightarrow \cdots \rightarrow\begin{pmatrix} -k & 0 & 0 \\ -6 & -3 & 3 \\ -3 & k & -k \end{pmatrix}$
$\begin{pmatrix} -k & 0 & 0 \\ -6 & -3 & 3 \\ -3 & k & -k \end{pmatrix}\begin{pmatrix} x\\y\\z\end{pmatrix} =  \begin{pmatrix} 0\\0\\0\end{pmatrix} \Rightarrow
\begin{cases}
-kx=0 \\ -6x-3y+3z=0 \\ -3x+ky-kz = 0
\end{cases} \Rightarrow \begin{cases}
x=0 & (k \ne 0)\\ y=z \\ z= Free
\end{cases} \Rightarrow \begin{pmatrix} 0\\1\\1\end{pmatrix}
$
Note: Since if $\lambda_3 = 0$ there will be repeated eigenvalues ($\lambda_1=0$), we'll check what happens if $k=-\frac{3}{2}$.
Therefore, for $k=0,-3$ the matrix is suspected to be not diagonalizable.
We'll check these values:
$\color{blue}{k=0}:$
$A_1 = \begin{pmatrix} 0 & 0 & 0 \\ -3 & 0 & 3 \\ -3 & 0 & 3 \end{pmatrix}, \lambda_1 = 3, \lambda_2=0$
For $\lambda_1 = 3$:
$(A-3I) = \begin{pmatrix} 0 & 0 & 0 \\ -3 & -3 & 3 \\ -3 & 0 & 0 \end{pmatrix} \rightarrow \cdots \rightarrow\begin{pmatrix} 1 & 0 & 0 \\ 0 & 1 & -1 \\ 0 & 0 & 0 \end{pmatrix}$
$\begin{pmatrix} 1 & 0 & 0 \\ 0 & 1 & -1 \\ 0 & 0 & 0 \end{pmatrix}\begin{pmatrix} x\\y\\z\end{pmatrix} =  \begin{pmatrix} 0\\0\\0\end{pmatrix} \Rightarrow
\begin{cases}
x=0 \\ y=z \\ z=Free
\end{cases} \Rightarrow \begin{pmatrix} 0\\1\\1\end{pmatrix}
$
For $\lambda_2 = 0$:
$(A-0*I) = \begin{pmatrix} 3 & 0 & 0 \\ -3 & 0 & 3 \\ -3 & 0 & 3 \end{pmatrix} \rightarrow \cdots \rightarrow\begin{pmatrix} 1 & 0 & 0 \\ 0 & 0 & 1 \\ 0 & 0 & 0 \end{pmatrix}$
$\begin{pmatrix} 1 & 0 & 0 \\ 0 & 0 & 1 \\ 0 & 0 & 0 \end{pmatrix}\begin{pmatrix} x\\y\\z\end{pmatrix} =  \begin{pmatrix} 0\\0\\0\end{pmatrix} \Rightarrow
\begin{cases}
x=0 \\ y=Free \\ z=0
\end{cases} \Rightarrow \begin{pmatrix} 0\\1\\0\end{pmatrix}
$
The number of eigenvectors (2) is different from the number of matrix rows (3). Therefore, the matrix is not diagonalizable for $k=0$.
$\color{blue}{k=-3}:$
$A_2 = \begin{pmatrix} 0 & 0 & 0 \\ 0 & -3 & 0 \\ 0 & -3 & 0 \end{pmatrix}, \lambda_1 = 0, \lambda_2=-3$
For $\lambda_1 = 0$:
$(A-0*I) = \begin{pmatrix} 0 & 0 & 0 \\ 0 & -3 & 0 \\ 0 & -3 & 0 \end{pmatrix} \rightarrow \cdots \rightarrow\begin{pmatrix} 0 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 1 & 0 \end{pmatrix}$
$\begin{pmatrix} 0 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & 1 & 0 \end{pmatrix}\begin{pmatrix} x\\y\\z\end{pmatrix} =  \begin{pmatrix} 0\\0\\0\end{pmatrix} \Rightarrow
\begin{cases}
x=Free \\ y=0 \\ z=Free
\end{cases} \Rightarrow \begin{pmatrix} 1\\0\\0\end{pmatrix}, \begin{pmatrix} 0\\0\\1\end{pmatrix}
$
For $\lambda_2 = -3$:
$(A-(-3)*I) = \begin{pmatrix} 3 & 0 & 0 \\ 0 & 0 & 0 \\ 0 & -3 & 3 \end{pmatrix} \rightarrow \cdots \rightarrow\begin{pmatrix} 1 & 0 & 0 \\ 0 & -1 & 1 \\ 0 & 0 & 0 \end{pmatrix}$
$\begin{pmatrix} 1 & 0 & 0 \\ 0 & -1 & 1 \\ 0 & 0 & 0 \end{pmatrix}\begin{pmatrix} x\\y\\z\end{pmatrix} =  \begin{pmatrix} 0\\0\\0\end{pmatrix} \Rightarrow
\begin{cases}
x=0 \\ y=z \\ z=Free
\end{cases} \Rightarrow \begin{pmatrix} 0\\1\\1\end{pmatrix}
$
The number of eigenvectors (3) equals to the number of matrix rows (3). Therefore, the matrix is diagonalizable for $k=-3$.
$\color{blue}{k=-\frac{3}{2}:}$
$A_3 = \begin{pmatrix} \frac{3}{2} & 0 & 0 \\ -\frac{3}{2} & -\frac{3}{2} & \frac{3}{2} \\ -\frac{3}{2} & -\frac{3}{2} & \frac{3}{2} \end{pmatrix}, \lambda_1 = 0, \lambda_2=\frac{3}{2}$
For $\lambda_1 = 0$:
$(A-0*I) = \begin{pmatrix} \frac{3}{2} & 0 & 0 \\ -\frac{3}{2} & -\frac{3}{2} & \frac{3}{2} \\ -\frac{3}{2} & -\frac{3}{2} & \frac{3}{2} \end{pmatrix} \rightarrow \cdots \rightarrow\begin{pmatrix} 1 & 0 & 0 \\ 0 & 1 & -1 \\ 0 & 0 & 0 \end{pmatrix}$
$\begin{pmatrix} 1 & 0 & 0 \\ 0 & 1 & -1 \\ 0 & 0 & 0 \end{pmatrix}\begin{pmatrix} x\\y\\z\end{pmatrix} =  \begin{pmatrix} 0\\0\\0\end{pmatrix} \Rightarrow
\begin{cases}
x=0 \\ y=z \\ z=Free
\end{cases} \Rightarrow \begin{pmatrix} 0\\1\\1\end{pmatrix}
$
For $\lambda_2 = \frac{3}{2}$:
$(A-\frac{3}{2}*I) = \begin{pmatrix} 0 & 0 & 0 \\ -\frac{3}{2} & -3 & \frac{3}{2} \\ -\frac{3}{2} & -\frac{3}{2} & 0 \end{pmatrix} \rightarrow \cdots \rightarrow\begin{pmatrix} 1 & 0 & 1 \\ 0 & 1 & -1 \\ 0 & 0 & 0 \end{pmatrix}$
$\begin{pmatrix} 1 & 0 & 1 \\ 0 & 1 & -1 \\ 0 & 0 & 0 \end{pmatrix}\begin{pmatrix} x\\y\\z\end{pmatrix} =  \begin{pmatrix} 0\\0\\0\end{pmatrix} \Rightarrow
\begin{cases}
x=-z \\ y=z \\ z=Free
\end{cases} \Rightarrow \begin{pmatrix} -1\\1\\1\end{pmatrix}
$
The number of eigenvectors (2) is different from the number of matrix rows (3). Therefore, the matrix is not diagonalizable for $k=-\frac{3}{2}$.
Finally, we can say that the matrix is not diagonalizable over $\Bbb R $ for $k=0, -\frac{3}{2}$ (only).


Q:

Не работает random_device

Имеется следующий код:
    std::random_device rd;
    std::uniform_int_distribution<int> dist(0, N_BRICK_KIND - 1);
    figure = static_cast<BrickType>(dist(rd));

На линуксе работает без проблем, но вот когда компилирую под винду (кросскомпиляция с помощью mingw) и запускаю под wine, то этот код приводит к одним и тем же результатам, всегда. При этом результат можно изменить только если перекомпилировать прогу. Заменил этот код на си-шный srand - rand - работает, но почему не работает код выше?

A:

Вот похожий вопрос из английского SO. Если кратко, то насколько я понимаю, в MingW для Windows еще не реализован random_device. Рекомендуют использовать версию из boost.


Q:

Как заставить группу setInterval работать синхронно?

 this.fade = function (t, f){
    var t = t || 500;
    var f = f || 50;
    var steps = t / (1000 / f);
    var op = 1;
    var d0 = 1 / steps;
    this.elements.forEach((e)=>{var timer = setInterval(function(){
        var current = timer;
        op -= d0;
        // устанавливаем opacity элементу DOM
        e.style.opacity = op;
        // уменьшаем количество оставшихся шагов анимации
        steps--;

        // если анимация окончена
        if(e.style.opacity <= 0){
        // убираем интервал выполнения
            clearInterval(current);
            // и убираем элемент из потока документа
            e.style.display = 'none';
        }

    }, 1000)});

};

код аналогичен fade jquery, только вот работает асинхронно(элементы исчезают не одновременно). Как задать setInterval чтобы они все работали синхронно?

A:

Попробуйте так:
this.fade = function (t, f){
    var t = t || 500;
    var f = f || 50;
    var steps = t / (1000 / f);
    var op = 1;
    var d0 = 1 / steps;

    var timer = setInterval(() => {
        op -= d0;

        this.elements.forEach((element) => {
            e.style.opacity = op;

            if(op <= 0){
                clearInterval(timer);
                e.style.display = 'none';
            }
        });
    }, 1000);
};


Q:

Rails association= return value and behavior

The guide does not say what return value would be for association= methods. For example the has_one association=
For the simple case, it returns the assigned object. However this is only when assignment succeeds.
Sometimes association= would persist the change in database immediately, for example a persisted record setting the has_one association.

How does association= react to assignment failure? (Can I tell if it fails?)
Is there a bang! version in which failure raises exception?

A:

http://guides.rubyonrails.org/association_basics.html#has-one-association-reference-when-are-objects-saved-questionmark
So another part of the guide does talk about the return behavior for association assignment.
If association assignment fails, it returns false.
There is no bang version of this.
Update
Behaviors around :has_many/has_one through seems to be different.
Demo repository: https://github.com/lulalalalistia/association-assignment-demo
In the demo I seeded some data in first commit, and hard code validation error in second commit. Demo is using rails 4.2
has_many through
class Boss < ActiveRecord::Base
  has_many :room_ownerships, as: :owner
  has_many :rooms, through: :room_ownerships
end

When I add a room, exception is raised:
irb(main):008:0> b.rooms << Room.first
  Boss Load (0.2ms)  SELECT  "bosses".* FROM "bosses"  ORDER BY "bosses"."id" ASC LIMIT 1
  Room Load (0.1ms)  SELECT  "rooms".* FROM "rooms"  ORDER BY "rooms"."id" ASC LIMIT 1
   (0.1ms)  begin transaction
   (0.1ms)  rollback transaction
ActiveRecord::RecordInvalid: Validation failed: foo
irb(main):014:0> b.rooms
=> #<ActiveRecord::Associations::CollectionProxy []>

has_one through
class Employee < ActiveRecord::Base
  has_one :room_ownership, as: :owner
  has_one :room, through: :room_ownership
end

When I add a room I don't get exception:
irb(main):021:0> e.room = Room.first
  Room Load (0.2ms)  SELECT  "rooms".* FROM "rooms"  ORDER BY "rooms"."id" ASC LIMIT 1
  RoomOwnership Load (0.1ms)  SELECT  "room_ownerships".* FROM "room_ownerships" WHERE "room_ownerships"."owner_id" = ? AND "room_ownerships"."owner_type" = ? LIMIT 1  [["owner_id", 1], ["owner_type", "Employee"]]
   (0.1ms)  begin transaction
   (0.1ms)  rollback transaction
=> #<Room id: 1, created_at: "2016-10-03 02:32:33", updated_at: "2016-10-03 02:32:33">
irb(main):022:0> e.room
=> #<Room id: 1, created_at: "2016-10-03 02:32:33", updated_at: "2016-10-03 02:32:33">

This makes it difficult to see whether the assignment succeeds or not.


Q:

Entity Framework DbContext and thread safety

I need to update a few tables in my DB in a single transaction and I read that using DbContext.SaveChanges should be the way to do so.
However I also read that the lifetime of the DbContext should be as short as possible because it grows over time as it loads more entities.
Also I read that in order to make it thread-safe, each action should have its own DbContext.
Should I have a DbContext for each table I want to change and call SaveChanges on each DbContext? Wouldn't the last SaveChanges call override the changes of the previous calls?
What is the best way to do it? (I need this for a website)

A:

Simple way is, to have one DbContext per request, ASP.NET MVC does all thread safety, each controller instance in ASP.NET MVC is isolated for every request, you don't have to worry about race conditions. As long as you don't create threads and just simply do data transformation in action method using single DbContext, you will not have any problem.
Basically DbContext does nothing, it just queues SQL query to target database, it is the database which handles multi threading, race conditions. To protect your data, you should use transactions and add validations in your database to make sure they are saved correctly
public abstract class DbContextController : Controller{

    public AppDbContext  DB { get; private set;}

    public DbContextController(){
        DB = new AppDbContext();
    }

    protected override void OnDisposing(bool disposing){
        DB.Dispose();
    }

}

If you inherit any class from DbContextController and use DB throughout the life of controller, you will not have any problem.
public ActionResult ProcessProducts(){
    foreach(var p in DB.Products){
       p.Processed = true;
       foreach(var order in p.Orders){
          order.Processed = true;
       }
    }
    DB.SaveChanges();
}

However, if you use any threads like in following example,
public ActionResult ProcessProducts(){
    Parallel.ForEach(DB.Products, p=>{
         p.Processed = true;
         // this fails, as p.Orders query is fired
         // from same DbContext in multiple threads
         foreach(var order in p.Orders){
             order.Processed = true;
         }
    });
    DB.SaveChanges();
}


Q:

Site Breadcrumbs

I'm working on a site and want to add breadcrumbs with border radius. I'm having trouble trying to make it look like breadcrumbs with 2nd and 3rd child z index.
What i want to achieve is the 2nd and 3rd child under the previous list.

JS Fiddle http://jsfiddle.net/1cnh7bz7/1/
this is my code
.uk-breadcrumb > li {
  font-size: 1rem;
  vertical-align: top;
  border: 1px solid #000000;
  border-radius: 500px;
  padding: 0 15px;
  background: #ffffff;
  margin-left: -20px;
}

.uk-breadcrumb > li,
.uk-breadcrumb > li > a,
.uk-breadcrumb > li > span {
  display: inline-block;
  z-index: 1;
}
.uk-breadcrumb .uk-active {
  background: #eeeeee;
  border: 1px solid #eeeeee;
  z-index: 2;
}

Home

Culture

arts

any help appriciated

A:

I have used a little hack on the z-index to make it work. First of all, you were playing with z-index without using a position value, so it had no effect. See the lines .uk-breadcrumb > li + li it targets a element li next to another li and used multiple of these to determine if it is the first, second or third and then applied the correct z-index.
I've started the z-index at 10 but could have started at any number, but starting higher than needed makes it easier to just add a level if we wanted 4 levels instead of three. I am sure the community can find a better way to do it by nexting instead, but this will work well enough...

.uk-breadcrumb > li {
  font-size: 1rem;
  vertical-align: top;
  border: 1px solid #000000;
  border-radius: 500px;
  padding: 0 15px;
  background: #ffffff;
  margin-left: -20px;
}
.uk-breadcrumb > li {
  z-index: 10;
}
.uk-breadcrumb > li + li {
  z-index: 9;
}
.uk-breadcrumb > li + li+ li {
  z-index: 8;
}
.uk-breadcrumb > li,
.uk-breadcrumb > li > a,
.uk-breadcrumb > li > span {
  display: inline-block;
  position: relative;
}
.uk-breadcrumb .uk-active {
  background: #eeeeee;
  border: 1px solid #eeeeee;
}

Home

Culture

arts


Q:

fl.transitions.Tween not found on ActionScript Mobile project

I'm developing an ActionScript mobile project for Android.
When I add the following import, compiler says that is not found.
import fl.transitions.Tween;

How can I use Tween with mobile projects?
package{
    import flash.display.Sprite;
    import flash.text.TextField;
    import flash.events.MouseEvent;
    import fl.transitions.Tween;
    import fl.transitions.easing.Strong;

    public class spriteButton extends Sprite
    {
        private var alphaOver:Tween;
        private var alphaLabelOver:Tween;
        private var alphaLabel:Tween;

        public function spriteButton(newLabel:String)
        {
            myLabel.text = newLabel;
            myLabelOver.text = newLabel;
            myLabelOver.alpha = 0;
            buttonMode = true;
            mouseChildren = false;
            addEventListener(MouseEvent.MOUSE_OVER, handleMouseOver);
            addEventListener(MouseEvent.MOUSE_OUT, handleMouseOut);
            addEventListener(MouseEvent.MOUSE_UP, handleMouseUp);
        }

By the way, I'm very new on ActionScript 3.0 development.
I get this errors:
The import fl could not be found.
The import Tween could not be found.

Description Resource    Path    Location    Type
1172: Definition fl.transitions:Tween could not be found.   spriteButton.as /Test01/src line 4  Flex Problem

A:

if you are new to AS3, then use this library: http://www.greensock.com/tweenmax/ for tweenning objects.


Q:

what is the environment variable for 'app alias' on OpenShift?

I have checked all the variables listed on the official link,
For a deployed app on openshift, How do i get the alias of the app?
I've added subdomain.example.com as the alias, but the variable OPENSHIFT_APP_DNS is just showing the *.rhcloud.com address but not the alias added, how do I access the alias with environment variables?

A:

There is not currently an environment variable that holds this information within your application.  If you need to retrieve it programmatically you might check into the OpenShift Online API (https://access.redhat.com/documentation/en-US/OpenShift/2.0/html/REST_API_Guide/)


Q:

Entries tag search:fieldtype=""

According to the EE doc, within a channel entries tag you can search a grid field as long as the field color is set to "yes" for Include in search.
I have bot he Grid field and the individual column set to yes, but don't get results when I definitely should.
In the example below, there is a Grid titled "product_application" and one of 3 fields with the title "partno".
{exp:channel:entries channel="models" search:partno="={segment_3}"}
    <p>{title}-</p>
{/exp:channel:entries}

Has anyone run into difficulties with this?
Russ

A:

To use search parameter in Grid you have to add search parameter in grid fieldtype not in Channel entries tag. You can get more information from below example. https://docs.expressionengine.com/latest/fieldtypes/grid.html#searchcolumn_name
{grid_field search:partno="search_value"}
    {grid_field:your_grid_field}
{/grid_field}

I hope this will works for you. Thanks!


Q:

While loop in Shell

I want to make a while...loop statement in my Shell script like:
while [ $line < $line_number ]; do
    echo $line
done

But there is an error. I think it is because I wrote it in bash code. But I need to do it in sh mode. How can I do it? Thanks!

A:

You need to use, either
while [ $line -lt $line_number ]; do
    echo $line
done

or
while [[ $line < $line_number ]]; do
    echo $line
done

Disscussion[source]
Single [] are posix shell compliant condition tests.
Double [[]] are an extension to the standard [] and are supported by bash and other shells (e.g. zsh, ksh). They support extra operations (as well as the standard posix operations). For example: || instead of -o and regex matching with =~. A fuller list of differences can be found in the bash manual section on conditional constructs.
Use [] whenever you want your script to be portable across shells. Use [[]] if you want conditional expressions not supported by [] and don't need to be portable.


Q:

Communicating that I don't appreciate being repeatedly pressed to do something

A close family member, Ann, has been trying to get me to do XYZ for years. She'll text me every now and then asking if I've done it yet. Every time we see each other she'll no doubt bring it up. She's been close to fanatical about XYZ. She'll call me and preach about how I should be doing this.
Recently, she finally began to listen to my reasons of why I don't think XYZ is a good idea for me. And--amid the preaching--she actually made some entirely valid points about why maybe this is a good idea for me. I've been thinking about this for the last few days, and I think I may give XYZ a shot.
I'd like to tell Ann as much, and let her know what she said to convince me and my reasons for doing this (as it'll undoubtedly come up the next time I see her anyways).
However, I'd like to make it absolutely clear that I do not approve of her methods. I do not appreciate being constantly hounded after on this point and having this brought up every time I see her despite my (prior) obvious refusal. My fear though, is that even if I express these feelings, when I say that I am in fact going to try XYZ, that's all she'll hear.
How can I impress upon her how little I appreciate her behavior despite me agreeing with her?

A:

I see three things here:

Ann has a history of repeatedly pushing you.
You've had only 1 good conversation about XYZ so far.
That conversation had some points that made you change your mind, and you're now thinking of doing XYZ.

My parents can be pushy. They'll repeatedly tell me to do things, or change the way I do things. But it often takes a conversation like the last one you had with Ann to change my mind: I don't need to be told to do things a certain way over and over, I need to be explained why doing things a certain way is better, I need to hear their arguments, not just their opinion. And, like Ann, years ago my parents saw me changing my mind as their personal victory, as a result of their repeated reminders, and not as a conscious choice from my side that was made based on mutual understanding.
For me, it has helped to voice this to my parents, and keep it separate from doing XYZ. So my advice to you would be to first have a good conversation with Ann, that focuses on how much better you liked having the conversation where she did listen to your concerns, and provided counterarguments. Tell her that for you, there's such a clear difference between her behaviour before (texting, bringing it up at every occasion) and the good conversation you had. Point out specifics. Basically, tell her everything you told us here, and perhaps more.
But keep XYZ out of that conversation. Don't immediately tell Ann that you're now thinking of doing XYZ. If you can, don't do XYZ before having had that conversation, and don't do it immediately after either. That way, Ann will hopefully have time to process what you had to say about the conversation without associating it with XYZ.
Eventually, you do need to tell her that the good kind of conversation helped you change your mind on XYZ, while all other the other things she did never helped. This may just be a casual line at the end of the conversation, but make sure to only tell her about doing XYZ once you have the firm impression that she gets the part about communicating. If that point doesn't come, don't tell her about doing XYZ. You might even refrain from telling her until she's trying to get you to do ABC by preaching again, by telling her at that point it wasn't her preaching that made you decide to do XYZ.
You're probably going to need to have multiple conversations about this. You should be ready to repeatedly remind Ann about how you like to talk about these things when she's on to having you do ABC. You need to keep complimenting her or expressing your gratitude after having had a good kind of conversation. In the same way, you need to tell her when you're not up to having one or remind her of the good way to talk about things if she's just preaching again.
For me, I had to have a few similar conversations with my parents, most of them made without relating it to any specific thing they wanted me to do or which I had in the past changed my mind on. It worked, to an extent. They will still point out things to me, and they will still ask me to do so repeatedly. But we're now at a point where, if things are brought up a few times, we'll end up having a conversation where we will exchange arguments and viewpoints, and sometimes I end up changing my mind, sometimes they see I have a point and will stop asking. And we all understand now that repeatedly bringing something up is not the thing that changed any minds, that it was only the thing that sparked the meaningful conversation.


Q:

vim cut and paste history

When I'm 'cutting' in vim, I believe there are registers that keep a history of all the recent things I've cut.  How do I access those registers?
For example, let's say I cut each one of these words consecutively

'Hello'
'World'
'And'
'Vim'

Note that I'm not actually saving these edits into particular registers, I'm just using 'd' four times consecutively.

A:

The
:help registers
command reveals that there are 10 numbered registers ("0 to "9).
Register "0 is the most recent thing yanked; register "1 has the most recent deleted text, register "2 the previous deletion, "3 has the deletion before that, and so on.
If you delete each line in turn, registers "1, "2, "3 and "4 will contain "Vim", "And", "World" & "Hello", respectively.
You can verify this by using the :reg (or :registers) command:
:reg
""   Vim^J
"1   Vim^J
"2   And^J
"3   World^J
"4   Hello^J

So after deleting the four lines one at a time, you could recover the 2nd line ("World") with
"3p

because it's the third most recent deletion.

A:

In addition to njd's answer, this can be simplified with the YankRing plugin.  As well as making it easier to browse the previous yanks, you can configure some keys to allow you to pop previous yanks off the 'stack'.  This allows you to do:
yy    " Copy first line
yy    " Copy second line
yy    " Copy third line
yy    " Copy fourth line
" Assumes you've mapped ,p to be the pop command: choose your preferred key or key-combination
,p    " Paste fourth line and pop it off the Yank Ring
,p    " Paste third line and pop it off the Yank Ring
,p    " Paste second line and pop it off the Yank Ring
,p    " Paste first line and pop it off the Yank Ring


Q:

A question on the ambiguity of the Alternate History genre

Say I am writing a (mostly) realistic fiction book. The entirety of said work is mostly what a person would expect from realistic fiction with the world being almost entirely similar to our own, politically and what-not. But then say I interjected a few minute details that are considered unhistorical, for example: one of the characters visit their relative who was a hoarder that was raised in the great depression, and they stumble upon a newspaper that had a headline detailing Germany bombing the eastern coast of the United States during the first Great War.
Would it still be considered realistic fiction if nothing else was out of the ordinary except that little footnote of a detail?

A:

Everything in a story has to matter. If you write alternate history, the alternate has to matter to the story. If you put in a detail that is obviously and deliberately contrary to history (as opposed to an accidental anachronism, which you will find in many books if you look hard enough) then it is alternate history. And if it is alternate history in which the alternate history does not matter, it is just plain weird.

A:

The definition of the whole genre "Alternate History" is that you are mostly trying to be as realistic as possible, except for one or more historical events. It's completely up to you what those details are and to what extent you exactly want to change reality. If you want a newspaper to talk about Germany attacking the United Stated then go ahead and do that - just be aware that your readers will likely have some knowledge about the real events and might pick up on these differences, which means that you should either talk about them in greater detail later in the book or treat them as a sort of "Easter-Egg", a little detail that some people might pick up, but that is irrelevant to the overall story. The reason for placing Easter-Eggs in your story would be to give the readers that look for them a few things to talk about - it should be a few things, not just one - and you should make it obvious that this is an Easter-Egg. Most of the time you wouldn't do something like this in a book.
You could of course just state that the newspaper article said that there was such an attack and later you explore how this specific newspaper was often accused of false or not-completely-true news. This has to fit in the story however.
All in all it's completely fine to change little details in this genre, but if you don't want to do something with it you should leave it out. Either it plays a role and is an intended difference, or it's explored to be at least not-completely-true or it's treated as a part of multiple little Easter-Eggs that you want your readers to find so that they may find out some hidden information for example - but you should not just put in a little difference, just for the sake of having a little difference in your book.

A:

What is your purpose in wanting to do this?
If the story is 99% set in the real world, and then you throw in this one paragraph of alternate history, and then the story goes back to the real world and the alternate history is never mentioned again ... I don't see the point. The reader will either think you are very confused about history, or they will expect this incident to make a difference. They will expect it to have some relevance or purpose. Readers who are not interested in an alternate history story will be annoyed that you dragged it in, and readers who want to read an alternate history story will be annoyed that you dropped it.
There's nothing wrong with mixing genres. You can include a romance subplot in a science fiction story, or have a horror story set in the Old West. But there is something very, very wrong with dragging in another genre for one paragraph and then apparently forgetting that you did it.


Q:

Quotient of flat module is flat - a property in Mumford's Red book

Hi,
In Mumford's "Red Book of Varieties and Schemes", Chapter III, Paragraph 10 (entitled "Flat and smooth morphisms"), the following property is stated:
Let $M$ be a $B$-module, and $B$ an algebra over $A$. Let $f\in B$ have the property that for all maximal ideals $m \subset A$, multiplication by $f$ is injective in $M / m \cdot M$. Then $M$ flat over $A$ implies $M / f \cdot M$ flat over $A$.
My question is whether this statement is true as stated, without some finiteness assumptions (it is not clear, for example, what is the role of $B$ here if no finiteness is assumed), and, secondly, can someone indicate a proof, or an exact reference for a proof.
Thank you,
Sasha

A:

This is false without finiteness conditions: let $k$ be a field, $A=k[X,Y]$, $B=A_{(X)}$, $M=B$, $f=X$.

A:

As Hailong Dao comments above, Matsumura's "Commutative Ring Theory", Theorem 22.6, implies the theorem in the body of the question for the case when $A$,$B$ are Noetherian, and $M$ is of finite type over $B$ (maybe almost what is written in the body of the question, since there one checks not for maximal ideals $m \subset A$ but for preimages of maximal ideals of $B$, which might be only prime).
Actually, there is also a version for the case when $B$ is of finite presentation over $A$, and $M$ is a $B$-module of finite presentation (which follows from the Noetherian case by the trick "finitely presented morphism is base change of morphism between Noetherian things". One can find it in Grothendieck's EGA IV, part 3, proposition 11.3.7 (in geometric formulation) (I do not understand the organization into chapters of EGA, so I hope I gave a correct reference). Thus there is a correct statement:
Let $i: A \to B$ be of finite presentation, $u: M \to N$ a morphism between two finitely-presented $B$-modules. Suppose that $N$ is flat over $A$. Then the following are equivalent:
a) $u$ is injective and $Coker(u)$ is flat over $A$.
b) For every $q \in Spec(B)$, the morphism $id\otimes u : k(p)\otimes_A M \to k(p)\otimes_A N$ is injective, where $p = i^{-1} (q)$ and $k(p)$ is the fraction field of $A / p$.


Q:

Servers with Access-Control-Allow-Origin: *

I'd like to test image loading over AJAX from jsFiddle, but I don't know any sites that allow AJAX from remote domains.

A:

Here you go, an image with the Access-Control-Allow-Origin: * header:
http://novaember.com/img/testimg.php


Q:

Need to help to convert string to hex bytes

I am programming in Java.  The program have a String as below.
String str = "byte."

Can the above string be converted to an array of hex bytes as below?
byte[] data = {0x62, 0x79, 0x74, 0x65};

Thank you.

A:

There's no such thing as "hex bytes" and more than there are "decimal integers" vs "hex integers".
You can certainly convert a string to a byte array though. For example:
byte[] data = str.getBytes("UTF-8");

The UTF-8 part here is the name of the encoding to use - where an encoding is effectively a mapping between Unicode characters and bytes. (It's somewhat more complicated than that, but it's a good first approximation.)
There is a parameterless overload of String.getBytes() but I would strongly recommend that you don't use it - it will pick the platform default encoding, which is rarely a good idea.
You can also use an overload taking a Charset, which ends up being nicer in conjunction with a library such as Guava, where you can write:
byte[] data = str.getBytes(Charsets.UTF_8);

... so you no longer rely on a string representation.


Q:

How to count the number of digits of an integer in python3 with recursion.Cannot convert int to str and cannot use loops

Needs to return the number of digits in an integer using recursion.NO LOOPS and cannot use str function either.I have the general case but i need help with the base case:
    def count(x):
       x=abs(x)
      #general case
      if x<10:
       return 1
      #base case

    x=123
    print(count(x))

A:

you are on the right track, so when its less than 10 you know that its a single digit so you can return 1, otherwise its greater than 10 so return 1 + the result of the function passing in x // 10
def count(x):
    if abs(x) > 10:
        return 1 + count(x // 10)
    return 1

for i in (1, 23, 345, 454564, 34, -345, -98):
    print(f'There are {count(i)} digits in the number {i}')

OUTPUT
There are 1 digits in the number 1
There are 2 digits in the number 23
There are 3 digits in the number 345
There are 6 digits in the number 454564
There are 2 digits in the number 34
There are 3 digits in the number -345
There are 2 digits in the number -98


Q:

Debugging tips?

I'm new to games programming and I'm working on a C#/XNA project.
Something I'm spending a lot of time on is debugging. Obviously as games run in a loop finding the exact iteration that a bad condition has occurred can be tricky.
Spending time setting up conditional breakpoints certainly helps but eats up time.
Are there some ninja tips out there for helping to track down the precise moment things go bad that you guys use?

A:

you can try creating log files, although they may a be a bit hard to work with but they are useful in many ways:

using log files you can replay your game with all the things happen in it including the bugs! so in case of rare bugs you can check the bug again and again until you solve it.
using log files you can monitor your variables without stopping your program, I mean when you try debugging your program is stopped for a couple of minutes when you are checking what is happening and usually that will lead to unexpected frames after debugging. but using log files you can monitor all those variables after program execution so there will be no unexpected changes in your application results.
later on you can use same log file feature to create a replay viewer for your game, it's pretty good if a gamer could see what he did or what he didn't to win/lose a game.

A:

Kind of a simple advice here but a little something that I found very useful is displaying debugging strings/rectangles to the screen.
You can print the player's current state, the enemy's animation state, the number of active bullets, the frames per second, etc. All these simple variables are what make up the core of your game, so it's essential that they work properly and a nice way to make sure they do so is to have debugging tools at hand.
So, in addition to logging variables like Gajet proposed (which is a very good advice imho), you should also show these variables while your testing so you can clearly see when something is wrong.
It may seem stupid, but it helped me find a lot of nasty bugs that I thought were much more complicated (I simply put red rectangles to show colliding tiles on a platformer, and I found out that the problem wasn't in the collision response code, but rather in the collision detection code).
You'll start out with a debugging string tool, then move on to debugging shapes (rectangles or even lines to represent vectors), then to more complicated tools and you'll eventually end up with a pretty solid debugging toolbox that you can reuse over other projects (if you make sure your debug code is general enough to be independant of the game).
In addition to debugging tools, consider writing unit tests. I know it doesn't sound nice having to write tests for most functions from your game, but don't see it this way. Unit tests can save you a whole lot of time. For example, if your collision system is not working but you wrote enough unit tests for your collision detection, you can just look into your collision response code and find the bug.
Not only does it tell you where to look for the bug, it also tells you when you break something after changing a few lines somewhere, because your tests won't pass anymore.
If unit tests are too much for you, then at least start adding assertions into your code. So, if something is obviously wrong (e.g. a character with negative health), your code will break right away and you won't waste your time too much.

A couple of advices that I learned the hard way. You may think some are useless, but try them out and see if they fit your debugging needs.


Q:

Do all ultimates charge at the same speed?

Lately I have been playing a lot as Tracer and noticed my ultimate charges faster than other characters. Do all ultimates charge at the same speed, what exactly effects it?

A:

Most of the time, the primary role of the hero, and is he fulfilling  it, is the main ultimate charge booster.
For instance, if you're a Mercy and stay at your spawn your Ultimate will charge quite slowly. if, on the other had you're healing someone who's taking alot of damage, your ultimate will charge much faster.
Also check this thread out. To summarise:
Passive charge rate (from fastest to slowest)

5% charge in approx 4 seconds (mech-less D.VA)
5% charge in approx 7.5 seconds (Symmetra)
5% charge in approx 8.5 seconds (Tracer)
5% charge in approx 9 seconds (Mei, Widowmaker, Mercy)
5% charge in approx 10 seconds (Roadhog, Reinhardt)
5% charge in approx 12 seconds(Genji, McCree, Hanzo, Junkrat, Torbjorn, D.VA, Reinhardt, Winston)
5% charge in approx 15 seconds (Pharah, Reaper, Soldier 76, Bastion,
Zarya, Lucio, Zenyatta)

And now for how much heroes charge for damaging enemies (from highest to lowest):

60% charge for 200 damage (mech-less D.VA)
25% charge for 200 damage (Symmetra)
22% charge for 200 damage (Tracer) 20% charge for 200 damage (Mei, Widowmaker)
18% charge for 200 damage (Winston, Roadhog, Reinhardt)
16% charge for 200 damage (Genji, McCree, Hanzo, Junkrat, Torbjorn, D.VA)
14% charge for 200 damage (Pharah, Reaper, Soldier 76, Bastion, Zarya)
12% charge for 200 damage (Zenyatta)
10% charge for 200 damage (Lucio)


Q:

Hibernate Criteria for assotiated objects

I have the next structure of DTO objects:
public class MainDTO implements Serializable {
    private Long mainId;
    private String name;
    ... //some other fields
    private boolean disabled;

    @ManyToOne()
    @JoinColumn(name = "root_id")
    private RootDTO root;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "child_id", updatable = false, referencedColumnName = "child_id")
    @Cascade(value = { CascadeType.ALL, CascadeType.DELETE_ORPHAN })
    private ChildDTO child;

    ...
}

public class RootDTO implements Serializable {
    ... //some other fields
    private boolean disabled;

    ...
}

public class ChildDTO implements Serializable {
    private Long childId;
    ... //some other fields
    private boolean disabled;

    @ManyToOne()
    @JoinColumn(name = "info_id")
    private InfoDTO info;

    ...
}

public class InfoDTO implements Serializable {
    private Long infoId;
    ... //some other fields
    private boolean disabled;

    ...
}

I need to fill Map<String, Map<Long, Long>> (<name from MainDTO, <mainId from MainDTO, infoId from InfoDTO >>) with next restrictions:
MainDTO.disabled = false,
MainDTO.root != null,
MainDTO.root.disabled = false,
MainDTO.child.disabled = false,
MainDTO.child.info != null,
MainDTO.child.info.disabled = false
Here is the code I've written, but got stuck in select infoId from InfoDTO:
Criteria rootCriteria = getSession().createCriteria(
        MainDTO.class);

// check that root is enabled
rootCriteria.createCriteria("root", "root").add(
    Restrictions.eq("disabled", false));

// check that child is enabled
Criteria childCriteria = rootCriteria
    .createCriteria("child", "child")
    .add(Restrictions.eq("disabled", false))
    .add(Restrictions.isNotNull("info"));

// check that info is enabled
childCriteria
    .createCriteria("info", "info")
    .add(Restrictions.eq("disabled", false));

ProjectionList rootProjection = Projections.projectionList()
    .add(Projections.property("mainId"))
    .add(Projections.property("name"))
    .add(Projections.property("child.info")); //HOW TO SELECT ONLY ID??
rootCriteria.setProjection(rootProjection);
rootCriteria.add(Restrictions.eq("disabled", false))
    .add(Restrictions.isNotNull("root"))
    .add(Restrictions.isNotNull("child"));

Thanks a lot!

A:

First of all, calling entities DTO is really confusing.
Now regarding your question, you should use the aliases you defined in your projections
ProjectionList rootProjection =
    Projections.projectionList()
               .add(Projections.property("mainId"))
               .add(Projections.property("name"))
               .add(Projections.property("info.infoId"));

Also, given that you're doing an inner join to root and child, the last two restrictions are not necessary: the inner joins already make sure those are not null.


Q:

Editing a post shows error about suggesting an edit

I just tried to edit one of my questions using the app. When I hit preview and submit it gave me this error:

What is the cause and can this be fixed?

A:

This will be fixed in the next build.
As I mentioned on your other bug, I've updated the filters the app uses to access fetch content from the API.  The filters are backwards/forwards compatible encoded strings that look something like )g0iMTmRaNniMgq0(nQfUJj1aHybaUZB0WC2dD2pZmozwzuw, so naturally when editing them, I let the API do it for me.  This involves pasting the code onto the filter field like this, making changes, then copying the new value.
Unfortunately, the app uses the yet unreleased 2.3 version of the API which provides fields like can_edit and can_suggest_edit and I accidentally re-encoded the filters that need that with a 2.2 filter editor which cropped off those values.
To test that this works, I'll be editing both this answer and your tags using the app.


Q:

How do you erase all content of a flowdocument

I have created a flowdocument and added numerous paragraphs to it programmically. Now in the I would like to be able to reset the flow document to a blank slate resulting in everything being erased.
I have looked for things like Clear, Reset, RemoveAll, Erase. Is there a method to emptying the document?

A:

Clear the Blocks collection of the FlowDocument:
document.Blocks.Clear();

The FlowDocument documentation includes this example, as well as other common operations (such as inserting a new paragraph at the beginning, or deleting the last block element).

A:

The following example clears all of the contents (Block elements) from the FlowDocument.
flowDoc.Blocks.Clear();

See the FlowDocument Overview for more examples.


Q:

Can Java system clipboard copy a file?

I've used Java system clipboard to transfer text and image, but I wonder if it can copy and paste files ? If so where can I find some sample code ?
I found a similar question at : How can I copy a file and paste it to the clipboard using Java?
But nowhere in it can I find the word "clipboard", and I don't know how to use it.
The methods I use to copy image look like this :
  public static void setClipboard(Image image)                                           // This method writes a image to the system clipboard : from exampledepot.com
  {
    ImageSelection imgSel=new ImageSelection(image);
    Toolkit.getDefaultToolkit().getSystemClipboard().setContents(imgSel,null);
  }

  public Image getImageFromClipboard()                                                   // Get an image off the system clipboard
  {
    Transferable transferable=Toolkit.getDefaultToolkit().getSystemClipboard().getContents(null);
    if (transferable!=null&&transferable.isDataFlavorSupported(DataFlavor.imageFlavor))
    {
      try { return (Image)transferable.getTransferData(DataFlavor.imageFlavor); }
      catch (UnsupportedFlavorException e) { e.printStackTrace(); }
      catch (IOException e) { e.printStackTrace(); }
    }
    else System.err.println("getImageFromClipboard: That wasn't an image!");
    return null;
  }

How to modify the above code to transfer files ?

A:

Essentially, yes.  You need to remember that both the drag'n'drop API and the clipboard API use the same concept of a Transferable, which wraps the data into DataFlavors, so you can transfer the data differently based on the flavor the target system would like to use
Generally, when transferring files, Java uses a java.util.List and a DataFlavor.javaFileListFlavor.  Unfourtantly, there's no nice "wrapper" class available for this, so you'll need to provide your own, for example...
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class Test {

    public static void main(String[] args) {
        File file = new File("/path/to/your/file");
        List listOfFiles = new ArrayList();
        listOfFiles.add(file);

        FileTransferable ft = new FileTransferable(listOfFiles);

        Toolkit.getDefaultToolkit().getSystemClipboard().setContents(ft, new ClipboardOwner() {
            @Override
            public void lostOwnership(Clipboard clipboard, Transferable contents) {
                System.out.println("Lost ownership");
            }
        });
    }

    public static class FileTransferable implements Transferable {

        private List listOfFiles;

        public FileTransferable(List listOfFiles) {
            this.listOfFiles = listOfFiles;
        }

        @Override
        public DataFlavor[] getTransferDataFlavors() {
            return new DataFlavor[]{DataFlavor.javaFileListFlavor};
        }

        @Override
        public boolean isDataFlavorSupported(DataFlavor flavor) {
            return DataFlavor.javaFileListFlavor.equals(flavor);
        }

        @Override
        public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
            return listOfFiles;
        }
    }

}

In my tests, I was able to place a File in the List, wrap into a Transferable, pass it to the Clipboard and was able to paste the file through the system (Windows Explorer)


Q:

issue using 2 sections inside  element

Im trying to have 2 sections inside my  element.
My 1st section I want to have some columns with content. (its owrking fine)
My 2nd section I want to have below the 1st section and I want to have a black background with a paragraph aligned at left.
I think Im doing everything ok but its not working correctly.
Do you see what can be wrong in my code?
Im having this:

But Im trying this:

My jsfiddle with issue Im having:
http://jsfiddle.net/ra3zc/1/
My html:

Title of my column 1

Content of col 1

Title of my column 2

Content of col 2

Title of my column 3

Content of col 3

© I want copyright float at left in section 2

My css:
#footer-container
{
    width:100%;
    height:auto;
    float:left;
    background:gray;
}

#footer
{
    width:960px;
    margin:0 auto 0 auto;
}

#col
{
    float:left;
    margin-right:40px;
    margin:10px 53px 10px 0;
    width:200px;
}

#col h1
{
    color:#fff;
    font-size:17px;
    font-weight:bold;
    margin-bottom:10px;
}

#col p
{

    color:#ccc;
    font-size:14px;
    margin-bottom:10px;
}

#footer
{
    width:960px;
    margin:0 auto 0 auto;
    background:#000;
    height:100px;
}

A:

Basically your floats weren't clearing.
All you need to know about floats: http://css-tricks.com/all-about-floats/
Try this:
http://jsfiddle.net/ra3zc/2/
#footer-container {
    width:100%;
    height:auto;
    background:gray;
}
#footer {
    overflow: hidden;
    width:960px;
    margin:0 auto 0 auto;
}
#col {
    float:left;
    margin-right:40px;
    margin:10px 53px 10px 0;
    width:200px;
}
#col h1 {
    color:#fff;
    font-size:17px;
    font-weight:bold;
    margin-bottom:10px;
}
#col p {
    color:#ccc;
    font-size:14px;
    margin-bottom:10px;
}
#footer2 {
    width:960px;
    margin:0 auto 0 auto;
    background:#000;
}
#footer2 p {
    padding: 2em 0;
    color: white;
}


Q:

insert the last inserted record id into an array in another table using Codeigniter

so I got two tables one called patients and another called tests , the tests table has the patient id , i have a page called add patient which have fields for adding new patient information and other fields for adding their test info and upload all the data into the two tables in one query ,tests fields could be duplicated by ajax to i could add more than one test to the same patient , now i wanna add more than one test at the same time into the tests table and i managed to do so but the case is i can't add the patient_id into tests table, i wanna add the same patient_id more than one time to all the tests i have added while adding a new patient in that page, i'm new to Codeigniter!
this is the adding page
the patient fields and the test fields
<input type="text" name="patientname" />
<input type="text" name="address" />

<input type="text" name="testname[]"/>
<input type="text" name="price[]" />

and this is my controller
public function testbby
{
    $this->load->model("khmodel", "Khmodel");

    // patient main info
    $patient_input_data = array();
    $patient_input_data['patientname'] = $this->input->post('patientname');
    $patient_input_data['address'] = $this->input->post('address');

    //test data
    $testname = $this->input->post('testname[]');
    $price = $this->input->post('price[]');

    $test_input_data = array();
    for ($i = 0; $i < count($testname); $i ++ )
    {
        $test_input_data[$i] = array(
            'testname' => $testname[$i],
            'price' => $price[$i],
        );
    }
    $this->Khmodel->insert_bby($patient_input_data, $test_input_data);

    redirect('main/dashboard');
}

and this is my model
public function insert_bby($patient, $test)
{
    $this->db->insert('patients', $patient);
    $patient_id = $this->db->insert_id();

    // i used this and it worked but only while adding one test , s
    //once it's gonna be an array i dunno what to do with the id !
    //$test['refpatient']=$patient_id;
    $this->db->insert_batch('tests', $test);

    return $insert_id = $this->db->insert_id();
}

A:

the value i mean , i dont know but your code seems to be so right and logical
but i have tried this code and it worked so well , i didn't even use the model/
 public function testbby
{
$this->load->model("khmodel", "Khmodel");

// patient main info
$patient_input_data = array();
$patient_input_data['patientname'] = $this->input->post('patientname');
$patient_input_data['address'] = $this->input->post('address');

//test data
$testname = $this->input->post('testname[]');
$price = $this->input->post('price[]');

    $this->db->reset_query();
    $this->db->insert('patients', $patient_input_data);
    $patient_id=$this->db->insert_id();
$test_input_data = array();
for ($i = 0; $i < count($testname); $i ++ )
{
    $test_input_data[] = array(
        'testname' => $testname[$i],
        'price' => $price[$i],
        'patient_id'=>$patient_id

    );
}
  $this->db->reset_query();
  $this->db->insert_batch('tbl_tests',$test_input_data);
   redirect('main/dashboard');
   }


Q:

java URLConnection - how to read data from URLs containing uppercase?

https://docs.oracle.com/javase/tutorial/networking/urls/readingWriting.html has an example with:
URL oracle = new URL("http://www.oracle.com/");

that works fine, but if the URL has uppercase, like https://file-examples.com/wp-content/uploads/2017/08/file_example_PPT_250kB.ppt
then get error about URL not exists (and there is https://file-examples.com/wp-content/uploads/2017/08/file_example_ppt_250kb.ppt in the stack trace)

A:

URL/filename.fileformate in this filename is case sensitive you have to manage tolowercase  when you create it


Q:

Oracle text index (Context) keep growing

In my application I needed to search through many varchar columns from differents tables.
So I created a materialized view in which I concatenate those columns, since they exceed the 4000 characters I merged them concatenating the columns with the TO_CLOBS(column1) || TO_CLOB(column)... || TO_CLOB(columnN).
The query is complex, so the refresh is complete on demand for the view. We refresh it every 2 minutes.
The CONTEXT index is created with the sync on commit parameter.
The index then is synchronized every two minutes.
But when we run the optimize index it does not defrag the index. So it keeps growing.
In ctx_user_indexes I see how optimize drops the docid count but tokens doesnt shrinks. But when I   use  the  REBUILD parameter in the index  optimization it works correctly (drops down number of rows in DR$TEXT_INDEX_IDX$I).
Any idea ?
Thanks, and sorry for my poor english.

A:

By adding a job to decrease the number of rows works.


Q:

SQL Server 2005: Update rows in a specified order (like ORDER BY)?

I want to update rows of a table in a specific order, like one would expect if including an ORDER BY clause, but SQL Server does not support the ORDER BY clause in UPDATE queries.
I have checked out this question which supplied a nice solution, but my query is a bit more complicated than the one specified there.
UPDATE TableA AS Parent
SET Parent.ColA = Parent.ColA + (SELECT TOP 1 Child.ColA
    FROM TableA AS Child
    WHERE Child.ParentColB = Parent.ColB
    ORDER BY Child.Priority)
ORDER BY Parent.Depth DESC;

So, what I'm hoping that you'll notice is that a single table (TableA) contains a hierarchy of rows, wherein one row can be the parent or child of any other row.  The rows need to be updated in order from the deepest child up to the root parent.  This is because TableA.ColA must contain an up-to-date concatenation of its own current value with the values of its children (I realize this query only concats with one child, but that is for the sake of simplicity - the purpose of the example in this question does not necessitate any more verbosity), therefore the query must update from the bottom up.
The solution suggested in the question I noted above is as follows:
UPDATE messages
SET status=10
WHERE ID in (SELECT TOP (10) Id
    FROM Table
    WHERE status=0
    ORDER BY priority DESC
);

The reason that I don't think I can use this solution is because I am referencing column values from the parent table inside my subquery (see WHERE Child.ParentColB = Parent.ColB), and I don't think two sibling subqueries would have access to each others' data.
So far I have only determined one way to merge that suggested solution with my current problem, and I don't think it works.
UPDATE TableA AS Parent
SET Parent.ColA = Parent.ColA + (SELECT TOP 1 Child.ColA
    FROM TableA AS Child
    WHERE Child.ParentColB = Parent.ColB
    ORDER BY Child.Priority)
WHERE Parent.Id IN (SELECT Id
    FROM TableA
    ORDER BY Parent.Depth DESC);

The WHERE..IN subquery will not actually return a subset of the rows, it will just return the full list of IDs in the order that I want.  However (I don't know for sure - please tell me if I'm wrong) I think that the WHERE..IN clause will not care about the order of IDs within the parentheses - it will just check the ID of the row it currently wants to update to see if it's in that list (which, they all are) in whatever order it is already trying to update... Which would just be a total waste of cycles, because it wouldn't change anything.
So, in conclusion, I have looked around and can't seem to figure out a way to update in a specified order (and included the reason I need to update in that order, because I am sure I would otherwise get the ever-so-useful "why?" answers) and I am now hitting up Stack Overflow to see if any of you gurus out there who know more about SQL than I do (which isn't saying much) know of an efficient way to do this.  It's particularly important that I only use a single query to complete this action.
A long question, but I wanted to cover my bases and give you guys as much info to feed off of as possible. :)
Any thoughts?

A:

UPDATE statements will be executed as a single query, not as a step by step result.
You need to either use a while loop/cursor (uhhgg) or maybe make use of a CTE expression view to achieve what you are trying, which gives you the recursice possibility.
Have a look at

Using Common Table Expressions
Recursive Queries Using Common Table
Expressions


Q:

How to formatting numbers by column in a table (tableGrob)

I have been trying to learn how to format tables for output in R. I'm now trying to take the table in example and format the numbers in the columns. I would like to have two digits in some columns and none in some columns like the rank column. Also, I would like to keep the row names as Year Month. How would one go about creating a table like this?
Note: Also the "3" in the column 'sepal.with' is printed as "3" not "3.0".
library(gtable)
library(grid)
library(gridExtra)
library(zoo)

iris <- as.matrix(iris[1:4, 1:3])
rownames(iris)<-as.yearmon(seq(as.Date("2000/1/1"), as.Date("2000/4/1"), by = "month"))
RankColumn<-seq(1, 4, by = 1)
iris<-cbind(iris, RankColumn)
iris<- round(as.matrix(iris), digits=2)

# a simple function to scale each column to the range [0, 1]
norm <- function(x) {
apply(x, 2, function(y){(y-min(y))/(max(y)-min(y))})
}

bluecol <- colorRamp(c("#3366EE", "#AABBFF", "#DDDDFF"))(norm(iris))
bluecol <- rgb(bluecol[, 1], bluecol[, 2], bluecol[, 3], max=255)

tt <- ttheme_default(core=list(bg_params=list(fill=bluecol)))

g <- tableGrob(iris, theme=tt)
g <- gtable_add_grob(g,
grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
t = 2, b = nrow(g), l = 1, r = ncol(g))
g <- gtable_add_grob(g,
grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
t = 1, l = 1, r = ncol(g))
grid.draw(g)

A:

Something like this may work to get you the format you're looking for.
library(gtable)
library(grid)
library(gridExtra)
library(zoo)

iris <- as.matrix(iris[1:4, 1:3])
rownames(iris)<-as.yearmon(seq(as.Date("2000/1/1"), as.Date("2000/4/1"), by = "month"))
RankColumn<-seq(1, 4, by = 1)
iris<-cbind(iris, RankColumn)

# Create the matrix
iris<- as.matrix(iris)

# a simple function to scale each column to the range [0, 1]
norm <- function(x) {
  apply(x, 2, function(y){(y-min(y))/(max(y)-min(y))})
}

# function to format columns
format.column <- function(matrix, colnum, rounding, decimals){
  formatted <- format(round(as.numeric(matrix[,colnum]), digits = rounding),nsmall = decimals)
  return(formatted)
}

bluecol <- colorRamp(c("#3366EE", "#AABBFF", "#DDDDFF"))(norm(iris))
bluecol <- rgb(bluecol[, 1], bluecol[, 2], bluecol[, 3], max=255)

tt <- ttheme_default(core=list(bg_params=list(fill=bluecol)))

# Set formatting for individual columns
# Adjust these or add additional columns to format as necessary
iris[,1] <- format.column(matrix = iris, colnum = 1, rounding = 2, decimals = 2)
iris[,2] <- format.column(matrix = iris, colnum = 2, rounding = 2, decimals = 1)

g <- tableGrob(iris, theme=tt)
g <- gtable_add_grob(g,
                     grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
                     t = 2, b = nrow(g), l = 1, r = ncol(g))
g <- gtable_add_grob(g,
                     grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
                     t = 1, l = 1, r = ncol(g))
grid.draw(g)

A:

While functional and flexible, I found Matt's format function a bit over complicated. A little sprintf magic should suffice. Also, converting the yearmon objects to character will keep the format.
library(gtable)
library(grid)
library(gridExtra)
library(zoo)

data(iris)
iris <- iris[1:4, 1:3]
rownames(iris) <- as.character(as.yearmon(
  seq(as.Date("2000/1/1"), as.Date("2000/4/1"), by = "month")))
iris$RankColumn <- 1:nrow(iris)

# a simple function to scale each row or column to the range [0, 1]
# will convert characters to numerics if in a sensible format
norm <- function(x, mar=2) {
    rnames <- rownames(x)
    x <- apply(x, 2, as.numeric)
    x <- apply(x, mar, function(y){(y-min(y))/(max(y)-min(y))})
    rownames(x) <- rnames
    x
}

# function to pad with zero
# by default does not pad integers
zeropad <- function(x, nz=1, exc.int=TRUE) {
    if (is.integer(x) & exc.int) {
        x
    } else {
        sprintf(paste0("%.", nz, "f"), x)
    }
}

bluecol <- colorRamp(c("#3366EE", "#AABBFF", "#DDDDFF"))(norm(iris))
bluecol <- rgb(bluecol[, 1], bluecol[, 2], bluecol[, 3], max=255)

tt <- ttheme_default(core=list(bg_params=list(fill=bluecol)))

# convert floats to zero-padded characters
iris[1:ncol(iris)] <- sapply(iris, zeropad, 2)

g <- tableGrob(iris, theme=tt)
g <- gtable_add_grob(g,
                     grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
                     t = 2, b = nrow(g), l = 1, r = ncol(g))
g <- gtable_add_grob(g,
                     grobs = rectGrob(gp = gpar(fill = NA, lwd = 2)),
                     t = 1, l = 1, r = ncol(g))
plot.new()
grid.draw(g)

(edited to work exclusively with data frames. norm and zeropad made a bit 'smarter')


Q:

Typescript Backbone View Events do not fire

I'm trying to make a simple view to test with backbone. I've started with events, but no one fires. Why ?
I've made already other things with backbone like routing etc. without problems. Thanks for your time.
My backbone definitions are from -> this source <-
module Views {
export class MenuView extends Backbone.View {
    constructor(viewOptions?: Backbone.ViewOptions) {

        super(viewOptions);
    }

    el = document.body;
    events = {
        "click #Btn-Start": "navigate",
        "click #Btn-Software": "navigate",
        "click #Btn-Anderes": "navigate",
        "click #Btn-Impressum": "navigate"
    };

    initialize() {
        console.log("initialize"); // fire
    }

    render() {
        console.log("render"); // not fire
    }

    navigate() {
        console.log("navigate"); // not fire
    }
}

}

EDIT: Tried routes with the route(name: string, callback: function) and the routes as object.
It seems to work with a function reference but not as string in the routes object. Maybe there is a way to declare it in the view like these.

A:

Use the setElement function inside the ctor instead of el object.


Q:

Why is XCode archive acting different than XCode build/run on iPhone

I have an app for the iPhone developed on XCode 4.  It works correctly in the following environments:

iPhone Simulator (iOS version 5)
iOS 5 device (executed from Archive)
iOS 5 device (executed from XCode build)
iOS 4 device (execute from XCode build)
iOS 3 device (executed from XCode build)

However, when I put the archive that works in iOS 5 on a iOS 3 or 4 device it acts funny.  The exact same code works fine when run from XCode on the same device though.
When I say it acts funny, it is animating a sliding UIView in the wrong axis. I do perform a rotation transformation on the UIView before I animate it though.  But again, it works fine when run directly from XCode, even on iOS 3 and 4 devices.  It is only acting up in the archive and only for iOS 3 and 4.  The archive works fine in iOS 5.
The rotation is done by a static call in a helper class:
+ (UIImage*)rotateImage:(UIImage *)image {
CGRect             bnds = CGRectZero;
UIImage*           copy = nil;
CGContextRef       ctxt = nil;
CGImageRef         imag = image.CGImage;
CGRect             rect = CGRectZero;
CGAffineTransform  tran = CGAffineTransformIdentity;

rect.size.width  = CGImageGetWidth(imag);
rect.size.height = CGImageGetHeight(imag);

bnds = rect;

bnds = swapWidthAndHeight(bnds);
tran = CGAffineTransformMakeTranslation(rect.size.height, 0.0);
tran = CGAffineTransformRotate(tran, M_PI / 2.0);

UIGraphicsBeginImageContext(bnds.size);
ctxt = UIGraphicsGetCurrentContext();

CGContextScaleCTM(ctxt, -1.0, 1.0);
CGContextTranslateCTM(ctxt, -rect.size.height, 0.0);

CGContextConcatCTM(ctxt, tran);
CGContextDrawImage(UIGraphicsGetCurrentContext(), rect, imag);

copy = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

return copy;
}

The animation is done by:
// The first image should fall from top.
CGRect rect = boardView.frame;
rect.origin = CGPointMake(VIEW_IMAGE_X_POS, 0);
boardView.frame = rect;
[myView addSubview:boardView];

// The starting image comes down.  Then passes control to the next animation routine for the clones.
[UIView beginAnimations:@"addStartingImage" context:boardView];
[UIView setAnimationDuration:1.2];
[UIView setAnimationDelegate:self];
[UIView setAnimationDidStopSelector:@selector(startingImageDidStop:finished:context:)];

// Add the new image
rect = boardView.frame;
rect.origin = CGPointMake(VIEW_IMAGE_X_POS, myView.contentSize.height - 108);
boardView.frame = rect;

// End the animation
[UIView commitAnimations];

Everything else runs fine.  Any thoughts?

A:

Try to turn off compiler optimizations.
Something is going wrong with UI on old iOS 3.x and 4.x ARMv6 devices when compiling a release build. I have no idea why, but turning off compiler optimizations will help.
Turning off Thumb may also help you with this issue, you can go to your build settings and mouse over the "Other C Flags" option. Click on the little plus button that appears to the right of this option and add a condition for the ARMv6 architecture. Do this again to create one for the ARMv7 architecture. Under the ARMv6 architecture, add the extra compiler flag of -mno-thumb.


Q:

Does someone destroyed by a God of Destruction leave a ghost?

If someone gets destroyed by a Hakai, does he/she leave a ghost or is that obliterated alongside him/her?

A:

I think this is already in its wikia page.

As Gods of Destruction, they possess the power to destroy almost anything with little effort, even intangible beings such as souls. People destroyed by Hakai do not go to Other World and simply cease to exist. However, in the manga, Beerus admits that Hakai does not work against people who are immortal.

Since the Other World is their equivalent to our afterlife where presumably, our ghost or spirit goes after death, then yes, Hakai can destroy someone including his/her ghost/spirit.
The technique however,

can be controlled by the user in moderation to not fully destroying the victim.

There are also a lot of variations of the said technique.


Q:

PDO INSERT do not register duplicated records inside mysql

Hello I have te following PDO insert into database function, how I can check if there is such a recored inside the database already to give error that the user is already registred with this information ? My table is organized like that
id | curso_id | user_id
1  | 12       | 43
2  | 5        | 56

so if a combination of curso_id = 12 and user_id = 43 is inside the database do not register second one of this kind, give error.
$userid = $_SESSION['userID'];
$cursoid = $_GET["id"];

try {

          $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD ); //our new PDO Object
          $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
          $stmt = $con->prepare( "Insert Into subscriptions ( curso_id, user_id ) Values ('$cursoid', '$userid')" );
          $stmt->execute();

       } catch (PDOException $e) {
              echo "I'm sorry there is a problem with your operation.."; $e->getMessage(); //catch and show the error
       }

$con = null;
header( 'Location: cursos.php' ) ;
}

Thanks for the help in advance

A:

Set a UNIQUE index : unique( curso_id, user_id ) constraint . And then you can use query something like this with ON DUPLICATE KEY UPDATE clause :
INSERT INTO subscriptions
    ( curso_id, user_id )
    VALUES
    ('12', '43')
    ON DUPLICATE KEY UPDATE user_id = user_id;

If the affected-rows is 1 , a new row is inserted .
If the affected-rows is 2 , an existing row is updated .
Based on the affected-rows value , you can choose to display appropriate message to the user .
...
INSERT ... ON DUPLICATE KEY UPDATE
REPLACE
Insert to table or update if exists (MySQL)


Q:

Demonstrate equality (cotangent)

Any hint to demonstrate that the function
$$
C(z) = \pi\cot \pi z
$$
satisfies
$$
2F(2z) = F(z) + F(z + \frac{1}{2}),
$$
please?
Thanks.

A:

$$
C(z) +C(z+{1/2})= \pi\Big(\cot (\pi z)+\cot( {\pi z+{\pi/2}})\Big) =\pi\Big(\cot (\pi z)-\tan( \pi z)\Big)
$$
$$ = \pi{\cos^2 (\pi z)-\sin^2( \pi z)\over \cos (\pi z)\sin( \pi z)} =\pi {2\cos(2\pi z)\over \sin(2\pi z)} = 2C(2z)
$$


Q:

Help w/ array of dictionaries in a tableview

This is kinda confusing so please bear with me.
I have an array (listOfStates) of dictionaries. Where listOfStates has this structure:
{stateName} - {stateCapital}
{Alabama} - {Montgomery}
{Alaska} - {Juneau}
{Arizona} - {Phoenix}
...
{West Virginia} - {Charleston}
{Wisconsin} - {Madison}
{Wyoming} - {Cheyenne}

This is the code used to obtain the 1st letter of each US State(stateName) in order to group them together alphabetically:
listOfStates = [[NSArray alloc] init];
stateIndex = [[NSMutableArray alloc] init];
NSMutableArray *tempArray = [[NSMutableArray alloc] init];

for (NSDictionary *row in listOfStates) {
    [tempArray addObject:[row valueForKey:@"stateName"]];

     for (int i=0; i<[tempArray count]-1; i++){
     char alphabet = [[tempArray objectAtIndex:i] characterAtIndex:0];
     NSString *uniChar = [NSString stringWithFormat:@"%C", alphabet];
         if (![stateIndex containsObject:uniChar]){
             [stateIndex addObject:uniChar];
         }
     }
}

That code works beautifully, however I'm having issues understanding how to populate a tableview cell with BOTH the @"stateName" and @"stateCapital"(as the subtitle) after I use NSPredicate to sort the array.
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

static NSString *CellIdentifier = @"Cell";

UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
    //---get the letter in the current section---
NSString *alphabet = [stateIndex objectAtIndex:[indexPath section]];

    //---get all states beginning with the letter---
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", alphabet];
NSArray *states = [[listOfStates valueForKey:@"stateName"] filteredArrayUsingPredicate:predicate];

        //---extract the relevant state from the states object---
    cell.textLabel.text = [states objectAtIndex:indexPath.row];
        //cell.textLabel.text = [[listOfStates objectAtIndex:indexPath.row] objectForKey:@"stateName"];
        //cell.detailTextLabel.text = [[listOfStates objectAtIndex:indexPath.row] objectForKey:@"stateCapital"];

return cell;
}

Any help is appreciated and I am more than willing to send the entire project, if you think it'll help you understand.
Thank you so much.

A:

Maybe change the data structure so you have one dictionary with state name as a key and state capital as a value. That way you can sort your keys and get the value using the keys, not indexes.


Q:

How to create dynamic route with parameter in a JavaScript function?

One of my route is defined like this:
society_mybundle_searchpage:
    pattern:  /search/cp/{cp}
    defaults: { _controller: SocietyMyBundle:Search:searchByCP }

So it needs one parameter: {cp}.
Now I'd like to create a form with an input widget. So my code is like that:
  <form onsubmit="return search();" action="#">
    {{ form_rest(form) }}
  </form>

(Nothing specific, I let symfony do all the work for me). Note that this form calls a JS function: search(). So here's my code in twig:
<script type="text/javascript">
<!--
function verif_formulaire(){
    /* some code to get the value of the cp */
    ...
    /* then: */
    ss="{{ path('society_mybundle_searchpage', {'cp': '+cp+'}) }}";
    return true;
}
-->
</script>

The output is:
function verif_formulaire(){
    ss="/symfony/web/app_dev.php/pizzas/search/cp/+tt+";
    return true;
}

This is not the output I need. I want the output to be exactly like that this:
function verif_formulaire(){
    ss="/symfony/web/app_dev.php/pizzas/search/cp/"+tt+"/";
    return true;
}

How shall I proceed?

A:

My solution was: implement a custom url_decode function in twig (very easy).
Then use the format() function.
Here's the result:
window.location ="{{ path('my_path', {'cp': "%s" }) | url_decode | format('"+monCP+"') | raw }}";

Explanation: path('my_path', {'cp': "AAAA" }) will generate an URL like '/mypath/cp/AAAA/' thus path('my_path', {'cp': "%s" }) will generate an URL like '/mypath/cp/%s/'
But the '%s' will be escaped. So I decode it through '| url_decode' :
path('my_path', {'cp': "%s" }) | url_decode

Will generate proper string '/mypath/cp/%s/'.
Then I use the format() function to pass a string.
Example: '"/mypath/cp/%s/" | format('OLIVIER')' will give '"/mypath/cp/OLIVIER/"'
So, here, I pass a specific string: '"+monCP+"' (watch carefully the quotes and double quotes).
So: '"/mypath/cp/%s/" | format('"+monCP+"')' will give '/mypath/cp/"+monCP+"/'
Last problem: this whole string is again escaped. This time, a classical "| raw" is enough.
Thus, to conclude, this:
var xx ="{{ path('my_path', {'cp': "%s" }) | url_decode | format('"+monCP+"') | raw }}";

Will result in full normal JavaScript code:
var xx ="/my-symfony-url/cp/"+monCP+"/";

This may look complex, but wow. No external JavaScript file needed. This is what I wanted. Just pure fast Symfony 2 php-generated cache. I propably could make this a Twig macro or something.


Q:

dynamic query filter with SQLalchemy operators

I have a list : scope_list = ['prd1 rls1', ' prd1 rls1 rls3 rls2']
I would like to create a filter based on scope_list that in SQL would look like :
(product=prd1 AND `release` in (rls1)) OR (product=prd1 AND release in (rls1 ,rls3, rls2))

Knowing that the number of values in scope_list varies and that I can't previously know it. This is why I would like to manage the filter dynamically from scope_list.
In SQL Alchemy I guess I should do something like this :
session.query(my_table).filter(or_(and_(my_table.product==%s,mytable.release.in_(%s))) for element.split() in scope_list)

I'm just starting to learn SQL Alchemy, any help would be much appreciated.

A:

Both or_ and and_ can take variable number of positional arguments, so if you build a list you can pass it in as position arguments with or_(*or_args).
# First I split each term in the scope list.
scope_list = [term.split() for term in scope_list]
# Then the query is built.
or_args = [and_(
    my_table.product == scope[0],
    my_table.release.in_(scope[1:])) for scope in scope_list]
results = session.query(my_table).filter(or_(*or_args)).all()


Q:

Objective-C Indexing

I'm currently trying to implement some kind of search system in a program of mine, and wanted to use an index, but I'm fairly new at Objective-C. The main idea is to have a 'search' command or text box and when I type a word, it'll show me all the items that include that word. All these 'items' will be listed in a .txt file (hopefully) in alphabetical order. Any help is appreciated.

A:

You need to read the .txt file into an NSSet or some other collection class and you can then search it using something like:
[words filterUsingPredicate:[NSPredicate predicateWithFormat:@"SELF contains[c] 'word'"]];

(See the Predicate Guide for details).


Q:

NSMenuItem action is not executing

I am creating a status bar on my app and the menus show up fine, however it does not seem to access the actions that I have set up for it.
I am adding the status bar through a C function:
void MyFunction(CefRefPtr<CefBrowser> browser) {
    MyMenuItem* item = [[MyMenuItem alloc] initWithTitle:@"Item 1" action:@selector(doAction:) keyEquivalent:@"")];
    [item setBrowser:browser];

    NSMenu *menu = [[NSMenu alloc] initWithTitle:@""];
    [menu setAutoenablesItems:NO];
    [menu addItem:item];

    NSStatusBar *statusBar = [NSStatusBar systemStatusBar];
    MSStatusItem *statusItem = [statusBar statusItemWithLength:NSBariableStatusItemLength];
    [statusItem retain];
    [statusItem setImage:imageObj];
    [statusItem setTitle:@"Status"];
    [statusItem setHilightMode:YES];
    [statusITem setMenu:menu];
}

Declaring the actions right above MyFunction():
@interfaceMyMenuItem : NSMenuItem {
    CefRefPtr<CefBrowser>_browser;
}

@property (nonatomic) CefRefPtr<CefBrowser> browser;
- (void)doAction:(id)sender;
@end

@implementation MyMenuItem
@synthesize browser = _browser;
- (void)doAction:(id)sender {
    NSLog(@"Doing action");
}
@end

Everything compiles just fine, So I think it might have something to do with creating the Items from a C function, but not properly setting up the interface.

A:

have you tried setting target of menuitem and implementing validateUserInterfaceItem?
MyMenuItem* item = [[MyMenuItem alloc] initWithTitle:@"Item 1" action:@selector(doAction:) keyEquivalent:@"")];
[item setTarget:self];

and
-(BOOL)validateUserInterfaceItem:(id<NSValidatedUserInterfaceItem>)anItem
{
    return ([anItem selector] == @selector(doAction:));
}