text:
Q: Some rows are collapsed in DataGrid, I am getting issue in KeyBoard navigation I am using DataGrid, run time i make visible collapse some rows.
Suppose my 4th row's visibility is collapse, and my focus is on 3rd row, when i try to move on 5th row with the help of Down-Arrow key, it is not working. Same way if my focus on 5th row and want to move on 3rd row with Up-Arrow key, it is also not working.
Now, what should i do?

A: This is actually a bug in .Net, there is a bug report here.
One workaround is to use Attached behavior to handle the up and down selection. The following example requires the IsSynchronizedWithCurrentItem to be set to true for the DataGrid.
Note! make sure you change the while condition to the appropriate way to determine if the item is collapsed.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Media;

namespace DataGridGroupingTest
{
    class DataGridKeyboardNavigationAttachedBehavior
    {
        public static readonly DependencyProperty
                KeyboardKey
                    = DependencyProperty.RegisterAttached(
                        "IsKeyboardNavigationEnabled",
                        typeof(bool),
                        typeof(DataGridKeyboardNavigationAttachedBehavior),
                        new PropertyMetadata(
                            false,
                            OnIsKeyboardNavigationEnabledChanged));

        public static bool GetIsKeyboardNavigationEnabled(DependencyObject depObj)
        {
            return (bool)depObj.GetValue(KeyboardKey);
        }

        public static void SetIsKeyboardNavigationEnabled(DependencyObject depObj, bool value)
        {
            depObj.SetValue(KeyboardKey, value);
        }

        private static void OnIsKeyboardNavigationEnabledChanged(DependencyObject depObj, DependencyPropertyChangedEventArgs e)
        {
            DataGrid dataGrid = depObj as DataGrid;
            if (dataGrid != null)
            {
                dataGrid.PreviewKeyDown += dataGrid_PreviewKeyDown;
                dataGrid.IsSynchronizedWithCurrentItem = true;
            }
        }

        static void dataGrid_PreviewKeyDown(object sender, System.Windows.Input.KeyEventArgs e)
        {
            DataGrid dataGrid = sender as DataGrid;
            if (dataGrid != null && dataGrid.CurrentCell != null)
            {
                if (e.Key == System.Windows.Input.Key.Down || e.Key == System.Windows.Input.Key.Up)
                {
                    ICollectionView view = CollectionViewSource.GetDefaultView(dataGrid.Items);

                    int loopCount = 0;
                    do
                    {
                        if (e.Key == System.Windows.Input.Key.Down)
                        {
                            view.MoveCurrentToNext();
                            if (view.IsCurrentAfterLast)
                            {
                                view.MoveCurrentToFirst();
                                loopCount++;
                            }
                        }
                        if (e.Key == System.Windows.Input.Key.Up)
                        {
                            view.MoveCurrentToPrevious();
                            if (view.IsCurrentBeforeFirst)
                            {
                                view.MoveCurrentToLast();
                                loopCount++;
                            }
                        }
                    } while (((Person)view.CurrentItem).Boss != null && !((Person)view.CurrentItem).Boss.IsExpanded && loopCount < 2);

                    // We have to move the cell selection aswell.
                    dataGrid.CurrentCell = new DataGridCellInfo(view.CurrentItem, dataGrid.CurrentCell.Column);

                    e.Handled = true;
                    return;
                }
            }
        }
    }
}


text:
Q: Spring beans with runtime initialization parameters I have a class which needs

*

*Dependency injection for various beans it uses

*Runtime parameters for initialization

The class would look something similar to this
public class Validator {

    @Autowired
    private ServiceA serviceA;

    @Autowired
    private ServiceB serviceB;

    private String s;

    private ClassA a;
    private ClassB b;

    public void initialize(String s, ClassA a, ClassB b) {
        this.s = s;
        this.a = a;
        this.b = b;
    }

    public void performTaskA() {
        //use serviceA, serviceB, s, a and b
    }

    public void performTaskB() {
        //use serviceA, serviceB, s, a and b
    }

    public void performTaskC() {
        //use serviceA, serviceB, s, a and b
    }

}

What are various options through which I can define the above class as spring bean (to take the advantage of dependency injection) and also make sure that the caller calls initialize() before calling any performTask*() methods?
Note - I am aware of Object getBean(String name, Object... args) throws BeansException; but it doesn't look good since we would loose type safety. Any other suggestions?
Update -
The solution mentioned here with lookup method injection is a nice option. Until it is implemented in spring, what's your opinion on the below alternative of using inner classes
public class MyService {
    private ServiceA serviceA;
    private ServiceB serviceB;

    public class DataClass {
        private Integer counter;

        public DataClass(Integer counter) {
            this.counter = counter;
        }

        public Integer performActionAndGetCount() {
            serviceB.performAction();
            return this.counter++;
        }
    }
}

//client module
MyService service = beanFactory.getBean("myService");
MyService.DataClass dataClass = service.new DataClass(1);

Any drawbacks of this approach?

A: Use component,service or repository annotation to annotate your class. This would enable your class to be considered as a spring bean and you can then use dependency injection and runtime initialization.
Make sure in your {dispatcher-servlet}.xml(replace the name in {} to the name you have given your dispatcher servlet in web.xml} file you have written this line

A: This can be accomplished using a combination of scope="prototype" and a <lookup-method>.
First, define the class you want to parameterize as a bean with scope="prototype". This will cause the context to generate a new instance every time the bean is requested.
<bean class="com.example.Validator" scope="prototype"/>

Then, define a "factory class" that will wrap the generation and initialization of new objects.
<bean class="com.example.ValidatorFactory">
  <lookup-method name="newValidator"/>
</bean>

This class would look like this:
public class ValidatorFactory {
    public Validator createValidator(String str, Class<?> classA, Class<?> classB) {
        Validator v = newValidator();
        v.initialize(str, classA, classB);
        return v;
    }

    protected void newValidator() {
        // Spring will implement this via AOP
    }
}

This forces clients to go through a routine that will call initialize() while still loading beans via the Spring context.

A: I am not so clear about your requirement. But I think @PostConstruct annotated method can come to your rescue. You can find more details about @PostConstruct annotation here.
Hope this helps you. Cheers.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Creating a layer from svg image using openlayers 3 So I'm trying to take big svg file and use it as a layer on open layers 3 map. I only want to display the svg, without any map underneath it. Trying to get an answer produced some info about using icon marker for that, but I couldn't make it to work.
Does anyone know how to simply show an svg file as a layer ?

A: By default objects in a Layer need to be geolocated so that the renderer knows where to draw them. A hack I found involves using D3 to map svg features into vectors with a custom projection function for the renderer. It also handles listening for move/pan. see: http://bl.ocks.org/pbogden/6283017
some code from the solution reproduced here
d3.json("us-states.json", function(err, collection) {
    var bounds = d3.geo.bounds(collection),
        path = d3.geo.path().projection(project), // create a d3.geo.path that converts GeoJSON to SVG
        vector = new OpenLayers.Layer.Vector( "states" ); // create a vector layer

    // Use D3 to add the states after the vector layer has been added to the map
    vector.afterAdd = function() {
        var div = d3.select("#"+vector.div.id);
        div.selectAll("svg").remove();  // Prepare OpenLayers vector div to be the container for D3

        var svg = div.append("svg"),
            g = svg.append("g");

        var states = g.selectAll("path")
                .data(collection.features)
              .enter().append("path");

        reset();

        // Reposition the SVG to cover the features
        function reset() {
            var bottomLeft = project(bounds[0]),
                topRight = project(bounds[1]);

            svg .attr("width", topRight[0] - bottomLeft[0])
                .attr("height",bottomLeft[1] - topRight[1])
                .style("margin-left", bottomLeft[0] + "px")
                .style("margin-top", topRight[1] + "px");

            g   .attr("transform", "translate(" + -bottomLeft[0] + "," + -topRight[1] + ")")

            states.attr("d", path);
        };
        map.events.register("moveend", map, reset);
    };
    // Add the vector layer to the map
    map.addLayer(vector);

   // Use OpenLayers to implement a custom D3 geographic projection.
   // Converts lon/lat to viewport coordinates (D3 uses 2-element arrays).
   function project(x) {
       var point = map.getViewPortPxFromLonLat( new OpenLayers.LonLat(x[0], x[1])
                                                    .transform("EPSG:4326", "EPSG:900913")
       );
       return [ point.x, point.y ];
   }
});

A: I just answered this in another similiar question. See that answer for a runnable example.
The gist of it: just include the svg file as the url for ol.source.ImageStatic.


text:
Q: Get all rows where string starts with column value Using SQLAlchemy, it's easy to get all the rows where a given column starts with a given string. But how do I flip it around so that I get rows where the beginning of the string matches the column?
I.e, if the string is "stackoverflow" I'd want it to match a row with the value "stack"
If necessary, I can store regex in the column instead of just the string, but I don't know how to invert a regex comparison either.

A: Here is SQL solution implemented as sqlalchemy expression
class Foo(Base):
    __tablename__="foo_tablename"
    bar = Column(String(80))

bar = 'stackoverflow'
session.query(Foo).filter(literal('stackoverflow').like(func.concat(Foo.bar, '%')))

SQLAlchey log shows generated query:
>>INFO sqlalchemy.engine.base.Engine SELECT bar FROM foo_tablename WHERE :param1 LIKE CONCAT(foo_tablename.bar_column,'%')
>>INFO sqlalchemy.engine.base.Engine {'param1': 'stack'}

Please note:

*

*such type of sql query prevents database from using column index - so it is potential performance bottleneck.

So if I would need to add such functionality into production I would consider using full text search feature provided by database. SQLAlchemy doesn't provide support for full text search as it is database specific functionality. See example of combining PostgreSQL full text search with SQLAlchemy.
Updated
User Audrius Kažukauskas suggested how to get rid of raw sql. So this removes limitations of using literal SQL.

A: Maybe there's a better way, but this should work:
bar = 'stackoverflow'
session.query(Foo).filter(
    Foo.data.in_([bar[:i] for i in xrange(5, len(bar) + 1)])
)


text:
Q: Get request from android app to wamp does not working I am working on an android app, but I don't have internet conection so I am using WAMP local server.
If I want to show web page I used loadURL(http://10.0.2.2/wamp/www/....) and page shows, WebView working.
But when I tried sending some request to this page, that did not work, I want to show source code, this page didn't work, I used code available on net for the same, but that did not work too.
I already have added Internet permission.
I don't have experience with WAMP.
Any help is appreciated!!
And sorry , my English is not good:)

A: May be an error in your url.

Try http://10.0.2.2/.... instead of http://10.0.2.2/wamp/www/....

Also make sure you set INTERNET PERMISSION.


text:
Q: Error when importing pyautogui on macOS 10.13 and Python 3.8 I'm working in a conda environment with Python 3.8.0 created using conda create --name atbs python=3.8.0. I have installed pyobjc, pyobc-core and pyautogui using pip install pyautogui. The installation looks successful, and I can run import objc with no errors, but when I run import pyautogui I get the following error message. Can anyone help me figure out what is going on?
Traceback (most recent call last):
  File "/opt/anaconda3/envs/atbs/lib/python3.8/site-packages/pyautogui/_pyautogui_osx.py", line 5, in <module>
    import Quartz
  File "/opt/anaconda3/envs/atbs/lib/python3.8/site-packages/Quartz/__init__.py", line 6, in <module>
    import AppKit
  File "/opt/anaconda3/envs/atbs/lib/python3.8/site-packages/AppKit/__init__.py", line 10, in <module>
    import Foundation
  File "/opt/anaconda3/envs/atbs/lib/python3.8/site-packages/Foundation/__init__.py", line 9, in <module>
    import CoreFoundation
  File "/opt/anaconda3/envs/atbs/lib/python3.8/site-packages/CoreFoundation/__init__.py", line 16, in <module>
    objc.pathForFramework("/System/Library/Frameworks/CoreFoundation.framework"),
  File "/opt/anaconda3/envs/atbs/lib/python3.8/site-packages/objc/_dyld.py", line 148, in pathForFramework
    fpath, name, version = infoForFramework(dyld_find(path))
  File "/opt/anaconda3/envs/atbs/lib/python3.8/site-packages/objc/_dyld.py", line 142, in dyld_find
    return dyld_framework(filename, framework_name, version)
  File "/opt/anaconda3/envs/atbs/lib/python3.8/site-packages/objc/_dyld.py", line 101, in dyld_framework
    if _dyld_shared_cache_contains_path(f):
NotImplementedError: _dyld_shared_cache_contains_path not available

A: I got the similar issue and found the workaround from
https://github.com/hbldh/bleak/issues/372. It works for me too.
In your file "/opt/anaconda3/envs/atbs/lib/python3.8/site-packages/objc/_dyld.py", replace the following lines
try:
    from objc._objc import _dyld_shared_cache_contains_path
except ImportError:
    _dyld_shared_cache_contains_path = None

with
_dyld_shared_cache_contains_path = None


text:
Q: MySQL access denied via PHP only I have access to shared university research server that I want to host a php/mysql site on.  I've compiled and run the mysql server and can connect to it fine using the 'mysql -u  -h localhost -p', however when I use the exact same credentials and parameters through a PHP script, I always get 'access denied for user@localhost'.  I did some more digging and found that even when my instance of the server isn't running, I get the same error message, which suggests there is an issue with the fact that this server is shared and running possibly multiple instances of mysqld. I've tried altering the port and socket and connecting to them explicitly through the script, but still have no had any luck.  My PHP code works fine locally, so there's nothing syntactically wrong as far as I can tell.
Has anyone experienced a similar problem or can perhaps point me in the direction of some resources?  Thanks in advance for your time!

A: I've had this before. It turned out to be a problem with localhost not resolving properly or reliably. See what happens if you replace that with 127.0.0.1

A: I just had a similar issue but I'm connecting to MySQL on a different machine.  I solved my issue by passing a hostname (I created in /etc/hosts) to mysqli connect instead of an IP address.  Not sure why that resolved it, but it did.


text:
Q: Output returned data in current div I have an ajax form where I output data returned via PHP script using this line of code:
jQuery(".commentfeedback").html(data);

That outputs it to div with class commentfeedback. Instead, I want to simply output it in the current div, so I tried:
jQuery(this).html(data);

But it did not work. What am I doing wrong?
Complete JS code:
jQuery('.commenttopicform').submit(ajaxSubmit);

function ajaxSubmit(){

var commenttopicform = jQuery(this).serialize();

jQuery.ajax({
    type:"POST",
    url: "/testrmv/wp-admin/admin-ajax.php",
    data: commenttopicform,
    success:function(data){
        jQuery(".commentfeedback").html(data); // empty div to show returned data
    }
});

return false;
}

HTML:
         <form action="" method="post" class="commenttopicform" />
             <input type="hidden" name="postid" value="<?php echo $t_id; ?>" />
             <input type="hidden" name="action" value="comment_topic" />

                  <textarea name="comment" maxlength="2000" placeholder="Please add a note here..."></textarea>

                  <input type="submit" value="Add Note" class="button-primary newcomsub" name="send" />

 </form>

A: You can use the context: option to pass along the this value to the callback.
jQuery.ajax({
    type:"POST",
    url: "/testrmv/wp-admin/admin-ajax.php",
    data: commenttopicform,
    context: this,
    success:function(data){
        jQuery(this).nextAll('.commentfeedback').eq(0).html(data); // empty div to show returned data

    }
});


text:
Q: Create list of list of numbers. If sorting is wrong a new sublist should be created a) Input is list of numbers
i/p = > [2,5,1,4,7,3,1,2,3]

b) output should be sorted sublists
o/p = > [[2,5],[1,4,7],[3],[1,2,3]]

A: Algorithm
input = [2,5,1,4,7,3,1,2,3]

output = [[]]
for idx,val in enumerate(input):
    if idx > 0 and input[idx-1] > input[idx]:
        output.append([val])
    else:
        output[-1].append(val)

print output

Output is
[[2, 5], [1, 4, 7], [3], [1, 2, 3]]

Explanation of the algorithm in words:
Create an output list with an empty sublist. Enumerate over the input list. If the previous element (if one exists) is not bigger than the actual element add the element to the last sublist of the output. If it's bigger create a new sublist in output and add it to this new sublist.

A: Another Solution:
def sortedsublist():
'''create sorted sublist from the given list'''
    inputl = []
    sortedl = []
    subl = []
    inputl = [7,8,9,2,3,1,2,3,1,2,1]
    for i in range(len(inputl)):
    try:
    if inputl[i] <= inputl[i+1]:
        subl.append(inputl[i])
    else:
        subl.append(inputl[i])
        sortedl.append(subl)
        subl= []
     except IndexError:
        subl.append(inputl[i])
        sortedl.append(subl)
        subl = []
    print sortedl
    return
if __name__="main":
    sortedsublist()


text:
Q: What is an elegant way to track the size of a set of objects without a single authoritative collection to reference? Update: Please read this question in the context of design principles, elegance, expression of intent, and especially the "signals" sent to other programmers by design choices.
I have two "views" of a set of objects. One is a dictionary/map indexing the objects by a string value. The other is a dictionary/map indexing the objects by an ordinal (ordering integer).  There is no "master" collection of the objects by themselves that can serve as the authoritative source for the number of objects, but the two dictionaries should always both contain references to all the objects.
When a new item is added to the set a reference is added to both dictionaries, and then some processing needs to be done which is affected by the new total number of objects.
What should I use as the authoritative source to reference for the current size of the set of objects?  It seems that all my options are flawed in one dimension or another.  I can just consistently reference one of the dictionaries, but that would codify an implication of that dictionary's superiority over the other.  I could add a 3rd collection, a simple list of the objects to serve as the authoritative list, but that increases redundancy.  Storing a running count seems simplest, but also increases redundancy and is more brittle than referencing a collection's self-tracked count on the fly.
Is there another option that will allow me to avoid choosing the lesser evil, or will I have to accept a compromise on elegance?

A: I'd suggest encapsulation: create a class that hides the "management" details (such as the   current count) and use it to expose immutable "views" of the two collections.
Clients will ask the "manglement"  object for an appropriate reference to one of the collections.
Clients adding a "term" (for lack of a better word) to the collections will do so through the "manglement" object.
This way your assumptions and implementation choices are "hidden" from clients of the service and you can document that the choice of collection for size/count was arbitrary. Future maintainers can change how the count is managed without breaking clients.
BTW, yes, I meant "manglement" - my favorite malapropism for management (in any context!)

A: I would create a class that has (at least) two collections.

*

*A version of the collection that is
sorted by string

*A version of the
    collection that is sorted by ordinal

*(Optional) A master collection

The class would handle the nitty gritty management:

*

*The syncing of the contents for the collections

*Standard collection actions (e.g. Allow users get the size, Add or retrieve items)

*Let users get by string or ordinal

That way you can use the same collection wherever you need either behavior, but still abstract away the "indexing" behavior you are going for.
The separate class gives you a single interface with which to explain your intent regarding how this class is to be used.

A: If both dictionaries contain references to every object, the count should be the same for both of them, correct? If so, just pick one and be consistent.

A: I don't think it is a big deal at all.  Just reference the sets in the same order each time
you need to get access to them.
If you really are concerned about it you could encapsulate the collections with a wrapper that exposes the public interfaces - like

*

*Add(item)

*Count()

This way it will always be consistent and atomic - or at least you could implement it that way.
But, I don't think it is a big deal.


text:
Q: Cache location with gitlab-runner and docker executor on Windows? Where are the zips of the job caches when running gitlab-runner on Windows with docker executor ?

A: Here is what I found on the computer executing gitlab-runner, which has a more or less default configuration:
C:\ProgramData\docker\volumes\<runner-id>\_data\<path\to\repo>\<cache key>-N\cache.zip

With:

*

*<cache key> the value of the cache key provided from .gitlab-ci.yml.

*N an integer close to 1, possibly due to parallel builds (?). I think that sometimes the directory name is simply <cache key>.


text:
Q: Quick way to find eigenvalues of anti-diagonal matrix If $A \in M_n(\mathbb{R})$ is an anti-diagonal $n \times n$ matrix, is there a quick way to find its eigenvalues in a way similar to finding the eigenvalues of a diagonal matrix? The standard way for finding the eigenvalues for any $n \times n$ is usually straightforward, but may sometimes lead to painstaking computational time. Just wondering if there was a quicker way in doing so for any anti-diagonal matrix without having to resort to the standard method of finding the determinant of $A - \lambda I$, where $I$ is the $n \times n$ identity matrix, and setting it equal to $0$ and solving for $\lambda$.

A: Suppose $A$ has even size, say, $2m \times 2m$. Then by reordering the basis we can produce a block diagonal matrix with the same eigenvalues as the original.
$$
\left(
\begin{array}{cc}
0      & a_{1,2m} \\
a_{2m,1} & 0   \\
\end{array}
\right)
\oplus
\cdots
\oplus
\left(
\begin{array}{cc}
0      & a_{m,m+1} \\
a_{m+1,m} & 0   \\
\end{array}
\right).
$$
The characteristic polynomial is
$$\det(\lambda I - A) = \det\left(\lambda I - \left(
\begin{array}{cc}
0      & a_{1,2m} \\
a_{2m,1} & 0   \\
\end{array}
\right)\right)
\cdots  \det\left(\lambda I - \left(
\begin{array}{cc}
0      & a_{m,m+1} \\
a_{m+1,m} & 0   \\
\end{array}
\right)\right)
= (\lambda^2 - a_{1,2m}a_{2m,1})\cdots(\lambda^2 - a_{m,m+1}a_{m+1,m}) .
$$
and so the eigenvalues are the roots of these factor polynomials, namely both square roots of each of the products $a_{1,2m}a_{2m,1}, \ldots, a_{m,m+1} a_{m+1,m}$.
If $A$ has odd size, say, $(2m + 1) \times (2m + 1)$ when we change basis we can send the middle ($(m+1)$st) element to the end, in which case the characteristic polynomial takes a similar form as in the even case (with indices $> m$ shifted up one), but with an additional factor of $\lambda - a_{m+1, m+1}$, so the additional eigenvalue in this case is just the middle entry of the matrix.

A: One can actually find the eigenvalues of $A$ directly without reordering the indices (note: I'm not saying that this is the quickest or preferred way to find those eigenvalues -- this is not). The eigenvalues of $A$ are just the roots of the characteristic polynomial $\det(xI-A)$. When $n$ is odd, let $m=\frac{n+1}2$ and write
$$
A=\left[\begin{array}{c|c|c}0&0&A_{13}\\ \hline 0&a_{mm}&0\\ \hline A_{31}&0&0\end{array}\right]\tag{$\ast$}
$$
where $A_{13}$ and $A_{31}$ are two anti diagonal matrices of size $m-1$. By Laplace expansion along the middle row, we get $\det(xI-A)=(x-a_{mm})\det\left[\begin{array}{c|c}xI&-A_{13}\\ \hline -A_{31}&xI\end{array}\right]$. Using the formula $\det\pmatrix{X&Y\\ Z&W}=\det(XW-YZ)$ when $Z$ and $W$ commute, we further obtain
\begin{align*}
\det(xI-A)&=(x-a_{mm})\det(x^2I-A_{13}A_{31})\\
&= (x-a_{mm})(x^2-a_{1n}a_{n1})(x^2-a_{2,n-1}a_{n-1,2})\cdots\left(x^2-a_{m-1,m+1}a_{m+1,m-1}\right)
\end{align*}
and finding its roots is a trivial matter.
When $n$ is even, the central element in $(\ast)$ vanishes and we may skip the Laplace expansion step. The characteristic polynomial of $A$ is then
$$
(x^2-a_{1n}a_{n1})(x^2-a_{2,n-1}a_{n-1,2})\cdots\left(x^2-a_{\frac n2,\frac n2+1}a_{\frac n2+1,\frac n2}\right).
$$

A: For ease of formatting and explanation, I'll be doing everything for the $5 \times 5$ example.  However, the same trick works for any $n \times n$ antisymmetric matrix (though slightly differently for even $n$).
Suppose
$$
A =
\begin{pmatrix}0&0&0&0&a_{15}\\0&0&0&a_{24}&0\\0&0&a_{33}&0&0\\0&a_{42}&0&0&0\\a_{51}&0&0&0&0 \end{pmatrix}
$$
Here's a neat trick: we note that
$$
A^2 = \pmatrix{
a_{15}a_{51}&&&&\\
&a_{24}a_{42}&&&\\
&&(a_{33})^2&&\\
&&&a_{24}a_{42}&\\
&&&&a_{15}a_{51}\\
}
$$
So, the eigenvalues of $A^2$ are precisely $\{a_{15}a_{51}, a_{24}a_{42}, (a_{33})^2\}$.
Now, note that if $\lambda$ is an eigenvalue of $A$, then $\lambda^2$ must be an eigenvalue of $A^2$.  This gives you six candidates for the eigenvalues of $A$.

In fact, with more thorough analysis, we can guarantee that the eigenvalues will be precisely $\lambda = \pm \sqrt{a_{i,(n+1-i)}a_{(n+1-i),i}}$ for $i = 1,\dots,\lfloor n/2\rfloor$ and, for odd $n$, $\lambda = a_{(n+1)/2,(n+1)/2}$.
Proof that this is the case: Let $e_1,\dots,e_n$ denote the standard basis vectors.  Let $S_{ij}$ denote the span of the vectors $e_i$ and $e_j$.
Note that $A$ is invariant over $S_{i(n-i)}$ for $i = 1,\dots,\lfloor n/2\rfloor$.  We may then consider the restriction $A_{i(n-i)}: S_{i(n-i)} \to S_{i(n-i)}$, which can be represented by the matrix
$$
\pmatrix{0 & a_{i(n-i)}\\a_{(n-i)i} & 0}
$$
It suffices to find the eigenvalues of this transformation.
For the case of an odd $n$, it is sufficient to note that $a_{(n+1)/2,(n+1)/2}$ lies on the diagonal with zeros in its row and column.

Another explanation: denote the matrix
$S = \pmatrix{e_1 & e_{n} & e_2 & e_{n-1} & \cdots}$
Noting that $S$ is orthogonal (i.e. $S^{-1} = S^{T}$), we find that
$$
SAS^{-1} =
\pmatrix{
0&a_{1,n}\\
a_{n,1}&0\\
&&0&a_{2,n-1}\\
&&a_{n-1,2}&0\\
&&&&\ddots
}
$$
This matrix is similar, and therefore has the same eigenvalues.  However, it is also block diagonal.


text:
Q: How to convert existing Angular 2 project to Meteor project I have finished creating an angular 2/ node.js project and I want to use Meteor so that I can create a mobile version. Can I simply create a new meteor project, copy and past all of my angular 2 code to the meteor project and be good to go? I have no idea what to do, I've searched everywhere.
Structure of my MEAN stack app:
server/
    node_modules/
    models/
    config/
    server.js
client/
    angular-src/
        node_modules/
        src/
            app/
                  ...
        tsconfig.json
        tslint.json
        package.json
        karma.conf.js

Do I have to completely start over to make a meteor app?
Thanks


text:
Q: Append category to column if date range is between start and end date I'm sure this is simple, but I can't wrap my head around it. Essentially I have two dataframes, a large df that contains process data every six hours and a smaller df that contains a condition number, a start date and an end date. I need to fill the condition column of the large dataframe with the condition number that corresponds to the date range, or else leave it blank if the dates do not fall between any date range in the small df. So my two frames would look like this:
Large df
Date            P1  P2
7/1/2019 11:00  102 240
7/1/2019 17:00  102 247
7/1/2019 23:00  100 219
7/2/2019 5:00   107 213
7/2/2019 11:00  100 226
7/2/2019 17:00  104 239
7/2/2019 23:00  110 240
7/3/2019 5:00   110 232
7/3/2019 11:00  102 215
7/3/2019 17:00  103 219
7/3/2019 23:00  107 243
7/4/2019 5:00   107 246
7/4/2019 11:00  103 219
7/4/2019 17:00  105 220
7/4/2019 23:00  107 220
7/5/2019 5:00   107 227
7/5/2019 11:00  108 208
7/5/2019 17:00  110 248
7/5/2019 23:00  107 235

Small df
Condition   Start Time  End Time
A        7/1/2019 11:00 7/2/2019 5:00
B        7/3/2019 5:00  7/3/2019 23:00
C        7/4/2019 23:00 7/5/2019 17:00

And I need the result to look like this:
Date            P1  P2  Cond
7/1/2019 11:00  102 240 A
7/1/2019 17:00  102 247 A
7/1/2019 23:00  100 219 A
7/2/2019 5:00   107 213 A
7/2/2019 11:00  100 226
7/2/2019 17:00  104 239
7/2/2019 23:00  110 240
7/3/2019 5:00   110 232 B
7/3/2019 11:00  102 215 B
7/3/2019 17:00  103 219 B
7/3/2019 23:00  107 243 B
7/4/2019 5:00   107 246
7/4/2019 11:00  103 219
7/4/2019 17:00  105 220
7/4/2019 23:00  107 220 C
7/5/2019 5:00   107 227 C
7/5/2019 11:00  108 208 C
7/5/2019 17:00  110 248 C
7/5/2019 23:00  107 235

A: You need:
for i, row in sdf.iterrows():
    df.loc[df['Date'].between(row['Start Time'], row['End Time']), 'Cond'] = row['Condition']

Output:
                Date    P1  P2  Cond
0   2019-07-01 11:00:00 102 240 A
1   2019-07-01 17:00:00 102 247 A
2   2019-07-01 23:00:00 100 219 A
3   2019-07-02 05:00:00 107 213 A
4   2019-07-02 11:00:00 100 226 NaN
5   2019-07-02 17:00:00 104 239 NaN
6   2019-07-02 23:00:00 110 240 NaN
7   2019-07-03 05:00:00 110 232 B
8   2019-07-03 11:00:00 102 215 B
9   2019-07-03 17:00:00 103 219 B
10  2019-07-03 23:00:00 107 243 B
11  2019-07-04 05:00:00 107 246 NaN
12  2019-07-04 11:00:00 103 219 NaN
13  2019-07-04 17:00:00 105 220 NaN
14  2019-07-04 23:00:00 107 220 C
15  2019-07-05 05:00:00 107 227 C
16  2019-07-05 11:00:00 108 208 C
17  2019-07-05 17:00:00 110 248 C
18  2019-07-05 23:00:00 107 235 NaN

A: You may try pd.IntervalIndex and map as follows:
inx = pd.IntervalIndex.from_arrays(df2['Start Time'], df2['End Time'], closed='both')
df2.index = inx
df1['cond'] = df1.Date.map(df2.Condition)

Out[423]:
                  Date   P1   P2 cond
0  2019-07-01 11:00:00  102  240    A
1  2019-07-01 17:00:00  102  247    A
2  2019-07-01 23:00:00  100  219    A
3  2019-07-02 05:00:00  107  213    A
4  2019-07-02 11:00:00  100  226  NaN
5  2019-07-02 17:00:00  104  239  NaN
6  2019-07-02 23:00:00  110  240  NaN
7  2019-07-03 05:00:00  110  232    B
8  2019-07-03 11:00:00  102  215    B
9  2019-07-03 17:00:00  103  219    B
10 2019-07-03 23:00:00  107  243    B
11 2019-07-04 05:00:00  107  246  NaN
12 2019-07-04 11:00:00  103  219  NaN
13 2019-07-04 17:00:00  105  220  NaN
14 2019-07-04 23:00:00  107  220    C
15 2019-07-05 05:00:00  107  227    C
16 2019-07-05 11:00:00  108  208    C
17 2019-07-05 17:00:00  110  248    C
18 2019-07-05 23:00:00  107  235  NaN

A: You could do something like the following:
df1 = pd.read_csv(io.StringIO(s1), sep='\s\s+', engine='python',
                                                converters={'Date': pd.to_datetime})

df2 = pd.read_csv(io.StringIO(s2), sep='\s\s+', engine='python',
                converters={'Start Time': pd.to_datetime, 'End Time': pd.to_datetime})

df2 = df2.set_index('Condition').stack().reset_index()
df = pd.merge_asof(df1, df2, left_on='Date', right_on=0, direction='backward')
df.loc[(df['level_1'].eq('End Time')) & (df['Date'] > df[0]), 'Condition'] = ''

print(df.iloc[:, :-2])

                  Date   P1   P2 Condition
0  2019-07-01 11:00:00  102  240         A
1  2019-07-01 17:00:00  102  247         A
2  2019-07-01 23:00:00  100  219         A
3  2019-07-02 05:00:00  107  213         A
4  2019-07-02 11:00:00  100  226
5  2019-07-02 17:00:00  104  239
6  2019-07-02 23:00:00  110  240
7  2019-07-03 05:00:00  110  232         B
8  2019-07-03 11:00:00  102  215         B
9  2019-07-03 17:00:00  103  219         B
10 2019-07-03 23:00:00  107  243         B
11 2019-07-04 05:00:00  107  246
12 2019-07-04 11:00:00  103  219
13 2019-07-04 17:00:00  105  220
14 2019-07-04 23:00:00  107  220         C
15 2019-07-05 05:00:00  107  227         C
16 2019-07-05 11:00:00  108  208         C
17 2019-07-05 17:00:00  110  248         C
18 2019-07-05 23:00:00  107  235

A: df1.insert(3, "Cond", [None] * len(df1))
for i in range(len(df2)):
    df1.loc[(df1["Date"] >= df2["Start Time"].loc[i]) * (df1["Date"] <= df2["End Time"].loc[i]), "Cond"] = df2["Condition"].loc[i]


text:
Q: Event should trigger when Toastr notification appears i want to trigger an event using protractor for close the Toastr notification messages. whenever the notification appears this event should triggered.. is this possible??
I have 10 forms ,i am validating these forms using protractor. In each form i have editable text fields. If you add/edit/delete any fields you will get toastr notification message. I want to close these messge whenever it appears in my appliaction.
is this possible?? Thanks in advance..

A: You can execute JS code while running your test for closing toastr notification, you could try this one (I tested it in their demo project - run this code toastr.remove() in a console when toastr notification was shown):
await browser.executeScript(toastr.remove())

note that browser.executeScript() return Promise so you need to resolve it.


text:
Q: Populating a drop down with a array of values passed from JavaScript I have a Drop down which shows continents. Based on the selection of continent the next Drop down will show the relevant countries of that continent.This is how I did it
Continent
   <Select  class="form-control" th:field="*{continent}" id="continent">
         <option th:value="Africa" th:text="Africa"></option>
         <option th:value="Europe" th:text="Europe"></option>
         <option  th:value="Asia" th:text="Asia"></option>
</Select>

Country
<Select  class="form-control" th:field="*{country}" id="country">  </Select>

Here is the JavaScript Code I used to do that


text:
Q: std::pow in static_assert triggers error C2057? The following code in Visual Studio 2013 causes an error C2057:
#include <cmath>

int main() {
    static_assert(std::pow(2, 2) < 5, "foobar");
    return 0;
}

error C2057: expected constant expression

If I compile under GCC -std=c++0x it works fine. http://ideone.com/2c4dj5
If I replace the std::pow(2, 2) with 4, it also compiles under Visual Studio 2013.

*

*Is this a VS2013 bug?

*How can I work around this?

A: std::pow is not a constexpr function. The reason GCC accepts your code is because it offers a builtin version of pow, which evaluates the function at compile time since the arguments are known. If you add the -fno-builtin flag to the GCC command line, your code fails to compile. The error message is as expected:

error: non-constant condition for static assertion

So, this is not a VS2013 bug, but the effect of a GCC optimization. clang doesn't compile the code either.

A: The workaround is to implement your own pow as a constexpr function.
template<typename T>
constexpr T _pow(T x, size_t y) {
    return y ? x * _pow(x, y-1) : 1;
}

This implementation is very simple, but should work in your use-case.


text:
Q: Máscara de Horas ou TimePicker JavaFX Tenho um TextField aonde entro com a hora, porém sempre tenho que digitar os :. Como posso colocar uma máscara nesse TextField ou então se for mais simples um TimePicker?

A: Acredito que o ideal seria usar o DatePicker do JFXtras:

A: aqui nesse site https://community.oracle.com/thread/2552039 tem uma solução, mas o melhor mesmo seria criar uma skin.
import java.util.regex.Pattern;

import javafx.application.Application;
import javafx.beans.binding.Bindings;
import javafx.beans.binding.IntegerBinding;
import javafx.beans.property.ReadOnlyIntegerProperty;
import javafx.beans.property.ReadOnlyIntegerWrapper;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.IndexRange;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
import javafx.stage.Stage;

public class TimeTextFieldTest extends Application {

 @Override
  public void start(Stage primaryStage) {
  VBox root = new VBox(5);
  root.setPadding(new Insets(5));
  Label hrLabel = new Label();
  Label minLabel = new Label();
  Label secLabel = new Label();
  TimeTextField timeTextField = new TimeTextField();
  hrLabel.textProperty().bind(Bindings.format("Hours: %d", timeTextField.hoursProperty()));
  minLabel.textProperty().bind(Bindings.format("Minutes: %d", timeTextField.minutesProperty()));
  secLabel.textProperty().bind(Bindings.format("Seconds: %d", timeTextField.secondsProperty()));

  root.getChildren().addAll(timeTextField, hrLabel, minLabel, secLabel);
  Scene scene = new Scene(root);
  primaryStage.setScene(scene);
  primaryStage.show();
  }

  public static void main(String[] args) {
  launch(args);

  }

  public static class TimeTextField extends TextField {

    enum Unit {HOURS, MINUTES, SECONDS};

    private final Pattern timePattern ;
    private final ReadOnlyIntegerWrapper hours ;
    private final ReadOnlyIntegerWrapper minutes ;
    private final ReadOnlyIntegerWrapper seconds ;

    public TimeTextField() {
      this("00:00:00");
    }
    public TimeTextField(String time) {
      super(time);
      timePattern = Pattern.compile("\\d\\d:\\d\\d:\\d\\d");
      if (! validate(time)) {
        throw new IllegalArgumentException("Invalid time: "+time);
      }
      hours = new ReadOnlyIntegerWrapper(this, "hours");
      minutes = new ReadOnlyIntegerWrapper(this, "minutes");
      seconds = new ReadOnlyIntegerWrapper(this, "seconds");
      hours.bind(new TimeTextField.TimeUnitBinding(Unit.HOURS));
      minutes.bind(new TimeTextField.TimeUnitBinding(Unit.MINUTES));
      seconds.bind(new TimeTextField.TimeUnitBinding(Unit.SECONDS));
    }

    public ReadOnlyIntegerProperty hoursProperty() {
      return hours.getReadOnlyProperty();
    }

    public int getHours() {
      return hours.get() ;
    }

    public ReadOnlyIntegerProperty minutesProperty() {
      return minutes.getReadOnlyProperty();
    }

    public int getMinutes() {
      return minutes.get();
    }

    public ReadOnlyIntegerProperty secondsProperty() {
      return seconds.getReadOnlyProperty();
    }

    public int getSeconds() {
      return seconds.get();
    }

    @Override
    public void appendText(String text) {
      // Ignore this. Our text is always 8 characters long, we cannot append anything
    }

    @Override
    public boolean deleteNextChar() {

      boolean success = false ;

      // If there's a selection, delete it:
      final IndexRange selection = getSelection();
      if (selection.getLength()>0) {
        int selectionEnd = selection.getEnd();
        this.deleteText(selection);
        this.positionCaret(selectionEnd);
        success = true ;
      } else {
        // If the caret preceeds a digit, replace that digit with a zero and move the caret forward. Else just move the caret forward.
      int caret = this.getCaretPosition();
      if (caret % 3 != 2) { // not preceeding a colon
        String currentText = this.getText();
        setText(currentText.substring(0, caret) + "0" + currentText.substring(caret+1));
        success = true ;
      }
      this.positionCaret(Math.min(caret+1, this.getText().length()));
      }
      return success ;
    }

    @Override
    public boolean deletePreviousChar() {

      boolean success = false ;

      // If there's a selection, delete it:
      final IndexRange selection = getSelection();
      if (selection.getLength()>0) {
        int selectionStart = selection.getStart();
        this.deleteText(selection);
        this.positionCaret(selectionStart);
        success = true ;
      } else {
      // If the caret is after a digit, replace that digit with a zero and move the caret backward. Else just move the caret back.
        int caret = this.getCaretPosition();
        if (caret % 3 != 0) { // not following a colon
          String currentText = this.getText();
          setText(currentText.substring(0, caret-1) + "0" + currentText.substring(caret));
          success = true ;
        }
        this.positionCaret(Math.max(caret-1, 0));
      }
      return success ;
    }

    @Override
    public void deleteText(IndexRange range) {
      this.deleteText(range.getStart(), range.getEnd());
    }

    @Override
    public void deleteText(int begin, int end) {
      // Replace all digits in the given range with zero:
      StringBuilder builder = new StringBuilder(this.getText());
      for (int c = begin; c<end; c++) {
        if (c % 3 != 2) { // Not at a colon:
          builder.replace(c, c+1, "0");
        }
      }
      this.setText(builder.toString());
    }

    @Override
    public void insertText(int index, String text) {
      // Handle an insert by replacing the range from index to index+text.length() with text, if that results in a valid string:
      StringBuilder builder = new StringBuilder(this.getText());
      builder.replace(index, index+text.length(), text);
      final String testText = builder.toString();
      if (validate(testText)) {
        this.setText(testText);
      }
      this.positionCaret(index + text.length());
    }

    @Override
    public void replaceSelection(String replacement) {
      final IndexRange selection = this.getSelection();
      if (selection.getLength()==0) {
        this.insertText(selection.getStart(), replacement);
      } else {
        this.replaceText(selection.getStart(), selection.getEnd(), replacement);
      }
    }

    @Override
    public void replaceText(IndexRange range, String text) {
      this.replaceText(range.getStart(), range.getEnd(), text);
    }

    @Override
    public void replaceText(int begin, int end, String text) {
      if (begin==end) {
        this.insertText(begin, text);
      } else {
      // only handle this if text.length() is equal to the number of characters being replaced, and if the replacement results in a valid string:
      if (text.length() == end - begin) {
        StringBuilder builder = new StringBuilder(this.getText());
        builder.replace(begin, end, text);
        String testText = builder.toString();
        if (validate(testText)) {
          this.setText(testText);
        }
          this.positionCaret(end);
      }
      }
    }

    private boolean validate(String time) {
      if (! timePattern.matcher(time).matches()) {
        return false ;
      }
      String[] tokens = time.split(":");
      assert tokens.length == 3 ;
      try {
        int hours = Integer.parseInt(tokens[0]);
        int mins = Integer.parseInt(tokens[1]);
        int secs = Integer.parseInt(tokens[2]);
        if (hours < 0 || hours > 23) {
          return false ;
        }
        if (mins < 0 || mins > 59) {
          return false ;
        }
        if (secs < 0 || secs > 59) {
          return false ;
        }
        return true ;
      } catch (NumberFormatException nfe) {
        // regex matching should assure we never reach this catch block
        assert false ;
        return false ;
      }
    }

    private final class TimeUnitBinding extends IntegerBinding {

      final Unit unit ;
      TimeUnitBinding(Unit unit) {
        this.bind(textProperty());
        this.unit = unit ;
      }
      @Override
      protected int computeValue() {
        // Crazy enum magic
        String token = getText().split(":")[unit.ordinal()];
        return Integer.parseInt(token);
      }

    }

  }
}

Aqui tem um exemplo de skin só que é para formatar dinheiro.
https://github.com/thiagofdso/MoneyTest


text:
Q: Python monkeypatching best practices I am testing an application that has several external dependencies and I have used monkeypatching techniques to patch the functions of external libraries with a custom implementation to help my tests. It works as expected.
But the problem I currently have is that this makes my test file really messy. I have several tests and each test requires its own implementation of the patched function.
For instance, let us say I have a GET function from an external library, my test_a() needs GET() to be patched so that it returns False and test_b() needs GET() to be patched so that it returns True.
What is the preferred way to handle such a scenario. Currently I do the following:
def test_a(monkeypatch):
    my_patcher(monkeypatch, patch_get_to_return_true = True, patch_get_to_return_false = False, patch_get_to_raise_exception = False)

def test_b(monkeypatch)
    my_patcher(monkeypatch, patch_get_to_return_true = True, patch_get_to_return_false = False, patch_get_to_raise_exception = False)

def test_c(monkeypatch)
    my_patcher(monkeypatch, patch_get_to_return_true = False, patch_get_to_return_false = False, patch_get_to_raise_exception = True)

def my_patcher(monkeypatch, patch_get_to_return_true = False, patch_get_to_return_false = False, patch_get_to_raise_exception = False):

    def patch_func_pos():
        return True

    patch_func_neg():
        return False

    patch_func_exception():
        raise my_exception

    if patch_get_to_return_true:
        monkeypatch.setattr(ExternalLib, 'GET', patch_func_pos)

    if patch_get_to_return_false:
        monkeypatch.setattr(ExternalLib, 'GET', patch_func_neg)

    if patch_get_to_raise_exception:
        monkeypatch.setattr(ExternalLib, 'GET', patch_func_exception)

The above sample has just three tests that patch one function. My actual test file has around 20 tests and each test will further patch several functions.
Can someone suggest me a better way of handling this? Is it recommended to move monkeypatching part to a separate file?

A: Without knowing further details, I would suggest splitting my_patcher into several small fixtures:
@pytest.fixture
def mocked_GET_pos(monkeypatch):
    monkeypatch.setattr(ExternalLib, 'GET', lambda: True)

@pytest.fixture
def mocked_GET_neg(monkeypatch):
    monkeypatch.setattr(ExternalLib, 'GET', lambda: False)

@pytest.fixture
def mocked_GET_raises(monkeypatch):
    def raise_():
        raise Exception()
    monkeypatch.setattr(ExternalLib, 'GET', raise_)

Now use pytest.mark.usefixtures to autoapply the fixture in test:
@pytest.mark.usefixtures('mocked_GET_pos')
def test_GET_pos():
    assert ExternalLib.GET()

@pytest.mark.usefixtures('mocked_GET_neg')
def test_GET_neg():
    assert not ExternalLib.GET()

@pytest.mark.usefixtures('mocked_GET_raises')
def test_GET_raises():
    with pytest.raises(Exception):
        ExternalLib.GET()

However, there is room for improvements, depending on the actual context. For example, when the tests logic is the same and the sole thing that varies is some test precondition (like different patching of GET in your case), tests or fixtures parametrization often saves a lot of code duplication. Imagine you have an own function that calls GET internally:
# my_lib.py

def inform():
    try:
        result = ExternalLib.GET()
    except Exception:
        return 'error'
    if result:
        return 'success'
    else:
        return 'failure'

and you want to test whether it returns a valid result no matter what GET behaves:
# test_my_lib.py

def test_inform():
    assert inform() in ['success', 'failure', 'error']

Using the above approach, you would need to copy test_inform three times, the only difference between the copies being a different fixture used. This can be avoided by writing a parametrized fixture that will accept multiple patch possibilities for GET:
@pytest.fixture(params=[lambda: True,
                        lambda: False,
                        raise_],
                ids=['pos', 'neg', 'exception'])
def mocked_GET(request):
    monkeypatch.setattr(ExternalLib, 'GET', request.param)

Now when applying mocked_GET to test_inform:
@pytest.mark.usefixtures('mocked_GET')
def test_inform():
    assert inform() in ['success', 'failure', 'error']

you get three tests out of one: test_inform will run three times, once with each mock passed to mocked_GET parameters.
test_inform[pos]
test_inform[neg]
test_inform[exception]

Tests can be parametrized too (via pytest.mark.parametrize), and when applied correctly, parametrization technique saves a lot of boilerplate code.


text:
Q: Optimize Excel Macro - Speed There are two worksheets named Data and Calc.
The Data tab has app 200,000 rows and 14 columns. Each month going forward I will be adding roughly 1500 rows of data.
Calc tab fetches the relevant data from the data tab.
Cell K3:HB3 are numbers from 1 to 200.
Below is the formula which is used to calculate data for 1500 rows and 200 columns and currently I am taking roughly 15 mins to do the calculations.
Please could you help me in processing the below macro faster.
Sub Calc()

Application.ScreenUpdating = False
Application.Calculation = xlManual
Application.CutCopyMode = False
Dim S As Workbook
Dim j, 1stcolm as Integer
Dim S1, D1 As Worksheet

Set S1 = ThisWorkbook.Worksheets("Data")
Set D1 = ThisWorkbook.Worksheets("Calc")
Dim myFormula As String
myFormula = "=SUMIFS(Data!C2,DATE(YEAR('Calc'!R[0]C5),MONTH('Calc'R[0]C5)+'Calc'!R3C[0]-1,1),Data!C7,'Calc'!R[0]C2)"

D1.Activate

For j = 4 To D1.Range("B" & Rows.Count). End (3) (1). Row

        Range("K" & j, "HB" & j) = myFormula
        Next j

Application.Screenupdating= True
Application.Calculation = xlAutomatic
Application.CutCopyMode = False

End Sub

A: Deactivate the automatic calculation and reactivate it at the end of your code. Also, it is better to not use a formula in your code, prefer the use of the loop.
Sub OptimizeTimeCode()

    'Remove the update of Excel screen
    Application.ScreenUpdating = False
    Application.EnableEvents = False 'Remove pop-up
    Application.DisplayAlerts = False
    Application.AskToUpdateLinks = False
    'Remove the automatic calculation
    Application.Calculation = xlCalculationManual

    '... your code

   'To be re-activated at the end of the process
   Application.ScreenUpdating = True
   Application.EnableEvents = True
   Application.DisplayAlerts = True
   Application.AskToUpdateLinks = True
   Application.Calculation = xlCalculationAutomatic

End Sub


text:
Q: function with callback execute callback before function complete I'd write the following code to practice function with callback in javascript.
fs = require('fs');

function funcWithCallback(callback) {

  fs.readFile('YouBikeTP.txt', 'utf8', function (err,data) {
  if (err) {
    return console.log(err);
  }
  console.log(data.length);
  });
  callback();
}

funcWithCallback(function(){
  console.log("string in callback ")
})

The purpose of the code is try to control the sequence of  methods execution. The string "string in callback" should be printed after the length of text file be printed, but when I ran this code the result will be:
>> "string in callback"
>> 91389 //the length of YouBikeTP.txt

which is not the result I expected.
should be
 >> 91389 //the length of YouBikeTP.txt
 >> "string in callback"

could anyone tell me why will the callback function been called before funcWithCallback(callback) complete ? Did I misunderstand the meaning of callback function ?

A: Change your code to this:
Reason: the function you have defined as a callback in the readFile is an asynchronous callback. It doesn't execute right away, rather it executes when the file loading has completed. Therefore you need to call the main callback function after the console.log for async callback is done.
fs = require('fs');

function funcWithCallback(callback) {

   fs.readFile('YouBikeTP.txt', 'utf8', function (err,data) {
      if (err) {
          return console.log(err);
      }
      console.log(data.length);
      callback(); //calling the main callback after the async callback console logs
   });

}

funcWithCallback(function(){
    console.log("string in callback ")
})

A: You are not calling callback () inside readFile's own callback, you are just calling it after calling readFile, that then calls its callback function (err,data) only after completing.

A: you must call the callback() in the fs.readFile callback function.As the callback should be called after asyc function written with the result or error.


text:
Q: How to implement a dependent drop down list with Django CreateView? I am trying to create a CreateView for one of my models "service". My "service" model has a foreign key to an "asset" model. "asset" model has a foreign key to the current user.
I would like to populate a drop down in "service" CreateView with all the "assets" owned by the current logged in "user".
Service model
class Service(models.Model):
    name = models.CharField(max_length=100)
    category = models.CharField(max_length=100)
    provider = models.CharField(max_length=100)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    asset = models.ForeignKey(Asset, on_delete=models.CASCADE)

Asset model
class Asset(models.Model):
    name = models.CharField(max_length=100)
    address = models.CharField(max_length=100)
    suburb = models.CharField(max_length=100)
    postcode = models.CharField(max_length=4)
    state = models.CharField(max_length=3)
    created = models.DateTimeField(auto_now_add=True)
    updated = models.DateTimeField(auto_now=True)
    owner = models.ForeignKey(User, on_delete=models.CASCADE)

ServiceCreateView in views.py
class ServiceCreateView(LoginRequiredMixin, CreateView):
    model = Service
    fields = ['name', 'category', 'provider', 'asset']

If I user 'asset' in fields, I get all the assets added to the drop-down list. I need it to be only the assets owned by the current user.
Any help in this much appreciated.
Thank you.
(I am using the Django 2.2)

A: Modify your ServiceCreateView to use distinct form, specify template and send current user to that form, so it will know for which user it will need to filter asset
views.py:
class ServiceCreateView(LoginRequiredMixin, CreateView):
    form_class = ServiceCreateForm
    template_name = 'service_form.html'

    def get_form_kwargs(self):
        kwargs = super().get_form_kwargs()
        kwargs['user'] = self.request.user
        return kwargs

Create ModelForm with same fields and model, that will take user instance on init and filter your asset field accordingly.
forms.py:
class ServiceCreateForm(forms.ModelForm):
    class Meta:
        model = Service
        fields = ['name', 'category', 'provider', 'asset']

    def __init__(self, *args, **kwargs):
        user = kwargs.pop('user', None)
        super().__init__(*args, **kwargs)

        self.fields['asset'].queryset = self.fields['asset'].queryset.filter(
            owner=user)


text:
Q: TypeError: Class extends value # is not a constructor or null in react js I am trying to over ride some function of a prime react button component but i am getting this error while extending prime react button component class.
Here is my code:
import { Button } from "primereact/button";
class BtnBox extends Button {
  constructor(props) {
    super(props);
    this.renderLabel = this.renderLabel.bind(this);
  }

  renderLabel() {
      return icon;
  }
}
class IconButton extends React.Component {
  render() {
    return (

        <BtnBox {...this.props} />

    );
  }
}

export default IconButton;

A: can you try this form ?
import { Button } from "primereact/button";
     class BtnBox extends Button {
         constructor(props) {
             super(props);
          }

         render = () => {this.props.name};
      }

   class IconButton extends React.Component {
      render() {
        return (

            <BtnBox name='add item' />

        );
      }
    }

 export default IconButton;

if doesn't suite for you, can you share more detail ?


text:
Q: Mouse in Assembly 8086 As part of a school project I am making a game that shows everything we've learned this semester.
So I made this game where you're this smiley guy and you run around a maze with obstacles that bring you back to the start of the maze and once you reach the end you go to the next level.
So I wanted to add a title screen with a "button" -- pretty much a title screen drawn in text and then:
 mov  ax, 3h
 int  33h
 mov  mouseClick, bx
 mov  mouseX, cx
 mov  mouseY, dx
 call checkMClick
 cmp  mousePos, 1h
 je   goodMPos
 jne  badMPos

 goodMPos:

 call firstLevel
 call newMazePos
 call output

;---------------------------------------;

 checkMClick: cmp  mouseclick, 1h
              je   checkMouseX
              jne  mouse

 checkMouseX: cmp  mouseX, 7h
              jge  afterStartX
              jl   mouse

 afterStartX: cmp  mouseX, 23h
              jle  goodXPos
              jg   badMPos

 goodXPos:    mov  mousePos, 1h
              jmp  checkMouseY

 checkMouseY: cmp  mouseY, 7h
              jge  afterStartY
              jl   mouse

 afterStartY: cmp  mouseY, 11h
              jge  goodYPos
              jl   badMPos

 goodYPos:    mov  mousePos, 1h
              ret

 badMPos:     mov  mousePos, 0h
              jmp  mouse

But the coordinates for the mouse position are fucked up.
EDIT: Here's the pastebin for the entire thing

A: You have to change the order of the operands! The registers are the source.
mov  bx, mouseClick
mov  cx, mouseX
mov  dx, mouseY

Also function 3 of the mouse driver gives positions as if the screen were 640x200. You have to compensate for this.

A: ; DATA segment
mouseClick DW ?
mouseX     DW ?
mouseY     DW ?
mousePos   DW ?

; CODE segment
mov  ax, 3h
int  33h
mov  [mouseClick], bx ; Write the value of BX to mouseClick
mov  [mouseX], cx     ; Write the value of CX to mouseX
mov  [mouseY], dx     ; Write the value of DX to mouseY

Those following instructions need to specify how many bytes we want to access.
cmp  mouseclick, 1h
mov  mousePos, 1h

cmp  WORD[mouseclick], 1h ; for to compare two bytes
mov  WORD[mousePos], 1h   ; for to write two bytes

And for to check unsigned nunbers if the value is above, or below, we can use the instructions: "ja, jna, jb, jnb". The instructions: "jg, jng, jl, jnl are for signed numbers.
In text modes, all coordinates are specified as multiples of the cell size, typically 8x16 or 8x8 pixels.
http://en.wikipedia.org/wiki/Text_mode


text:
Q: JavaFX 2.0 TableView in FXML with Data from Database I am wondering how can I retrieve data from a mysql database into a tableview which is into a fxml file. I must retrieve the data and place it into a tableview which is located in a fxml file. I have the idea of how I will connect to the database, but I don't know how to retrieve the data and place it into tableview.
The tableview is in a fxml file. If I am still here, anyone know after I import the data how can I edit the cells in this tableview?
The application I work on is a desktop one!

A: There are a few ways to do this, one is to use the JDBC adapter from DataFX.
Update
FXML itself just defines an xml based UI structure, it cannot load data from a database.
When the data originates from the database, creating a static fxml file containing the data values is likely a bad idea in most cases.  Anytime the data in the database changes, you will need to generate and load a new fxml file and for that you will need to either create the new file by hand or write a fragile program to generate the new fxml file based upon the data in the database.
Suggested approach:

*

*Use the fxml only to define your TableView structure but not to contain actual data values.

*In your JavaFX Java code connect to the mysql database.

*Use the DataFX JDBC data source adapter to retrieve the data from the database and populate your TableView.

You could write your own code to do step 3.  Using your own code might be a good idea if you wish to use JPA (which I think DataFX does not currently directly support). Otherwise you will probably end up with better results quicker using the DataFX implementation.
To find out how to do edits in TableView, read this TableView tutorial. Again, DataFX will help you by providing Control Cell Factories for edits - so I'd recommend using DataFX for this rather than handcoding the TableView edit handling.
I'm not sure if the DataFX code will help you when you need to commit edits to a database; in that case you will probably need to add your own JDBC or JPA code to commit the changes.

A: AFAIK, you cannot retrieve and display the data from DB in FXML file, and make the tableview cells editable in FXML file. Even though it was possible (maybe partially through custom Builder and BuilderFactory), it is not recommended to do that in a sense of MVC.  Please read about Why Use FXML and its benefits first. Still you can define some basic data structures in FXML file if it is so necessary, see Introduction to FXML.
So do your non-view related tasks in a initialize() method of the controller, namely retrieve data and set the items of the tableview. Customize the cell factories of the table columns to support editing and so on.


text: Q: What is the correct property name for firebase auth photoURL? All of the firebase authentication documentation refers to this property as photoURL ('URL' is uppercase), but when I export user data to json, the property is photoUrl (camelCased). Is this just a quirk of the export process or has the property name changed throughout firebase?


text:
Q: onnewIntent method is not called when using Parse.com push notification Hi I am developing an android app to receive the push notification from parse.com with below requirement .
application have two activity say A and B.
when i launch my application activity A will be displayed and then activity B when i click button on activity A.
I want to open activity B when i receive push notification message and display on it whether my app running in background or not.
if running on background/or not how can i do that in both the cases.
Please help me.

A: Method onNewIntent() will be called is case:

This is called for activities that set launchMode to "singleTop" in   their package, or if a client used the FLAG_ACTIVITY_SINGLE_TOP flag when calling startActivity().
  In either case, when the   activity is re-launched while at the top of the activity stack instead   of a new instance of the activity being started, onNewIntent() will be   called on the existing instance with the Intent that was used to   re-launch it.

If instance of your activity B isn't exist then onCreate() will be called.


text:
Q: Terraform: AWS_volume_attachment how to auto assign devide_name I'm writing my first terraform script. Idea is to create aws_ebs_volume and then attach it to previously existing ec2 instance by providing variables like instance name, volume type, size, iops etc.
So far everything is working however I see one issue with it, in order to run script I would have to check existing device_names attached to EC2 instance and then manually pick new one. Every other variable can be provided off the top of my head. I was thinking if there's a way to automate it so terraform automatically assigns new, not used yet device_name ?
Any help would be appreciated, here's what I've got so far
variable "environment" { default = "dev" }
variable "ProductCode" { default = "test" }
variable "name" { default = "instance_name_terraform_test" }
variable "size" { default = "10" }
variable "type" { default = "gp2" }
variable "instance_name" { default = ["instance_name"] }
variable "iops" { default = "500" }
variable "device_name" { default = "xvdb" }

resource "aws_ebs_volume" "create_volume" {
  availability_zone = data.aws_instance.check.availability_zone
  size              = var.size
  type              = var.type
  encrypted         = true
  tags              = local.tags
  depends_on  = [data.aws_instance.check]
}

data "aws_instance" "check" {
  filter {
    name   = "tag:Name"
    values = var.instance_name
  }
}

resource "aws_volume_attachment" "attach" {
  instance_id = data.aws_instance.check.id

  volume_id   = aws_ebs_volume.create_volume.id
  device_name = var.device_name
  depends_on  = [data.aws_instance.check]
}
locals {
  tags = {
    Name        = var.name
    Environment = var.environment
    ProductCode = var.ProductCode
  }
}


text:
Q: asp.net mvc 4 [HttpPost] not working I am new to asp.net MVC 4. i have some problems dealing with attributs
i use [httppost] attribut in my controller but  it's not working
it's not even  invoked
my controller
    public ActionResult Inscription()
    {
        return View();
    }

    [HttpPost]
    public ActionResult Inscription(Candidat candidat)
    {
        if (!ModelState.IsValid)
        {
            return View(candidat);

        }

        return RedirectToAction("Index");
    }

my view
     @model ProcRec.Models.Candidat

     @{
     ViewBag.Title = "Inscription";
     Layout = "~/Views/Shared/_Layout.cshtml";
      }

      @Html.ValidationSummary(true)

      @using (Html.BeginForm("Inscription", "CandidatController"))
      {

      @*Nom :*@ @Html.LabelFor(model => model.nom_candidat)

       @Html.TextBoxFor(model => model.nom_candidat)
            @Html.ValidationMessageFor(Model => Model.nom_candidat)

             .

             .

       }
  <input type="submit"  class="submit right"  value="Inscription" />

think you for your help

A: Just correct beginform as :
@using (Html.BeginForm("Inscription", "CandidatController",FormMethod.Post))
{
  ........
  <input type="submit"  class="submit right"  value="Inscription" />
}

Put submit button inside BeginForm() and give BeginForm() FormMethod as Post.
Thankzz..

A: Put your <submit> element inside the form:
@using (Html.BeginForm())
{
    ...
    <input type="submit"  class="submit right"  value="Inscription" />
}

A: Don't need to change Html.BeginForm. By default it's POST.
Check : FormExtensions.BeginForm
Only issue is with the submit button, it should be inside form as mentioned in Andy Refuerzo's answer. Don't know why it is down-voted.


text:
Q: Free and easy file sharing or at least send files within local wifi is there any easy way to share or at least send files within local network (in my case wifi) and between various machines with Kubuntu linux and Windows 7?
I often have to send some files to a computer which is also connected to our home wifi network but need to avoid internet due slow connection.
I am looking for something simple - already tried LAN Messenger - the file sending works nice in Windows but I was not able to make it work in linux.
Currently looking on Lanshark but also heard about Samba sharing. Am I right that using smb means that everything I put in the sharing folder is automatically available for other users?
Is there any simple solution for this?
thanks

A: I would use Samba, rsync or Bittorrent Sync which is also encrypted and simple to use. If you want something a bit more sophisticated, like dropbox, you can deploy an Owncloud instance.
All of them can work in local network.
Samba in Linux will behave as the "Network Sharing" with Windows, OSX and Linux clients.
There are plenty of options, choose what fits better for you.


text:
Q: Maximal analytic continuation gives rise to a covering Suppose that $a$ is a point on a connected Riemann surface $X$ and $\varphi \in \mathcal{O}_a$ admits an analytic continuation along every curve in $X$ starting at $a$. Let $(Y, p, f, b)$ be the maximal analytic continuation of $\varphi$.
Problem: Prove that $p : Y \to X$ is a covering map.
My try: View $\operatorname{id} : X \to X$ as the analytic continuation of itself, then we must have a map $F : X \to Y$ such that $F(a) \in p^{-1}(a)$ and $f \circ F = \operatorname{id}$. I suspect $\# p^{-1}(a)$ gives the number of sheets of the covvering. I don't see yet how we can get a homeomorphism between an open $U \subset X$ and some $V_i$ in each of the sheets.

A: The maximal analytic continuation of a holomorphic germ $f_x \in \mathcal{O}_x$ at a point $x\in X$ is obtained by restricting the étale space
$$p:\vert \mathcal{O} \vert \xrightarrow{} X$$
to the connected component $Y$ containing $f_x$. This abstract construction can be found in Chap. 7 of "O. Forster: Riemann Surfaces." That $p$ is a covering map follows from the definition of the topology of $\vert \mathcal{O} \vert$.


text:
Q: JavaScript: Try/Catch vs error function passed as a parameter I am wondering which approach is better for error handling and debugging in JavaScript for nodeJS?
Having a pure try/catch block:
try
{
  dangerous.function();

}
catch(error);
{
  console.log(error);
}

or
Just using a function as a parameter, which will display if any errors occur
dangerous.function(function(error)
{
  console.log(error);
});

I am raising this question because I read that try/throw has a potential of logging too much stack trace data as written here: http://nodejs.org/api/domain.html#domain_warning_don_t_ignore_errors

A: It's totally up to you. Exceptions have the advantage of providing a stack trace.
Note that if dangerous.function does its work asynchronously, then you'll need to use your second approach, since there isn't any exception to catch initially. But that doesn't mean you can't use an exception, just that if you want to use an exception, you have to pass the exception to the callback rather than throwing it. (Or don't use an exception, that's also totally up to you.)

A: They aimed to fulfill the same purpose, but they are to be used in different contexts:

*

*try/catch will only work to intercept synchronous errors

*callback will allow both synchronous and asynchronous errors transmission

I strongly advice to read this article (even though it is first addressed for Node.js developers, it is valuable for every JavaScript developer) which fully covers the subject.


text:
Q: Why is the western sky yellow after sunset? I have read this question:
Why is the sky blue and the sun yellow?
where John Rennie says:

The only light we see directly from the Sun is the light that travels in a straight line from the Sun to our eye
If you consider the upper yellow line we can't see this light ray because it misses our eye. However the Rayleigh scattering due to the air scatters in all directions, so some of this scattered light reaches our eye. That means when we look away from the Sun we only see the scattered light and not the direct sunlight.
The Rayleigh scattering depends on the wavelength and blue light is scattered most. That means the light we see coming from directions away from the Sun has a spectrum weighted towards the blue.

Now I do understand that the sky is blue due to Rayleigh scattering. The Sun appears yellowish when close to sunset because the closer it is to the horizon, light has to pass through a longer way through the atmosphere and this means more Rayleigh scattering, thus, the direct sunlight into our eyes will be weighted more towards the yellow (more blue photons scatter off).
This explains both why the sky is blue and why the direct light from the Sun is more yellowish close to the horizon.

But what happens after sunset? There is no direct sunlight. All Sunlight is because of scattering. How can that be then yellowish? It should all be blue because of Rayleigh scattering. After sunset, none of the photons are reaching our eyes directly. All of them are scattered off the atoms in the atmosphere. Thus, Rayleigh scattering should dominate and cause it to be just blue.

Just to clarify, my question is about after the sunset, when the Sun is completely below the horizon, and no photon can reach our eyes directly from the Sun, all photons are scattered through the atmosphere. Why is the sky yellow then? There are no clouds either. The question is basically if the afterglow is caused by Mie scattering and how it can dominate Rayleigh.

A: This phenomenon is also known as an afterglow (the opposite is called foreglow, which occurs before sunrise), which is a broad arch of whitish or pinkish sunlight in the sky that is scattered by fine particulates, like dust, suspended in the atmosphere. An afterglow may appear above the highest clouds in the hour of fading twilight or be reflected off high snowfields in mountain regions long after sunset. The particles produce a scattering effect upon the component parts of white light. The high-energy and high-frequency light is scattered out the most, while the remaining low-energy and -frequency light reaches the observer on the horizon at twilight. The backscattering of this light further turns it pinkish to reddish.


text:
Q: Java -jar "/users/admin/Sample code/sample.jar" - Space issue I'm trying to trigger a payload installation using java with the help of this code from the command window:
" java -jar "/users/admin/Sample code/sample.jar" -payloads "/users/admin/Sample code/payloads" -logfile testing.log -loglevel FINE "
But because of the space present in the directory '/users/admin/Sample code/sample.jar', exception is being thrown.
How can i rectify this ?

A: (If my understanding is correct, this is more of a shell interpolation problem than a Java problem, so you might want to modify the tags to reflect this.)
This is going to be tricky because you need to know how many levels of parsing this command line is going to go through until some command processor shell does it's own parsing. At the end of this whole thing we are hoping to have all the tokens presented to the java process in the manner we expect.
That's the general problem.
Assuming you are running this directly from a shell (I think that's what "command window" means -- I'm trying to be careful here) then it depends on how that shell parses the command into tokens, and passes control to the Java process. For example, on Windows the sort of necessary and available quoting is different, and behaves differently, than POSIX shells.
The specific problem, then, is protecting this space as significant for the shell you are running the command in, such that the java process sees its arguments, and then the Java program that launches as a result sees /its/ arguments in the right manner.
You don't mention which shell you are running, or which of the arguments is failing (the argument to java, or the argument to the java program that is invoked.  So it is hard to hand you specific help.
But, if you are using a POSIX shell of some sort, you could use one (or more) backslash escapes on the offending spaces in either part until you get the results you want. Or use nested strong quotes to suppress interpolation by the shell or java main().
You might want to say what sort of program this is, and how you are running it, and on what platform, and what results you are getting, exactly. It is important to know where in this startup process the error is being thrown.
[EDIT]
I see you are probably on a POSIX shell of some sort, in which case, you should be able to use single-quotes or backslash escaping to protect the spaces in these arguments [either to the Java process or the main()].
[EDIT]
Given that this is a POSIX shell, and it appears to be failing to find a startup file, either the jarfile is missing this class or the jar manifest file is malformed. Does this class exist, exactly as spelled (case is significant!) in the jarfile? Remember that a class name must match exactly across the class definition in the code, in the filename/jarfile entry and in the manifest file.
That is, it appears that the JVM is finding the jarfile without a problem, but when it loads the jarfile to get the manifest info and the startup class, it fails to find that. So, this seems to be a problem with the jarfile itself, not that fact that your -jar optargs has a space in it.


text:
Q: How to store a List to Shared Preferences in Flutter? I have a list of RenderModel objects with 2 properties: message and widget. How can i save this list to Shared preferences ? Please tell me the solution. Thank you !
late List<RenderModel> listItems = <RenderModel>[];

A: You cannot. Widget is not a class you can just restore. It probably references an existing widget and the next time you run the app, that widget will be gone.
There might be another widget in it's place, but they have no connection. You will need to either save some kind of identifier, to find the widget you referenced, even if the app is closed and reopened, or you have to save some way of reconstructing all those widgets yourself.

A: You need to convert your list to a json and then store as a String.
you can use something like this to convert the list to string
String renderModelToJson(List<RenderModel> data) => json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

and fromJson and toJson will look like this.
 factory RenderModel.fromJson(Map<String, dynamic> json) => RenderModel(
    message: json["message"],
    widget: json["widget"],
);

Map<String, dynamic> toJson() => {
    "message": message,
    "widget": widget,
};


text:
Q: java.lang.NoClassDefFoundError in cmd I am facing this problem while trying to run my java file by writing java filename ....
I have read on many pages the possible ways this could be corrected but unfortunately I have been unable to correct my problem...

*

*First of all I looked at my environment variables and observed that there was no CLASSPATH     set and I had pointed PATH correctly to my jre as well as jdk bin in C:\

*Second I am able to run javac filename.java and observe that .class file gets built in the  local directory.

*While writing javac -classpath . filename works writing java -classpath . filename (without .class) results in the same error.
I just don't know how to run my program in command prompt!!!!
Please do not give me links to the pages which have given the same answers that I have mentioned above as they do not work in my case.....
Please help....

A: Note that if your class resides in some package mypackage, you need to make sure the class file is inside mypackage/ and do
java -classpath . mypackage.YourClass

A: There is a bit little information in your post ... as said, a complete example would really help solving this. Some ideas:

*

*Is class named filename? If not, you should make sure to call the right class name in the java command.

*if you have strange characters in your class name (basically anything apart from A-Z, a-z, 0-9, _), it could be mangled by your file system and thus lead to java not being able to find it. Make sure that the class name is the same as the file name.

*If you use packages, make sure the package names are congruent to your file structure (see latest questions with tag package for some examples).

*Is your class public? If not, make it so. (This should give another error, though.)

A: Stating javac filename.java and java filename are not enough for this really.
We also need to know the contents of the filename.java or at least the first few lines.
This is the expected way to declare a class
 public class Filename {
    }

This is the way it would have to be to work given your example: java filename
 public class filename {
    }

This is could exist too, but you are probably just messing with us :)
public class SomethingElse {
}

Overall no matter what the filename is on the filesystem, the class has a name and that is the name that the java command is expecting. I would recommend using the upper case first letter form as it is clearer imo


text:
Q: How to select options in Angular JS? I have generated SELECT list by php.
How I can select some option in this select list?
<select name="language[]" ng-model="formData.language" id="language" ng-required="true">
<option value="72" selected="selected">Fulfulde</option>
</select>

A: Try to use ng-options attribute
<select ng-model="myColor" ng-options="color.name group by color.shade disable when color.notAnOption for color in colors"> </select>

For more info my go through this link

A: I'd recommend you to use ng-options directive to work with select box.
<select ng-model="myColor" ng-options="color.name for color in colors"></select>

Working Plunkr


text:
Q: AWS transfer RDS mysql to another region without loosing data I wanted to transfer my mysql databaes from us-east-1 (virginia) to eu-east-1 (ireland) without loosing any data. Also, I want to stop  virginia after transfering database from one region to other region.
I have read about read replicas. I have tried once to make one read replica to another region with public access available. Once replica was ready I have promoted it and tried to access publicly . But I was not able to access the database with same credentials .
Also, I have seen blogs related to cloud formation.

A: So the question should really have title Why I can't access RDS Read Replica in a different region? Right?
My assumption is that the Security Group assigned to the Read Replica in eu-east-1 didn't permit access from your location.
Or that you created the read replica in a subnet without IGW (Internet Gateway) and therefore its public IP wasn't accessible.
Make sure you've got the Security Group and Subnet setting correct when creating the RDS Read Replica and you'll be fine.
Hope that helps :)

A: Create a read-replica of your existing RDS instance in another region. Then promote that read-replica to master. Now you have a separate instance running in another region. You can then stop this instance and point your applications
Refer below link
Amazon RDS  replica user guide


text:
Q: jquery step through images All I want to do is to be able to step through sequentially named images using up and down arrows.  I'm missing something simple and I can use some help.   The up and down fields do no work.  Any help is appreciated.  Here's my code:
HTML:

up up up

down down down

up up up

down down down

up up up

down down down

up up up

down down down

up up up

down down down

JavaScript:

I know my code is really clunky and bloated at this point, but it's a result of multiple error tests and not getting stuff to work.

A: Gabe is correct; you can't use a certain ID more than once. My advice is to orient it this way:

up

down

But the rest of it I'm a bit confused about; can you just explain, visually, how you expect this thing to look, and we can give you basic ideas about the pattern to follow? (Keeping in mind, Stack Overflow tends not to do the whole work for you)
(After comment: ) So this sounds like something pretty simple to control on the Javascript side, rather than have HTML for each instance of it. The basic idea would be to maintain the image index (and upper/lower bounds) as Javascript variables, and replace the image's src attribute with the correct one on each click. I'll give a bit of unfinished code to show what I'm thinking.
$(function() {
    var imgIndex = 10;
    var minIndex = 0;
    var maxIndex = 55;

    function refreshIndex() {
        // here, set the image's src to "n13.png", or whatever imgIndex is.
    }

    $('#pictureNavigator .upButton').click(function() {
        imgIndex++;
        refreshIndex();
    });
    $('#pictureNavigator .downButton').click(function() {
        imgIndex--;
        refreshIndex();
    });
});

There might be a few other things to think about there, but I think that should be enough. As for the HTML, you should only need one up arrow, one down arrow, and one image. There may also be a way for you to pre-cache each image you're going to show the user, before it's displayed, if you like. (You may want to at least try figuring that one on your own though)


text:
Q: Intersection of a line with a plane, where is wrong in third way? Let SABCD be a pyramid, SA perpendicular to the plane ABC, the base of pyramid is a rectangle,SA=h, AB=a, AD=b. A plane P passing A and  perpendicular to the line SC cut the lines SB, SD, SC respectively at E, F, K.
I tried it in three ways.
First way
\documentclass[border=3.14mm,12pt,tikz]{standalone}
\usepackage{tikz,tikz-3dplot}
\usepackage{tkz-euclide}
\usetkzobj{all}
\usetikzlibrary{intersections,calc,backgrounds}
\begin{document}
    \tdplotsetmaincoords{60}{120}
    \begin{tikzpicture}[tdplot_main_coords,scale=1.5]
    \pgfmathsetmacro\a{3}
    \pgfmathsetmacro\b{4}
    \pgfmathsetmacro\h{5}

    % definitions
    \path
    coordinate(A) at (0,0,0)
    coordinate (B) at (\a,0,0)
    coordinate (C) at (\a,\b,0)
    coordinate (D) at (0,\b,0)
    coordinate (S) at (0,0,\h)
    coordinate (E) at ({\a*\h^2/(\a^2+\h^2)}, 0, {\a^2*\h/(\a^2+\h^2)})
    coordinate (F) at (0, {\b*\h^2/(\b^2+\h^2)}, {\b^2*\h/(\b^2+\h^2)})
    coordinate (K) at ({\a*\h^2/(\a^2+\b^2+\h^2)}, {\b*\h^2/(\a^2+\b^2+\h^2)}, {(\a^2+\b^2)*\h/(\a^2+\b^2+\h^2)});

\begin{scope}
\draw [dashed, thick, name path=B--D] (B) -- (D);
\draw [dashed, thick, name path=C--A] (C) -- (A);
\path [name intersections={of=B--D and C--A,by=O}];
\end{scope}

\begin{scope}
\draw [dashed, thick, name path=S--O] (S) -- (O);
\draw [dashed, thick, name path=E--F] (E) -- (F);
\path [name intersections={of=S--O and E--F,by=I}];
\end{scope}

    \begin{scope}
    \draw[dashed, thick]
    (A) -- (B)   (D)--(A) (S)--(A);
    \draw[dashed, thick]
    (E) --(A)  -- (F);
    \draw[ultra thick]
    (S) -- (B) -- (C) -- (D)--cycle (S)--(C) (E) -- (K) --(F);
    \draw [thick, dashed] (A) -- (K)  (E) -- (F) ;
    \tkzMarkRightAngle(S,A,D)
    \tkzMarkRightAngle(S,A,B)
    \tkzMarkRightAngle(A,B,C)
    \tkzMarkRightAngle(B,A,D)
    \tkzMarkRightAngle(A,F,D)
    \tkzMarkRightAngle(A,E,B)
    \tkzMarkRightAngle(A,K,C)
    \end{scope}

    \foreach \point/\position in {A/left,B/below,C/below,S/above,D/right,E/left,D/right,F/right,K/above right,O/below,I/below}
    {
        \fill (\point) circle (1.5pt);
        \node[\position=3pt] at (\point) {$\point$};
    }
    \end{tikzpicture}

\end{document}

Second way
\documentclass[border=3mm,12pt]{standalone}
\usepackage{fouriernc}
\usepackage{tikz,tikz-3dplot}
\usepackage{tkz-euclide}
\usetkzobj{all}

\newcounter{smuggle}
\DeclareRobustCommand\smuggleone[1]{%
    \stepcounter{smuggle}%
    \expandafter\global\expandafter\let\csname smuggle@\arabic{smuggle}\endcsname#1%
    \aftergroup\let\aftergroup#1\expandafter\aftergroup\csname smuggle@\arabic{smuggle}\endcsname
}
\DeclareRobustCommand\smuggle[2][1]{%
    \smuggleone{#2}%
    \ifnum#1>1
    \aftergroup\smuggle\aftergroup[\expandafter\aftergroup\the\numexpr#1-1\aftergroup]\aftergroup#2%
    \fi
}

\usetikzlibrary{intersections,calc,backgrounds}
\tikzset{projection of point/.style args={(#1,#2,#3) on line through (#4,#5,#6)
        and (#7,#8,#9)}{%
        /utils/exec=\pgfmathsetmacro{\myprefactor}{((#1-#4)*(#7-#4)+(#2-#5)*(#8-#5)+(#3-#6)*(#9-#6))/((#7-#4)*(#7-#4)+(#8-#5)*(#8-#5)+(#9-#6)*(#9-#6))},
        insert path={%
            ({#4+\myprefactor*(#7-#4)},{#5+\myprefactor*(#8-#5)},{#6+\myprefactor*(#9-#6)})}
}}

 \begin{document}

    \tdplotsetmaincoords{60}{120}
 \begin{tikzpicture}[tdplot_main_coords,scale=1.5]
 \pgfmathsetmacro\a{3}
 \pgfmathsetmacro\b{4}
 \pgfmathsetmacro\h{5}

 % definitions
 \path
 coordinate(A) at (0,0,0)
 coordinate (B) at (\a,0,0)
 coordinate (C) at (\a,\b,0)
 coordinate (D) at (0,\b,0)
 coordinate (S) at (0,0,\h);

 \path[projection of point={(0,0,0) on line through (\a,0,0) and  (0,0,\h)}]
 coordinate (E)
 [projection of point={(0,0,0) on line through (0,0,\h) and (0,\b,0) }]
 coordinate (F)
 [projection of point={(0,0,0) on line through (0,0,\h) and (\a,\b,0) }]
 coordinate (K);

 \begin{scope}
 \draw [dashed, thick, name path=B--D] (B) -- (D);
 \draw [dashed, thick, name path=C--A] (C) -- (A);
 \path [name intersections={of=B--D and C--A,by=O}];
 \end{scope}

 \begin{scope}
 \draw [dashed, thick, name path=S--O] (S) -- (O);
 \draw [dashed, thick, name path=E--F] (E) -- (F);
 \path [name intersections={of=S--O and E--F,by=I}];
 \end{scope}

 \begin{scope}
 \draw[dashed, thick]
 (A) -- (B)   (D)--(A) (S)--(A);
 \draw[dashed, thick]
 (E) --(A)  -- (F);
 \draw[ultra thick]
 (S) -- (B) -- (C) -- (D)--cycle (S)--(C) (E) -- (K) --(F);
  \draw [thick, dashed] (A) -- (K)  (E) -- (F) ;

 \tkzMarkRightAngle(S,A,D)
 \tkzMarkRightAngle(S,A,B)
 \tkzMarkRightAngle(A,B,C)
 \tkzMarkRightAngle(B,A,D)
 \tkzMarkRightAngle(A,F,D)
 \tkzMarkRightAngle(A,E,B)
 \tkzMarkRightAngle(A,K,C)
 \end{scope}

  \foreach \point/\position in {A/left,B/below,C/below,S/above,D/right,E/left,D/right,F/right,K/above right,O/below,I/below}
 {
    \fill (\point) circle (1.5pt);
    \node[\position=3pt] at (\point) {$\point$};
 }

 \end{tikzpicture}
 \end{document}

Third way
Base on the answer Is there a command to find coordinates of projection of a point on a plane?
I defined command \def\VecMinus(#1,#2,#3)-(#4,#5,#6){(#1-#4,#2-#5,#3-#6)} and tried
\documentclass[border=3.14mm,12pt,tikz]{standalone}
\usepackage{tikz,tikz-3dplot}
%% smuggling from https://tex.stackexchange.com/a/470979/121799
\newcounter{smuggle}
\DeclareRobustCommand\smuggleone[1]{%
    \stepcounter{smuggle}%
    \expandafter\global\expandafter\let\csname smuggle@\arabic{smuggle}\endcsname#1%
    \aftergroup\let\aftergroup#1\expandafter\aftergroup\csname smuggle@\arabic{smuggle}\endcsname
}
\DeclareRobustCommand\smuggle[2][1]{%
    \smuggleone{#2}%
    \ifnum#1>1
    \aftergroup\smuggle\aftergroup[\expandafter\aftergroup\the\numexpr#1-1\aftergroup]\aftergroup#2%
    \fi
}

\def\parsecoord(#1,#2,#3)>(#4,#5,#6){%
    \def#4{#1}%
    \def#5{#2}%
    \def#6{#3}%
    \smuggle{#4}%
    \smuggle{#5}%
    \smuggle{#6}%
}
\def\SPTD(#1,#2,#3).(#4,#5,#6){#1*#4+#2*#5+#3*#6}
\def\VPTD(#1,#2,#3)x(#4,#5,#6){(#2*#6-#3*#5,#3*#4-#1*#6,#1*#5-#2*#4)}
\def\VecMinus(#1,#2,#3)-(#4,#5,#6){(#1-#4,#2-#5,#3-#6)}
\def\VecAdd(#1,#2,#3)+(#4,#5,#6){(#1+#4,#2+#5,#3+#6)}
\tikzset{intersection of line trough/.style args={#1 and #2 with plane
        containing #3 and normal #4}{%
        /utils/exec={\pgfmathsetmacro{\ltest}{abs(\SPTD#2.#4-\SPTD#1.#4)}
            \parsecoord#1>(\myAx,\myAy,\myAz)
            \parsecoord#2>(\myBx,\myBy,\myBz)
            \ifdim\ltest pt<0.01pt
            \typeout{Plane\space and\space line\space are\space parallel!\ltest}
            \pgfmathsetmacro{\myd}{0}
            \else
            \pgfmathsetmacro{\myd}{(\SPTD#3.#4-\SPTD#1.#4)/(\SPTD#2.#4-\SPTD#1.#4)}
            \fi
            %\typeout{({\myAx+\myd*(\myBx-\myAx)},{\myAy+\myd*(\myBy-\myAy)},{\myAz+\myd*(\myBz-\myAz)})}
            \def\myP{({\myAx+\myd*(\myBx-\myAx)},{\myAy+\myd*(\myBy-\myAy)},{\myAz+\myd*(\myBz-\myAz)})}
            \smuggle\myP},
        insert path={%
            \myP}
}}

\begin{document}
    \tdplotsetmaincoords{75}{110}
    \begin{tikzpicture}[tdplot_main_coords,scale=1.5]
    \pgfmathsetmacro\a{3}
    \pgfmathsetmacro\b{4}
    \pgfmathsetmacro\h{5}

    % definitions
    \path
    coordinate(A) at (0,0,0)
    coordinate (B) at (\a,0,0)
    coordinate (C) at (\a,\b,0)
    coordinate (D) at (0,\b,0)
    coordinate (S) at (0,0,\h);
    \def\mynormal{\VecMinus(\a,\b,0)-(0,0,\h)}
    \typeout{\mynormal:(\a,\b,-\h)}
    \path[intersection of line trough={(0,0,\h) and (\a,0,0) with plane containing (0,0,0) and normal (\a,\b,-\h)}]  coordinate (E)
    [intersection of line trough={(0,0,\h) and  (0,\b,0) with plane containing (0,0,0) and normal (\a,\b,-\h)}]  coordinate (F)
    [intersection of line trough={(0,0,\h) and  (\a,\b,0) with plane containing (0,0,0) and normal (\a,\b,-\h)}]  coordinate (K);

    \draw[dashed, thick]
    (A) -- (B)   (D)--(A) (S)--(A);
    \draw[dashed, thick]
    (E) --(A)  -- (F);
    \draw[ultra thick]
    (S) -- (B) -- (C) -- (D)--cycle (S)--(C);

    \draw [thick, dashed] (A) -- (K) (A) -- (C) (B) -- (D) (E) -- (F) ;
    \draw [thick] (E) -- (K) -- (F) ;

    \foreach \point/\position in {A/left,B/below,C/below,S/above,D/right,E/left,D/right,F/right,K/above right}
    {
        \fill (\point) circle (1.5pt);
        \node[\position=3pt] at (\point) {$\point$};
    }

    \end{tikzpicture}
        \end{document}

I got

A: I am sorry, my original code has a flaw. I simply forgot to put brackets around the scalar products like \SPTD#3.#4 and so on. And when testing this in the update to the previous answer, this did not matter. Once one adds these brackets, one gets
\documentclass[border=3.14mm,12pt,tikz]{standalone}
\usepackage{tikz,tikz-3dplot}
%% smuggling from https://tex.stackexchange.com/a/470979/121799
\newcounter{smuggle}
\DeclareRobustCommand\smuggleone[1]{%
    \stepcounter{smuggle}%
    \expandafter\global\expandafter\let\csname smuggle@\arabic{smuggle}\endcsname#1%
    \aftergroup\let\aftergroup#1\expandafter\aftergroup\csname smuggle@\arabic{smuggle}\endcsname
}
\DeclareRobustCommand\smuggle[2][1]{%
    \smuggleone{#2}%
    \ifnum#1>1
    \aftergroup\smuggle\aftergroup[\expandafter\aftergroup\the\numexpr#1-1\aftergroup]\aftergroup#2%
    \fi
}

\def\parsecoord(#1,#2,#3)>(#4,#5,#6){%
    \def#4{#1}%
    \def#5{#2}%
    \def#6{#3}%
    \smuggle{#4}%
    \smuggle{#5}%
    \smuggle{#6}%
}
\def\SPTD(#1,#2,#3).(#4,#5,#6){((#1)*(#4)+1*(#2)*(#5)+1*(#3)*(#6))}
\def\VPTD(#1,#2,#3)x(#4,#5,#6){((#2)*(#6)-1*(#3)*(#5),(#3)*(#4)-1*(#1)*(#6),(#1)*(#5)-1*(#2)*(#4))}
\def\VecMinus(#1,#2,#3)-(#4,#5,#6){(#1-1*(#4),#2-1*(#5),#3-1*(#6))}
\def\VecAdd(#1,#2,#3)+(#4,#5,#6){(#1+1*(#4),#2+1*(#5),#3+1*(#6))}
% the line is given by \vec x = \vec \ell_0 + t \vec \ell
% the points in the plane fulfill (\vec P_0 - \vec x)\cdot\vec n =0
% inserting the line equation in the plane equation gives
% (\vec Q - \vec \ell_0 - d \vec \ell)\cdot \vec n = 0
% solving for d yields
% d = (\vec Q \cdot \vec n - \vec \ell_0\cdot\vec n)/(\vec\ell\cdot \vec n)
%
% in the macro \vec \ell_0 = #1 , \vec \ell = #2 - #1
% #3 : \vec Q and #4 : \vec n
% so d=(#3.#4-#1.#4)/(#2.#4-#1.#4)
% and \vec P = \vec \ell_0 + d * \vec \ell = #1 + d * (#2-#1)
\tikzset{intersection of line trough/.style args={#1 and #2 with plane
        containing #3 and normal #4}{%
        /utils/exec={\pgfmathsetmacro{\ltest}{abs(\SPTD#2.#4-(\SPTD#1.#4))}
            \parsecoord#1>(\myAx,\myAy,\myAz)
            \parsecoord#2>(\myBx,\myBy,\myBz)
            \ifdim\ltest pt<0.01pt
            \typeout{Plane\space and\space line\space are\space parallel!\ltest}
            \pgfmathsetmacro{\myd}{0}
            \else
            \pgfmathsetmacro{\myd}{((\SPTD#3.#4)-(\SPTD#1.#4))/((\SPTD#2.#4)-(\SPTD#1.#4))}
            \fi
            %\typeout{({\myAx+\myd*(\myBx-\myAx)},{\myAy+\myd*(\myBy-\myAy)},{\myAz+\myd*(\myBz-\myAz)})}
            \def\myP{({\myAx+\myd*(\myBx-\myAx)},{\myAy+\myd*(\myBy-\myAy)},{\myAz+\myd*(\myBz-\myAz)})}
            \smuggle\myP},
        insert path={%
            \myP}
}}

\begin{document}
    \tdplotsetmaincoords{75}{110}
    \begin{tikzpicture}[tdplot_main_coords,scale=1.5]
    \pgfmathsetmacro\a{3}
    \pgfmathsetmacro\b{4}
    \pgfmathsetmacro\h{5}

    % definitions
    \path
    coordinate(A) at (0,0,0)
    coordinate (B) at (\a,0,0)
    coordinate (C) at (\a,\b,0)
    coordinate (D) at (0,\b,0)
    coordinate (S) at (0,0,\h);
    \def\mynormal{\VecMinus(\a,\b,0)-(0,0,\h)}
    \typeout{\mynormal:(\a,\b,-\h)}
    \path[intersection of line trough={(0,0,\h) and (\a,0,0) with plane containing (0,0,0) and normal (\a,\b,-\h)}]  coordinate (E)
    [intersection of line trough={(0,0,\h) and  (0,\b,0) with plane containing (0,0,0) and normal (\a,\b,-\h)}]  coordinate (F)
    [intersection of line trough={(0,0,\h) and  (\a,\b,0) with plane containing (0,0,0) and normal (\a,\b,-\h)}]  coordinate (K);

    \draw[dashed, thick]
    (A) -- (B)   (D)--(A) (S)--(A);
    \draw[dashed, thick]
    (E) --(A)  -- (F);
    \draw[ultra thick]
    (S) -- (B) -- (C) -- (D)--cycle (S)--(C);

    \draw [thick, dashed] (A) -- (K) (A) -- (C) (B) -- (D) (E) -- (F) ;
    \draw [thick] (E) -- (K) -- (F) ;

    \foreach \point/\position in {A/left,B/below,C/below,S/above,D/right,E/left,D/right,F/right,K/above right}
    {
        \fill (\point) circle (1.5pt);
        \node[\position=3pt] at (\point) {$\point$};
    }

 \end{tikzpicture}
\end{document}

This agrees with what you got with your other very nice methods. Sorry for the confusion!