Q:

A reference request for linear iterations with "rounding"

Given a vector $x$, define $[x]$ to be the vector obtained by rounding each
entry of $x$ to the nearest integer. For definiteness, lets assume that midpoints round up, e.g., $2.5$ rounds to $3$.
I would appreciate pointers to any literature which analyzes
dynamical systems of the form
$$ x(t+1) = A x(t) + B [x(t)].$$
Here $A,B$ are fixed matrices.
I would like to find out what is known about such systems. Unfortunately, I don't
even know what keywords to search for. Pointers to even tangentially
related literature would be very welcome!

A:

The dynamical system you have presented is in the class of discrete-time piecewise-affine (PWA) dynamical systems, and they are notoriously hard to analyze. The general form of a discrete-time PWA system is:
$x^+ = A_i x + B_i u + c_i$, for $x \in \Omega_i \subset \mathbb{R}^n$
where $x \in \mathbb{R}^n$ is the state vector, $u \in \mathbb{R}^m$ is the input vector, $c_i$ is a constant vector, and $\Omega_i$ is a region of the state-space. Note that $x^+$ is the updated state vector. Essentially, we have different affine dynamical systems on different "patches" of the state-space $\mathbb{R}^n$. This has been studied quite a bit in the past couple of decades by the control theory community. A good paper for you to start would be:

Analysis of discrete-time piecewise affine and hybrid systems (2002)

Another way of looking at the dynamical system you presented is to think of it as a linear dynamical system with quantized feedback. The following paper by Brockett might interest you too:

Quantized Feedback Stabilization of Linear Systems (2000)

However, your dynamical system is PWA over an infinite number of patches, and I do believe that the PWA systems literature considers only dynamical systems over a finite number of patches.


Q:

jQuery ui dialog box appears off view port

I am using jQuery ui dialog, when the page height is longer that view port height, vertical scroll bar will appear, then, when user scroll the page, the dialog will get off view port area ..
Is there an option to make the dialog always within the viewport area no matter the scroll offset is?

A:

Position:fixed; Might be what you are looking for.


Q:

The difference between modeling hierarchies in normalized and dimensional data modeling

I have trouble understanding the differences between modeling hierarchies in normalized and dimensional data modeling? I will very much appreciate your time and answers.

A:

In a normalized schema for a transactional database, a hierarchy might look like this:
create table geopolitical_area (
  id bigint primary key,
  type text not null,
  name text not null,
  code char(2),
  parent_id bigint null references geopolitical_area(id)
);

insert into geopolitical_area values
(1, 'Country', 'Canada', 'CA', null),
(2, 'Region', 'British Columbia', 'BC', 1);

Note the foreign key to the same table.
In a dimensional schema for a data warehouse, a hierarchy might look like this:
create table dim_customer (
  id bigint,
  name text,
  country_name text,
  country_code char(2),
  region_name text,
  region_code char(2) ...
);

insert into dim_customer values
(666, 'Neil McGuigan', 'Canada', 'CA', 'British Columbia', 'BC' ...);

Notice that the hierarchy has been flattened.
Often, you analyze a data warehouse using OLAP, where you would tell your OLAP server about the country > region hiearchy.
For example, in Mondrian OLAP server, a hierarchy might look like this:
<Dimension name="location">
  <Hierarchy>
    <Table name="dim_customer" />
    <Level name="Country" column="country_code" nameColumn="country_name" />
    <Level name="Region" column="region_code" nameColumn="region_name" />
  </Hierarchy>
</Dimension>


Q:

nullPointerException when call custom list view manager

i want to use custom list view.first,i create a java class named Main List with two variable (name , image).
this class code :
public class MainList {
    private String name;
    private String image;

    public MainList(String name, String image) {
        this.setName(name);
        this.setImage(image);
    }
public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getImage() {
        return image;
    }

    public void setImage(String image) {
        this.image = image;
    }
}

then i create ListManager class extends BaseAdapter , this class code:
public class ListManager extends BaseAdapter {
    private Context context;
    private ArrayList<MainList> list;
    private LayoutInflater inflater;

    public ListManager(Context context, ArrayList<MainList> list) {
        this.setContext(context);
        this.setList(list);
    }

    @Override
    public int getCount() {
        return list.size();
    }

    @Override
    public Object getItem(int i) {
        return i;
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        try {
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            viewHolder viewHolder = new viewHolder();

            if(view == null){
                inflater.inflate(R.layout.list,null);
                viewHolder.name = (TextView) view.findViewById(R.id.listTitle);
                viewHolder.image = (ImageView) view.findViewById(R.id.listImage);
            }else viewHolder = (viewHolder) view.getTag();

            if (list.size() > 0){
                MainList mainList = list.get(i);
                viewHolder.name.setText(mainList.getName());
            }
        }catch (Exception e){
            Log.i("Tag:LM", "getView: " + e.toString());
        }

        return view;
    }

    public Context getContext() {
        return context;
    }

    public void setContext(Context context) {
        this.context = context;
    }

    public ArrayList<MainList> getList() {
        return list;
    }

    public void setList(ArrayList<MainList> list) {
        this.list = list;
    }
    private static class viewHolder{
        private TextView name;
        private ImageView image;
    }
}

*i just set TextView for test my code . after create this classes , use in list activity , this class code :
public class ListActivity extends AppCompatActivity {

    private ListView listView;
    private ListManager adapter;
    private ArrayList<MainList> arrayList;
    private static final String TAG = "Tag:ListActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_list);
        try {
            listView = (ListView) findViewById(R.id.list);

            setData();

            adapter = new ListManager(this, arrayList);

            listView.setAdapter(adapter);
        }catch (Exception e){
            Log.i(TAG, "onCreate: "+e.toString());
        }
    }
    private void setData(){
        MainList mainList = new MainList("all","khddai");
        MainList mainList1 = new MainList("sf","khddai");
        MainList mainList2 = new MainList("adfdli","khdfai");
        MainList mainList3 = new MainList("aldi","khdfai");

        arrayList.add(mainList);
        arrayList.add(mainList1);
        arrayList.add(mainList2);
        arrayList.add(mainList3);
    }
}

android log cat:
07-20 14:53:15.240 9861-9861/com.package.app I/Tag:ListActivity: onCreate: java.lang.NullPointerException

A:

In ListActivity private ArrayList<MainList> arrayList; you didn't create object. with out using object you are using that variable in setData() method.
create object in class variable like this,
private ArrayList<MainList> arrayList = new ArrayList<>();

or
before adding it to list in setData like this
private void setData(){
        arrayList = new ArrayList<>();
        MainList mainList = new MainList("all","khddai");
        MainList mainList1 = new MainList("sf","khddai");
        MainList mainList2 = new MainList("adfdli","khdfai");
        MainList mainList3 = new MainList("aldi","khdfai");

        arrayList.add(mainList);
        arrayList.add(mainList1);
        arrayList.add(mainList2);
        arrayList.add(mainList3);
    }

and another issue as SRB bans mention, you should create view before getting the child, you missed to get a view after getting from Layout inflator view = inflater.inflate(R.layout.list,null);
public View getView(int i, View view, ViewGroup viewGroup) {
        try {
            inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            viewHolder viewHolder = new viewHolder();

            if(view == null){
                view = inflater.inflate(R.layout.list,null);
                viewHolder.name = (TextView) view.findViewById(R.id.listTitle);
                viewHolder.image = (ImageView) view.findViewById(R.id.listImage);
                view.setTag(viewHolder);
            }else viewHolder = (viewHolder) view.getTag();

            if (list.size() > 0){
                MainList mainList = list.get(i);
                viewHolder.name.setText(mainList.getName());
            }
        }catch (Exception e){
            Log.i("Tag:LM", "getView: " + e.toString());
        }

        return view;
    }


Q:

I have filled my jtable using following code but i m not able to set header of the column of the table

ResultSet rs = statment.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));

A:

I think you cannot set column names which are selected from a database, but you can copy data out of that column in a new column and set the name of that new column.
Or else you can get that column name using this code.. :)
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
String name = rsmd.getColumnName(1);

Where 1 is the index of the column.


Q:

How to search with cypher 2.0 case insensitive?

How to search with cypher 2.0 / Neo4j 2.1.7 case insensitive on a indexed field?

regex does not use index WHERE a.X =~ ('(?i)' + b.Y) ...
using lower() does not use index WHERE lower(a.X) = lower(b.Y) ...
adding a extra field with lower case property value for indexing is ugly

Not using the index will result in more them 2 mio DB Hits.

A:

For fulltext search using legacy indexes with Neo4j 2.x which is also case-insensitive check my blog post:
http://jexp.de/blog/2014/03/full-text-indexing-fts-in-neo4j-2-0/


Q:

Problems with JComboBox

import javax.swing.*;
import java.awt.*;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;

public class Test1{
    JComboBox combo;
    JTextField txt;

    public static void main(String[] args) {
        Test1 b = new Test1();
    }

    public Test1(){
        String degrees[] = {"AAS1","AAS2","AAS1","AAS3"};
        JFrame frame = new JFrame("Creating a JComboBox Component");
        JPanel panel = new JPanel();

        combo = new JComboBox(degrees);
        combo.setEditable(true);
        combo.setBackground(Color.gray);
        combo.setForeground(Color.red);

        txt = new JTextField(10);
        txt.setText("1");

        panel.add(combo);
        panel.add(txt);
        frame.add(panel);

        combo.addItemListener(new ItemListener(){
            public void itemStateChanged(ItemEvent ie){
                txt.setText(String.valueOf(combo.getSelectedIndex()+1));
            }
        });

        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setSize(400,400);
        frame.setVisible(true);

    } }

As you see from the code above. I have JComboBox with 4 items. If there are no items that are same everything is OK.
But in my example ("AAS1","AAS2","AAS1","AAS3") first and third items are same, and I have problems in this case.
When I select any item I want to get it's index in JTextField, but when I select third item I get index of first item.
Has any idea?

A:

That's because JComboBox is using equals to check the item equality. In your case, those two String are equal so it returns the first index that match. If you really need to do that, you might need to define your own item class like this:
private static class MyItem {
    private String value;

    public MyItem(String value) {
        this.value = value;
    }

    public String getValue() {
        return value;
    }

    @Override
    public String toString() {
        return value; //this is what display in the JComboBox
    }
}

And then add the item like this:
MyItem degrees[] = {new MyItem("AAS1"),new MyItem("AAS2"),new MyItem("AAS1"),new MyItem("AAS3")};
JComboBox combo = new JComboBox(degrees);


Q:

Direction of infinite plate when calculating the potential difference

Given the setting,

What is the potential difference between point $Q, ( {q ~\rm cm} , {0~\rm cm} )$ and point $P, ( {p~\rm cm} , {0~\rm cm})$? Let $q = 17.2~\rm cm$ and  $p = 2~\rm cm$.

When solving this problem, I know we have to find $E=\frac{\sigma}{2\epsilon_0}$ for each infinite plate. However, I am not sure about the direction of each infinite plate. The solution indicates that the $σ_1$ points right and $σ_2$ point left. How do we know that?

A:

The solution indicates that the σ1 points right and σ2 point left. How do we know that?

The charge on each plate is positive. The electric field due to a positive charge points away from that charge.
Therefore the field due to each plate points to the left on the left side of the plate, and to the right on the right side of the plate.


Q:

Generate code for multiple swaggers in the same project

How do i generate code for multiple swagger files from within the same module/project in one pom.xml.
In my application client had provided a swagger and we have one of the backend API to be called for which they provided swagger. I want to generate code for both of these in the same project. One way i was thinking is create separate module and execute the plugin separately and have those dependencies called out in main module.
How do i generate code from one build plugin? Please point me to existing one if it is a repost. I couldn't find any.
Here is the plugin i configured in pom.xml
 <plugin>
            <groupId>io.swagger</groupId>
            <artifactId>swagger-codegen-maven-plugin</artifactId>
            <version>2.2.1</version>
            <executions>
                <execution>
                    <goals>
                        <goal>generate</goal>
                    </goals>
                    <configuration>
                      <inputSpec>${project.basedir}/src/main/ resources/Service.json</inputSpec><inputSpec>${project.basedir}/src /main/resources/Client.json</inputSpec>
                        <language>java</language>
                        <configOptions>
                            <dateLibrary>java8</dateLibrary>
                        </configOptions>
                        <modelPackage>com.service.model</modelPackage>
                        <environmentVariables>
                            <models/>
                            <supportingFiles>false</supportingFiles>
                        </environmentVariables>
                    </configuration>
                </execution>
            </executions>
        </plugin>

Also tried *.json. At anytime it is taking only one json file and generating the code.

A:

In order to do this you could declare a different execution for each json file, each one should have a unique id.
Here is an example with two executions, execution-first-json for the file first.json and execution-second-json for the file second.json
<plugin>
    <groupId>io.swagger</groupId>
    <artifactId>swagger-codegen-maven-plugin</artifactId>
    <version>2.2.1</version>
    <executions>
        <execution>
            <id>execution-first-json</id>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
              <inputSpec>${project.basedir}/src/main/resources/first.json</inputSpec>
                <language>java</language>
                <configOptions>
                    <dateLibrary>java8</dateLibrary>
                </configOptions>
                <modelPackage>com.service.model</modelPackage>
                <environmentVariables>
                    <models/>
                    <supportingFiles>false</supportingFiles>
                </environmentVariables>
            </configuration>
        </execution>
        <execution>
            <id>execution-second-json</id>
            <goals>
                <goal>generate</goal>
            </goals>
            <configuration>
              <inputSpec>${project.basedir}/src/main/resources/second.json</inputSpec>
                <language>java</language>
                <configOptions>
                    <dateLibrary>java8</dateLibrary>
                </configOptions>
                <modelPackage>com.service.model</modelPackage>
                <environmentVariables>
                    <models/>
                    <supportingFiles>false</supportingFiles>
                </environmentVariables>
            </configuration>
        </execution>
    </executions>
</plugin>


Q:

C++/cli recognizing transitions between managed/unmanaged and measuring their cost

I am still fairly new to C++/cli and am not always sure when I am writing something whether I am doing something that creates a transition between managed and unmanaged run times. For instance I cannot add a LARGE_INTEGER or a std::vector as a member of a managed class, but I can use either in the middle of a managed method, but I don't know whether doing so creates a transition between managed and unmanaged runtimes. How can I see every point at which I am forcing a transition to be made and how can I measure the cost of those transitions?
One possibility that occurs to me is that I expect there is a "transition to unmanaged" and a "transition to managed" block of code in windows. Are there symbols for those I can put breakpoints at, e.g. with windbg so I can see each transition? Is there a way to get visual studio to show you each transition at runtime?
To measure the inpact when there are many transitions, are there corresponding event tracing for windows events that I can see with xperf, or performance counters for them I can see with perfmon?

A:

"Unmanaged runtime" is a bit of an oxymoron.  Unmanaged code doesn't run in a virtual machine.  Plus, the managed runtime is itself unmanaged code.  I think you're interested in code in general, not just the CLR and standard libraries, but ultimately everything is native code, some of it was created by the CLR JIT and some of it was created by a native compiler but it's all native code in the end.  There's even a common exception handling model (SEH) for both .NET and native exceptions (or more precisely, .NET uses the OS-provided exception model).
After the JIT runs, there's not much sign of managed->unmanaged transitions, since they're just a simple function call (the debugger can tell the difference because the unmanaged code is in the address space of a native library, and the JIT-compiled managed code is in a dynamic address space owned by the JIT).  The reverse direction is slightly more involved, since the call instruction was created before the code it calls, it has to be an indirect call (via function pointer).  But it's still a pointer direct to JIT-compiled code, not to some single unmanaged->managed thunk where you could put a breakpoint.  Actually, the function pointer probably starts out pointing to the JIT itself, which figures out what method is being called, compiles it, updates the function pointer, and finally tail-calls to the destination just as if it had been called in the first place.
This is the magic of C++ interop.  It also means that managed->unmanaged transitions are really not even worth worrying about.  Profile and find out what code paths are expensive, and if it turns out to be a call between managed and unmanaged code, optimize it then.  But don't go randomly looking for managed/unmanaged transitions.
Now, there are other reasons you might want to look for all managed/unmanaged transitions.  For example, the garbage collector can interrupt any thread running managed code (again, the code actually running is native code, but the GC can identify it because it's inside the memory space used by the JIT, and the JIT produced object usage tables detailing what stack variables are reachable objects at any given instruction pointer).  So if you want to guarantee that a certain thread is NEVER stopped by the garbage collection, you'd need to hunt down and eliminate all unmanaged->managed transitions in the functions which run in that thread.  Breakpoint injection still wouldn't be the right approach, even if there was a place to put the breakpoint, since that only catches transitions actually taken, not those that are conditional.


Q:

Database created from Code first shows in Server Explorer and not in SQL Server Object Explorer

Database 'EFCheck' (Created by Entity Framework code first) is showing in Server Explorer and not in SQL Server Object Explorer and I'm not seeing the created database in my SQL Server. Can anyone tell me where I can see the new db in SQL Server ?
Server Explorer where I see the new EFCheck db created by EF
SQL Server Object Explorer where I don't see the EFCheck db
My connection string in Web.Config
<connectionStrings>
    <add name="Db"
         connectionString="Data Source=ABHI\SQLEXPRESS;Integrated Security=True"
         providerName="System.Data.SqlClient" />
</connectionStrings>

DbContext
public class Db : DbContext {
   public Db() : base("name=Db") { }
   public virtual DbSet<Blog> Blogs { get; set; }
   public virtual DbSet<Post> Posts { get; set; }
}

A:

You didn't specify the Initial Catalog in your connection string.You have to set the Initial catalog as shown below.
<add name="Db"
connectionString="Data Source=ABHI\SQLEXPRESS;
Initial Catalog=Your-Db-Name-Should-Be-Set-Here;
Integrated Security=True" providerName="System.Data.SqlClient"/>


Q:

IntelliJ - Angular - How to diagram only the modules?

I am using the latest Ultimate Edition of IntelliJ and am attempting to generate a useful diagram for a project I am on that does not have any documentation. I am doing this to make it easy to see what all of the modules are and what modules they interact with.
The problem that I am running into is that everything that is imported is being generated into the diagram making it much larger than needed.
I would like to limit the diagramming to only MODULES and not everything else.
I was able to figure out that I can click all of the Modules I want and then diagram from those to see what they interact with but still am getting too many additional pieces in my diagram.
IntelliJ does not directly address this information in their help page: https://www.jetbrains.com/help/idea/project-module-dependencies-diagram.html#view_module_diagram
Does anyone know how I might get the diagram size reduced by only showing Modules?
Trying to export sometimes fails because of a memory issue.
Sadly my home system I built 10 years ago has more processing power than this newer machine at work.

Just a tip to anyone out there. Ways to diagram

Right Click on a folder and select Diagrams -> Show Diagram... (Not the best option)
Select one or more files then Right Click on a folder and select Diagrams -> Show Diagram...

* ---------------- *
* A tool suggested to me from a comment below that does the job! *
* Compodoc *
* ---------------- *

What is Compodoc ?
Compodoc is a documentation tool for Angular applications. It
  generates a static documentation of your application.

A:

There is unfortunately no way to do this in IDEA. Please vote for WEB-35691 and linked tickets to be notified on any progress with them


Q:

Removing attributes in jquery

How to remove multiple attributes of an element ?Jquery documentation has only mentioned about removing a single attribute at a time.Take a reference here

A:

The link you supplied states clearly the following about the parameter for removeAttr.

An attribute to remove; as of version 1.7, it can be a space-separated list of attributes.


Q:

Class diagram - how to document echo

Can i draw a UML class diagram that some how explain that my function do not return value, but rather echo it?
Here is an pseudoísh example of what my class looks like:
class api {
  private $data;

  public function dosomething() {
    $data = $this->getDataFromDatabase();
    echo json_encode($data);
  }

  private function getDataFromDatabase() {
    ....
  }

}

Here is a class diagram that shows my class above.
-----------------------------------
            api
-----------------------------------
    - data : string
-----------------------------------
    + dosomething() : void
    - getDataFromDatabase() : array
-----------------------------------

A:

You can either use : void or leave it away to show that it does not return anything. So the above is ok and alternatively you could write
-----------------------------------
            api
-----------------------------------
    - data : string
-----------------------------------
    + dosomething()
    - getDataFromDatabase() : array
-----------------------------------


Q:

Trying to get spark streaming to read data stream from website, what is the socket?

I am trying to get this data http://stream.meetup.com/2/rsvps into spark stream
They are JSON objects, I know the lines will be strings, I just want it to work before I try JSON.
I am not sure what to put as the port, I assume that is the problem.
SparkConf conf = new SparkConf().setMaster("local[2]").setAppName("Spark Streaming");

JavaStreamingContext jssc = new JavaStreamingContext(conf, Durations.seconds(1));

JavaReceiverInputDStream<String> lines = jssc.socketTextStream("http://stream.meetup.com/2/rsvps", 80);

lines.print();

jssc.start();
jssc.awaitTermination();

Here is my error
java.net.UnknownHostException: http://stream.meetup.com/2/rsvps
    at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:178)
    at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
    at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
    at java.net.Socket.connect(Socket.java:579)
    at java.net.Socket.connect(Socket.java:528)
    at java.net.Socket.<init>(Socket.java:425)
    at java.net.Socket.<init>(Socket.java:208)

A:

The socketTextStream isn't designed to work as an http client. As you noticed, you will need to create a custom receiver, one potential place to start is based on the receiver created as part of the meetup streaming data source (see https://github.com/actions/meetup-stream/blob/master/src/main/scala/receiver/MeetupReceiver.scala ).


Q:

Can we bypass connection?

I am new to differential geometry. It is surprising to find that the linear connection is not a tensor, namely, not coordinate-independent.
Can we bypass this ugly object? Only intrinsic quantities should appear in a textbook.

A:

As mentioned in a previous answer, connections are quite intrinsic. I will take the slightly more pedestrian view that a connection is a collection of maps from type $(k,l)$ tensor fields to type $(k,l+1)$ fields that is linear, satisfies a Leibniz rule, commutes with contraction, agrees with the differential for smooth functions and is usually assumed to be torsion free in the sense that $\nabla_a\nabla_bf = \nabla_b \nabla_a f$, where small latin indices are used in the abstract index sense (apologies to those who use precisely the opposite), so that second covariant derivatives of smooth functions are symmetric.
Now suppose we have two connections $\nabla$ and $\tilde{\nabla}$. We already know that $(\nabla - \tilde \nabla) f = 0$ for any smooth function. Now suppose we have a one form $\omega_a$. Then we can compute that
$$ (\nabla_b - \tilde \nabla_b)(f\omega_a) = f[(\nabla_b - \tilde \nabla_b)(\omega_a)] $$
as a result of the Leibniz rule. This means that $\omega_a \to (\nabla_b - \tilde \nabla_b)(\omega_a)$ is linear over $C^\infty(M)$, and thus is characterized by some type $(1,2) $ tensor $C^c_{ab}$ such that $(\nabla_b - \tilde \nabla_b)(\omega_a) = \omega_c C^c_{ab}$. The difference between the two actiong on arbitrary fields can now be expressed by various signed sums of contractions with $C^c_{ab}$
Now, there are particular connections $\nabla$ that we want to be able to compute with, e.g. Levi-Civita, which are defined in terms of intrinsic properties of $M$. But the only connections we really know how to write down easily are the flat connections $\tilde\nabla$ associated to a fixed coordinate chart. In this case, we often write $C^c_{ab} = \Gamma^c_{ab}$, which are the Christoffel symbols. Note that the "ugliness" of these symbols has to do with the fact that the flat connections are not coordinate independent, thus for different coordinate charts one generally has a different correction tensor $C^c_{ab}$, which leads to the saying which rather peeved a physics professor of mine that the Christoffel symbols are not a tensor.
Additionally, it seems rather strange to say that we should never present anything extrinsic. I suppose it is possible that everything could be derived from purely intrinsic computation, but that seems strange. In particular the use of differential geometry has many practical uses where we really would like to be able to numerically compute,say, the path of a geodesic.

A:

Connections are not tensors, but that does not mean they are not coordinate-independent objects! A linear connection is a map sending two vector fields $X,Y$ to another vector field $\nabla_X Y$ which satisfies the rules $\nabla_{fX+Z} Y = f \nabla_X Y + \nabla_Z Y$ and $\nabla_X (fY + Z) = f\nabla_X Y + (\nabla_X f)Y + \nabla_X Z$. This is an abstract definition that makes no reference whatsoever to coordinates.
The connection coefficients or Christoffel symbols $\Gamma^i_{jk} = (\nabla_j\partial_k)^i$ describe how the connection acts on a given coordinate basis. This object $\Gamma$ is not a tensor precisely due to the second rule above: it satisfies a product rule rather than full bilinearity. (Indeed this is necessary if we want something that behaves like a derivative - tensors act pointwise and thus cannot distinguish constants from non-constants!) This does not mean it's not intrinsic - it just means that its components in different coordinate systems are not related in the same way that those of tensors are.

A:

In contrast to what is written in the question and some of the comments, a connection is independent of coordinates.
The intrinsic way to define connections is the following. For simplicity, we treat only connections on the tangent bundle, even though a similar definition can be applied for any vector bundle. Let $M$ be a smooth manifold. Let $TM$ denote the tangent bundle to $M$, let $\Gamma(TM)$ denote the space of vector fields on $M$, and let $\mathrm{end}(TM)$ denote the space of vector bundle morphisms from $TM$ to itself. A connection on $M$ is a map$$\nabla:\Gamma(TM)\to\mathrm{end}(TM),$$which is additive and satisfies the Leibniz rule. Additivity should be clear enough, and the Leibniz rule means that we have $$\nabla fX=df\cdot X+f\nabla X,$$for any smooth function $f$ and a vector field $X$.
It is customary to use the notation $\nabla_YX$ for $\nabla(X)(Y)$. Using this notation, additivity means $$\nabla_Y(X_1+X_2)=\nabla_YX_1+\nabla_YX_2,$$while the Leibniz rule takes the form$$\nabla_YfX=df(Y)\cdot X+f\nabla_YX.$$As written above, this is perfectly intrinsic. Now, in some schools this intrinsic approach is neglected, and connections are introduced only via the Christoffel symbols. Naturally, the Christoffel symbols depend on coordinates, but this actually means nothing.


Q:

AngularJS 2 way Data Binding not working?

<!DOCTYPE html>

    <title>TheNetNinja Angular Playlist</title>
    <link href="content/css/styles.css" rel="stylesheet" type="text/css" />

    <input type="text" ng-model="favMeat" placeholder="enter your fav meat" />

Your fav meat is: {{ favMeat }}

The text box and the words below it are showing up, but the 'favMeat' value is not showing up when I type in the text box. I'm also running this on a local server built into the atom text editor. I would guess it has something to do with my src files? If I comment out the second src it still doesn't work.

A:

First of all there is no angularjs2 , its just angular 1.x or angular 2/4/5/6.
Just remove the duplicate reference to angular.js
Anyhow the above code works,

<!DOCTYPE html>

    <title>TheNetNinja Angular Playlist</title>
    <link href="content/css/styles.css" rel="stylesheet" type="text/css" />

    <input type="text" ng-model="favMeat" placeholder="enter your fav meat" />

Your fav meat is: {{ favMeat }}


Q:

Converting Model in Plug-in in QGIS

Recently, I started making a model on QGIS and now I want to transform it into a plug-in, but it seems that I have to change the code to do it, otherwise it won't work.

What changes are required to perform this conversion?

A:

To create a plugin from a model, use the "Plugin Builder" plugin.
By following THIS tutorial, you can build a basic structure.
On the third screen for plug-in creation, define the template as Process Provider. The model conversion is easier in this mode.
You will not need to use QT Creator or compile.bat described in the above link tutorial.
After you create your empty plugin, export your model as a Python script using QGIS version 3.6 or higher.
Save the created script.

In the folder where it was created the empty plugin, there are 5 basic files that should be edited. Keep the others as they are.
If your plugin has only one function, edit only the fourth file, use the default lines as examples:
This is a example of a plugin with 2 functions.
1- PluginNAME.py
You need to create a class for each function (model) that will be displayed, simply change the class name and self.provider in initProcessing.
class NewModelPlugin(object):

    def __init__(self):
        self.provider = None

    def initProcessing(self):
        self.provider = NewModelProvider()
        QgsApplication.processingRegistry().addProvider(self.provider)

    def initGui(self):
        self.initProcessing()

    def unload(self):
        QgsApplication.processingRegistry().removeProvider(self.provider)

class Model2Plugin(object):

    def __init__(self):
        self.provider = None

    def initProcessing(self):
        self.provider = Model2Provider()
        QgsApplication.processingRegistry().addProvider(self.provider)

    def initGui(self):
        self.initProcessing()

    def unload(self):
        QgsApplication.processingRegistry().removeProvider(self.provider)

For example, the Buffer by Percentage plugin has two functions, so in it's code there are two classes.

2- __init__.py
This file references all Classes created in the previous file, create a new block for each function.
    from .PluginNAME import NewModelPlugin
    return NewModelPlugin()

    from .PluginNAME import Model2Plugin
    return Model2Plugin()

3- PluginNAME_provider.py
Indicates which algorithms will be loaded. In import, list all comma-separated algorithms. In loadAlgorithm, enter all, one on each line.
from qgis.core import QgsProcessingProvider
from .PluginNAME_algorithm import (NewModelAlgorithm, Model2Algorithm)

class PluginNAMEProvider(QgsProcessingProvider):

    def __init__(self):
        QgsProcessingProvider.__init__(self)

    def unload(self):
        pass

    def loadAlgorithms(self):
        self.addAlgorithm(NewModelAlgorithm())
        self.addAlgorithm(Model2Algorithm())

4- PluginNAME_algorithm.py
Here will be the code of each algorithm.
Initially you need to import all libraries that all algorithms will use. QGIS automatic conversion creates almost all,
you will know which ones are missing when trying to run.
Create a class (QgsProcessingAlgorithm) for each desired algorithm.They are independent of each other, so each must have its own variables and parameters.
It's in this file, in each class, that you define the displayed name, system name, description, and icon displayed in QGIS.
Replace everything from Class (line 41 by default) with the Class contents of your script generated from your model.
Change the name of this class and the last return to the same name defined in the previous file.
class NewModelAlgorithm(QgsProcessingAlgorithm):

    def initAlgorithm(self, config=None):
    .
    .
    .

    def createInstance(self):
        return NewModelAlgorithm()

class Model2Algorithm(QgsProcessingAlgorithm):

    def initAlgorithm(self, config=None):
    .
    .
    .

    def createInstance(self):
        return Model2Algorithm()

5- Metadata.txt
In this file is the information that will be displayed on the plugin manager screen such as name, version, changelog.
In order for your plugin to appear in QGIS, move the full folder created by PuginBuilder to your user's python folder,
usually in C:\Users\User\AppData\Roaming\QGIS\QGIS3\profiles\default\python\plugins.
In QGIS, go to Plugins > Manage and Install plugins and enable it in the Installed tab.
Your plugin should appear inside your toolbox.
Using IF.
If you need one model to be executed by another via an if structure in the _algorithm.py file, it will be inserted into processAlgorithm.
After the if, put the required code with one more tab.
class NewModelAlgorithm(QgsProcessingAlgorithm):

    def initAlgorithm(self, config=None):
    .
    .
    .

    def processAlgorithm(self, parameters, context, model_feedback):
        feedback = QgsProcessingMultiStepFeedback(55, model_feedback)
        results = {}
        outputs = {}
        if SOMETHING is None:
            PLACE YOUR CODE HERE
        elif OTHERSTUFF is not None:
            ANOTHER CODE HERE
        else:
            ONE MORE OPTION

All input and output parameters that will be used within the if must exist in the initAlgorithm section.


Q:

MySQL 'WHERE' clause which excludes results in subquery

I have the following SQL query:
SELECT members.member_ID, members.nick_name
          FROM orgs
    INNER JOIN assets ON assets.org_ID = orgs.org_ID
    INNER JOIN orgs_to_members ON orgs_to_members.org_ID = orgs.org_ID
    INNER JOIN members ON members.member_ID = orgs_to_members.member_ID
    where orgs.org_ID = '7'
    AND NOT EXISTS (select shares.member_ID from shares where shares.asset_ID = '224')

There are 3 members in org 7:
     - member_ID 1
     - member_ID 4
     - member_ID 6

In the subquery, member IDs 1 and 4 result. I am trying to write 1 query which will return only member ID #6. When i run the above query, I get no results. When I separate them, I get the expected results. Please help.
Thanks!

A:

AND NOT EXISTS (select ...) is used to make sure that the subquery doesn't return any rows. It usually only makes sense if the subquery is correlated (i.e., if it refers to values from the outer query), since otherwise it will either be true for every result row (and won't actually affect the query), or be false for every result row (and will cause the query to return no results at all, as in your case). I think what you want is:
    AND members.member_ID NOT IN (select shares.member_ID from shares where shares.asset_ID = '224')


Q:

How to tie entity recognition to intent prediction?

I'm having a problem with Rasa_NLU giving me the wrong entity for an intent.  An example is “How do I get to New York?” Where, I tagged the training data to name the entity “city”. In a different intent, it was tagged “destination”.
intent: check_weather
what is the weather in new york?

intent: get_directions
how do I get to new york?

I have a script that takes action on the intent returned and processes the entities. If I get back the get_directions intent, I’ll look in the json for the destination entity, but it has city instead. Using ner_crf, is there a way to de-emphasize entities in an intent, so that the classifier is biased to those that the intent was trained for? That is, the classifier would be weighted to giving a destination for get_directions, and a city for get_weather?
The typical answer I've found is to add more training examples. I'm up to 60 for each of the two intents I have, and it is still getting it wrong.

A:

As of right now, you can only featurize/unfeaturize all entities for a certain intent. I can see that that's not really your use case since both intents require entities -- just different ones. There is currently a community PR open to add per-intent featurization of specific entities, so it will be available in the future.


Q:

How to build a custom report from Google Sheets

I've googled to find out a way to build reports from data spreadsheets and it seems google data studio and google sheets are an option to achieve that.
Despite some experience on LibreOffice Calc, I am newcomer in Google Sheets and DataStudio.
The data I have in Google Sheets is:

The report I would like to build, whose have to update when new data will arrive in google sheet (let say, each day or so).

I just colored the field names (objId; objDesc; objMore; objProgress; taskId; taskDesc; taskMore; event) and sorted the data into spreadsheet to easy understanding what I want to achieve.
Appreciate your help.

A:

Solution

So basically you want to generate a report of a hierarchy of your objects, tasks and events in the described order whenever you click a button.

In this solution I have provided the code you will need for the most complicated part and then guidance for the rest of the steps.

Add a button to your sheet with the data in Insert->Drawing and draw your button.
Create a new sheet and insert the following formulas as shown in this picture:

=iferror(ArrayFormula(lookup(unique(Sheet1!A1:A),Sheet1!A1:A,row(Sheet1!A1:A)+1)))

and
=iferror(ArrayFormula(lookup(unique(Sheet1!E2:E),Sheet1!E2:E,row(Sheet1!E2:E)+1)))

These forumulas will basically detect any change in values in the designated columns (in our case the columns for the Object Ids and the Task Ids) which will be helpful for then generating the report.

After this head over the script editor and use the following function to generate an array of objects with the right data ordered hierarchically. The following piece of code contains self explanatory comments. This is the most tricky part and takes use of the previously created sheet to know where are our Object and Task Id changing and store the right information in the right place.

For this data:

This will be the generated object after running the function:
 [{ObjectId=1.0, 1={TaskId=S02, Events=[[3242.0]], TaskMore=ppp, Description=ppp}, 0={TaskId=S01, Description=qqq, Events=[[1.0], [23.0], [324.0]], TaskMore=qqq}, ObjectMore=aaaa, ObjectDesc=aaaa, 2={TaskMore=lll, Events=[[3.0]], TaskId=S03, Description=lll}, ObjectProgress=0.7}, {3={Description=www, Events=[[43.0]], TaskMore=www, TaskId=T01}, 5={TaskId=T03, Events=[[5.0]], TaskMore=ttt, Description=ttt}, ObjectMore=bbbb, 4={Description=eee, TaskId=T02, TaskMore=eee, Events=[[54.0], [4.0]]}, ObjectDesc=bbbb, 6={Description=yyy, Events=[[345.0], [343.0]], TaskId=T04, TaskMore=yyy}, ObjectProgress=0.33, ObjectId=2.0}]

function myFunction() {
  // Get sheets
  var sheetData = SpreadsheetApp.getActive().getSheetByName('Sheet1');
  var sheetHelp = SpreadsheetApp.getActive().getSheetByName('Sheet2');

  // This is the array where we will be storing our info
  var Objects = []
  // Get the ranges of values from our helper sheet that detect changes in that column
  var ObjectIds = sheetHelp.getRange(2, 1,sheetHelp.getLastRow(),1).getValues().flat();
  var TaskIds = sheetHelp.getRange(2, 2,sheetHelp.getLastRow(),2).getValues().flat();

  // Delete all the blank elements in the flaten array of values
  ObjectIds = ObjectIds.filter(item => item);
  TaskIds = TaskIds.filter(item => item);

  // Delete the last item as this would just be the change between a value and a blank cell
  ObjectIds.pop();
  TaskIds.pop();

  // Lets iterate through all our main objects detected
  for(i=0;i<ObjectIds.length;i++){
    // for each object insert its details and information
    Objects.push({
      ObjectId: sheetData.getRange(parseInt(ObjectIds[i]), 1).getValue(),
      ObjectDesc : sheetData.getRange(parseInt(ObjectIds[i]), 2).getValue(),
      ObjectMore : sheetData.getRange(parseInt(ObjectIds[i]), 3).getValue(),
      ObjectProgress : sheetData.getRange(parseInt(ObjectIds[i]), 4).getValue()
    });
    // for each object iterate through all its possible tasks
    for(j=0;j<TaskIds.length;j++){
      // get the last row value as for the last element of the tasks if we do not have anything it will
      // have issues in the following if condition if this is null
      var lastRow = sheetHelp.getLastRow();
      ObjectIds.push(lastRow);

      // If the task is within the object index range (i.e for an object between indices 8 and 12
      // his tasks are those between these indices as well
      if(TaskIds[j]<ObjectIds[i+1] && TaskIds[j]>=ObjectIds[i]){
        TaskIds.push(lastRow);

        // get all the events for this specific task checking that they are within the indices
        // of the task itself (only events that are within the index boundaries of the task
        var events = sheetData.getRange(TaskIds[j], 8,TaskIds[j+1]-TaskIds[j],1).getValues();

        // add the new task object
        Objects[i][j] = {
          TaskId : sheetData.getRange(parseInt(TaskIds[j]),5).getValue(),
          Description : sheetData.getRange(parseInt(TaskIds[j]),6).getValue(),
          TaskMore : sheetData.getRange(parseInt(TaskIds[j]),7).getValue(),
          Events : events
        };
        TaskIds.pop();
      }
      ObjectIds.pop();
    }
  }
  downloadReport(Objects);
}

Go back to the button you created and on its options under Assign Script select our function myFunction.
Once you have this array of objects with the right hierarchical information, then it is up to you the way you want to use it for generating reports. You could either:

Use the array of JSON objects to generate an HTML email for sending reports through Gmail whenever you click the sheet button.
Generate a new sheet and paste this data with the structure you shown in the picture (much easier to automate now that you have your data sorted), export as PDF and delete this sheet as its purpose was only to generate this PDF report.
Send it to other services as an array of JSON that then they can easily use.

For the second scenario of this fifth step, I am providing here some guidance as an example of how this could be implemented (a minimal example). Let me know if you need further guidance.
Basically, you would create this new sheet in your spreadsheet and then iterate over our array of objects and over our json objects to set the cell values of our new sheet in their adecuate place. Note that I have also edited the previous code I had to make a call to this new function from myFunction().
The following code has self explanatory comments and it will basically print the object ids that exist in your sheet:

function downloadReport(object){
  // Check if this sheet already exists from generating previous reports
  // and if so delete it to create a new report
  if(SpreadsheetApp.getActive().getSheetByName('Download')){SpreadsheetApp.getActive().deleteSheet(SpreadsheetApp.getActive().getSheetByName('Download'))}

  // Create your new sheet
  var sheet = SpreadsheetApp.getActive().insertSheet().setName('Download');

  // Iterate over each object in your array of objects
  for(i=0;i<object.length;i++){

  // print each object id of your series of objects. For doing so first access the array
  // element and then in that object access the key of the json object. Do the same for the
  // rest of the fields you are interested to print in your report.
    sheet.getRange(i+1, 1).setValue(object[i]['ObjectId']);
  }
}

I hope this has helped you. Let me know if you need anything else or if you did not understood something. :)


Q:

How to link a QProgressBar to a Terminal process percentage?

So I designed a very simple dialog using Qt which is meant to download videos from youtube and convert them to either mp4 or mp3, everything using youtube-dl command (I use system() to call youtube-dl). Yes, I'm a Linux user.
It's working fine, but I would like to show the progress of the download in my UI, like the one showing in the Terminal when I call youtube-dl directly from there.
Any constructive critique about the whole code would be very appreciated.
//ytdialog.h
#ifndef YTDIALOG_H
#define YTDIALOG_H
#include <iostream>
using namespace std;
#include <QDialog>

class QPushButton;
class QLineEdit;
class QLabel;

class ytDialog : public QDialog
{
  Q_OBJECT
  public:
    ytDialog(QWidget *parent = 0);
  private slots:
    void videoOutput(); //download the video that corresponds to the link in   link(QLineEdit)
    void audioOutput(); //download the video and converts it to mp3
    void enableButtons(); //enable the buttons when link is not empty
  private:
    QLabel *linkLabel; //Just a Label
    QPushButton *video; //Button to Download video
    QPushButton *audio; //Button to Download video and convert it to mp3
    QLineEdit *link; //Input link
};

#endif

//ytdialog.cpp **Just In case You need it**
#include <QtWidgets>

#include "ytdialog.h"

ytDialog::ytDialog(QWidget *parent)
      : QDialog(parent)
{
  linkLabel = new QLabel("Link: ");
  link = new QLineEdit;
  video = new QPushButton("Video Output");
  audio = new QPushButton("Audio Output");

  link->setMinimumWidth(400);
  video->setEnabled(false);
  audio->setEnabled(false);

  connect(link, SIGNAL(textChanged(const QString &)),
      this, SLOT(enableButtons()));
  connect(video, SIGNAL(clicked()),
      this, SLOT(videoOutput()));
  connect(audio, SIGNAL(clicked()),
      this, SLOT(audioOutput()));

  QHBoxLayout *linkLayout = new QHBoxLayout;
  linkLayout -> addWidget(linkLabel);
  linkLayout -> addWidget(link);

  QHBoxLayout *buttonsLayout = new QHBoxLayout;
  buttonsLayout -> addWidget(video);
  buttonsLayout -> addWidget(audio);

  QVBoxLayout *main = new QVBoxLayout;
  main -> addLayout(linkLayout);
  main -> addLayout(buttonsLayout);

  setLayout(main);
  setWindowTitle("Download Youtube");
}
void ytDialog::enableButtons()
{
   if (!link->text().isEmpty())
   {
     video->setEnabled(true);
     audio->setEnabled(true);
   }
   else
   {
     video->setEnabled(false);
     audio->setEnabled(false);
   }
}
void ytDialog::videoOutput()
{
  string cmd = "youtube-dl -o '/home/rodrigo/Videos/%(title)s.%(ext)s' " + link-    >text().toStdString();
  system(cmd.c_str());
}

void ytDialog::audioOutput()
{
  string cmd = "youtube-dl -x --audio-format mp3 -o '/home/rodrigo/Music/%(title)s.%    (ext)s' " + link->text().toStdString();
  system(cmd.c_str());
}

A:

You can use QProcess to execute the command. Then you can use readyReadStandardOutput signal to read the command output messages in a slot and process the text to extract the progress percentage :
In your constructor :
process = new QProcess();

connect (process, SIGNAL(readyReadStandardOutput()), this, SLOT(readyRead()));
connect (process, SIGNAL(finished (int, QProcess::ExitStatus)), this, SLOT(finished()));

videoOutput slot :
void ytDialog::videoOutput()
{
  string cmd = "youtube-dl -o '/home/rodrigo/Videos/%(title)s.%(ext)s' " + link-    >text().toStdString();
  process.start("/bin/sh", QStringList()<< "-c" << cmd);
}

readyRead slot :
ytDialog::readyRead()
{
  if (!process)
    return;

  QString str = process->readAllStandardOutput();

  //Extract the progress percentage and emit a signal to update the progress bar
  ...
}


Q:

Programmatically extracting a frame from a video in Flash

I need to write a small Flash app that will need to extract a video frame from a playing video. It will not need to be saved to the HDD of the user. I just need to get the image data and display it in the Flash movie. The frame to extract will be chosen by the user, which is why I'd like to do this purely on the client side (though I know I could do it from the server side).
I've tried searching for solutions but I'm not getting any useful results. Being a Flash newbie I haven't got any code yet seeing as I wouldn't know where to start.
So Flash gurus, is there a way to do this?

A:

If you take a 'screen grab' of a DisplayObject in flash using BitmapData's draw() method.
If you have something for displaying flv somewhere a bit to the right, or down, try something like:
var cloneData:BitmapData = new BitmapData(video.width,video.height,false,0x000000);
cloneData.draw(video);
//test
addChild(new Bitmap(cloneData));

Goodluck!

A:

After reading Georges answer, this is what I came up with as proof of concept. Posting here so it doesn't pollute original question.
<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="video.load()">
 <mx:VideoDisplay id="video" x="0" y="0" source="/content/content.flv" />
 <mx:Button x="10" y="10" label="Grab" click="grabClick()"/>
 <mx:Button x="71" y="10" label="Play" click="video.play()"/>
 <mx:Button x="130" y="10" label="Pause" click="video.pause()"/>
 <mx:Script>
  <![CDATA[
   import mx.controls.*;
   import flash.display.BitmapData;

   private function grabClick():void {
    var bitdata:BitmapData = new BitmapData(video.width, video.height, false, 0x0);
    bitdata.draw(video);
    var grabResult:Image = new Image();
    grabResult.x = 0;
    grabResult.y = video.height;
    grabResult.source = new Bitmap(bitdata);
    addChild(grabResult);
   }
  ]]>
 </mx:Script>
</mx:Application>


Q:

Add names from array using 'classed'

I have a codepen here - https://codepen.io/anon/pen/ddPMVx?editors=1010
It's a simple stacked bar chart
Each stack from the data is in its own layer with a class of 'layer'
I'd like to added another class that is the name of the key from the keys that create the stack
.classed('layer', true)

// .classed((i)=>{
//     return keys[i],
// }, true)

A:

You cannot use a function with classed. For further information, have a look at my answer here.
You can use a getter to get the existing classes and add the one you want. However, pay attention to this: the fact that you use the letter i in the argument...
function(i){...

... doesn't mean that it is the index. The index is the second argument, no matter its name. So, it should be:
function(_, i){...

All that being said, this is a way to add the key name without overriding the existing classes:
.attr("class", function(_, i){
    return d3.select(this).attr("class") + " " + keys[i]
});

Here is the updated CodePen: https://codepen.io/anon/pen/JpoKLK?editors=1010


Q:

Return all rows in a table that has specific column header text using Xpath

I have the following HTML table in a page:

            Birth Date

I have the following Xpath:
//table[//th[contains(text(), "Birth Date")]]/tr

I get rows from all tables in the page, not the one with the Birth Date header.
What am I missing?

A:

If I understand what you want then I think you are close. I think you want
'//table[.//th[contains(text(), "Birth Date")]]//tr'

(note the . before //th to query with respect to the table rather than the entire document).
You could also write this as
'//table[contains(.//th/text(), "Birth Date")]//tr'


Q:

MongoDB: Are bulk operations written to the oplog as a whole?

When I issue an ordered bulk operation in MongoDB 3, is the bulk operation as a whole written to the oplog so that it can be replayed as a whole after a server crash?
The rationale for this question is the following:
I know that there are no real transactions but that I can use the $isolated keyword to have some read consistency (in some cases).
Apart from being good schema design or not, let's assume that I would have to update multiple documents in possibly different collections in one go, in what would be a transaction in SQL. I do not care about the data being in an inconsistent state at any near moment, however I do require the data to be consistent eventually. So, while I may not care about errors and missing rollbacks during the operation, I require the sequence of updates to be performed entirely or not performed at all at some point, in order to have them survive unexpected server failures or shutdowns in the middle of the bulk operation (because of, say, random CoreOS updates).

A:

I will enter into this with the general caveat that I admit I have not even looked at the results, but the basic principles seem valid to me from the start.
What you need to consider here is "what is actually happening under the hood" of the "nice syntax sugar" you are presented with in general calls. What this means is basically looking at what the "command form" of the operations you are calling actually do. In this case "update".
So, if you had a look at that link already, then consider the following "Bulk" update form:
var bulk = db.collection.initializeOrdedBulkOp();

bulk.find({ "_id": 1 }).updateOne({ "$set": { "a": 1 } });
bulk.find({ "_id": 2 }).updateOne({ "$set": { "b": 2 } });

bulk.execute();

Now you already know this is being sent to the server as one request, but what you are likely not considering is that actual "request" made "under the hood" is actually this:
db.runCommand({
    "update": "collection",
    "updates": [
        { "q": { "_id": 1 }, "u": { "$set": { "a": 1 } } },
        { "q": { "_id": 2 }, "u": { "$set": { "b": 2 } } }
    ],
    "ordered": true
})

Therefore it stands to reason that what you actually see in the logs under the "update" operation is actually something like (abbreviated from full output to just the query):
{ "q": { "_id": 1 }, "u": { "$set": { "a": 1 } } }
{ "q": { "_id": 2 }, "u": { "$set": { "b": 2 } } }

Which therefore means that each of those actions with the associated command is in the oplog for "replay" on replication and/or on other actions you might perform such as specifically "replaying" the oplog entries.
I'd be sure that is what actually happens without even looking, because I know that it how the drivers implement the actual calls, and it makes sense that each call is kept within the oplog in this way.
Therefore "as a whole", then no. These are not "transactions" and are always distinct operations even if their submission and return are within a singular request. But they are not a singular operation, and therefore will not and should not be recorded as such.


Q:

Basic BLE communication app for iOS with swift

I am quite new to iOS programming and also to bluetooth protocol.
I have found a sample code written in swift and trying to modify it to work with my own bluetooth module. The module I have is DBM01 from dorji.
The service I need to use is FFF0 and the characteristics is FFF1 for sending a ASCII value.
When I use the LightBlue app on my macbook and connect to the board I have designed, which has the DBM01 module on it, I can send the char value of "1" and I get the expected response (Turning on a LED) and when I send value of "0" it turns the LED off.
Now with the code I have, I can connect to the DBM01 module. I can print its name. However, I cannot disconnect from it with the following function. I am also not sure if this is for disconnecting from the device or it is called automatically when the device is disconnected. Regardless, it does not work either way.
func centralManager(central: CBCentralManager,
            didDisconnectPeripheral peripheral: CBPeripheral,
            error: NSError?)

My main problem is I really didn't understand how I specify the service and the characteristics that I am interested in and connect to specific device that has them.
I am also unable to send a message. When I try I got the predefined error, since the following condition did't hold
if writeCharacteristic != nil

Below is my full code.
Appreciate if you can point out where I am doing wrong and how I can achieve connecting to specific device with specific service and characteristics information and sending data.
//
//  ViewController.swift
//  bleSwift
//

import UIKit
import CoreBluetooth

class ViewController: UIViewController, CBCentralManagerDelegate, CBPeripheralDelegate {

    var centralManager: CBCentralManager!
    var peripheral: CBPeripheral!
    var writeCharacteristic: CBCharacteristic!
    var service: CBService!
    var characteristic: CBCharacteristic!

    var bluetoothAvailable = false
    let message = "1"

    @IBOutlet weak var deviceName: UILabel!
    @IBOutlet weak var ServiceName: UILabel!
    @IBOutlet weak var CharacteristicsName: UILabel!

    func centralManagerDidUpdateState(central: CBCentralManager)
    {
        print("Checking state")
        switch (central.state)
        {
        case .PoweredOff:
            print("CoreBluetooth BLE hardware is powered off")

        case .PoweredOn:
            print("CoreBluetooth BLE hardware is powered on and ready")
            bluetoothAvailable = true;

        case .Resetting:
            print("CoreBluetooth BLE hardware is resetting")

        case .Unauthorized:
            print("CoreBluetooth BLE state is unauthorized")

        case .Unknown:
            print("CoreBluetooth BLE state is unknown");

        case .Unsupported:
            print("CoreBluetooth BLE hardware is unsupported on this platform");

        }
        if bluetoothAvailable == true
        {
            discoverDevices()
        }
    }

    func centralManager(central: CBCentralManager, didDiscoverPeripheral peripheral: CBPeripheral, advertisementData: [String : AnyObject], RSSI: NSNumber)
    {
                // Stop scanning
                self.centralManager.stopScan()
                print("Stopped Scanning")
                // Set as the peripheral to use and establish connection
                //self.peripheral = peripheral
                //self.peripheral.delegate = self
                //self.centralManager.connectPeripheral(peripheral, options: nil)
                peripheral.discoverServices([CBUUID(string: "FFF0")])
                print("CONNECTED!!")
                print(peripheral.name)
                deviceName.text = peripheral.name
    }

    func discoverDevices() {
        print("Discovering devices")
        centralManager.scanForPeripheralsWithServices(nil, options: nil)

    }

    @IBAction func disconnectDevice(sender: AnyObject) {

        func centralManager(central: CBCentralManager,
            didDisconnectPeripheral peripheral: CBPeripheral,
            error: NSError?)
        {
            print("CONNECTION WAS DISCONNECTED")
            deviceName.text = "Disconnected"
        }
    }

    @IBAction func Scan(sender: AnyObject)
    {
        print("Scan")
        centralManager = CBCentralManager(delegate: self, queue: nil)
    }

    @IBAction func Send(sender: AnyObject)
    {
        let data = message.dataUsingEncoding(NSUTF8StringEncoding)
        if writeCharacteristic != nil
        {
            print("Sent")
            peripheral!.writeValue(data!,  forCharacteristic: writeCharacteristic, type: CBCharacteristicWriteType.WithoutResponse)
        }
        else
        {
            print("Couldn't Send")
        }
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

}

A:

In order to send data to your ble peripheral, you should:

Start scanning.
In your ble central manager delegate you'll recieve didDiscoverPeripheral callback with discovered peripheral. Set yourself as its delegate and connect to it: centralManager.connectPeripheral(...)
Receive didConnectPeripheral in delegate. Now call discoverServices for this peripheral.
Recieve didDiscoverServices in your delegate. Finaly, call discoverCharacteristics for your service.
You'll recieve characteristic in didDiscoverCharacteristic delegate method. After that, you'll be able to send data to exact characteristic of your peripheral.
To disconnect peripheral, call method centralManager.cancelPeripheralConnection(...)


Q:

MPI process synchronization

I'm still confused about the implementation of my program using MPI. This is my example:
 import mpi.*;
 public class HelloWorld {
     static int me;
     static Object [] o = new Object[1];
     public static void main(String args[]) throws Exception {
       //10 processes were started: -np 10
       MPI.Init(args);
       me = MPI.COMM_WORLD.Rank();
       if(me == 0) {
            o[0] = generateRandBoolean(0.5);
            for(int i=1; i<10;i++)
                MPI.COMM_WORLD.Isend(o, 0, 1, MPI.OBJECT, i,0);
            if((Boolean)o[0])
                MPI.COMM_WORLD.Barrier();
        } else {

            (new HelloWorld()).work();
        }
        MPI.Finalize();
    }

    public void work() {
        //do some calculation
            //for some reason, the 10th process
        //will not be needed
            if(me == 9)
            return;

        //some times, the rest of the
        //processes have to be synchronized
        Request rreq = MPI.COMM_WORLD.Irecv(o, 0, 1, MPI.OBJECT, MPI.ANY_SOURCE, 0);
        rreq.Wait();
        if((Boolean)o[0])
            MPI.COMM_WORLD.Barrier();
    }

    public static boolean generateRandBoolean(double p) {
        return (Math.random() < p);
    }
}

The problem is that in some cases, I will not need all the processes, so I don't know what to do with the idle ones. At first, I was returning the not needed processes, but it generates problem if the rest of the processes need to be synchronized with Barrier().
I thought I could let the processes I don't need running waiting for a message to finish or to call Barrier, but it does not sound good to me.
Also, I read that calling Barrier has a performance penalty, so I would prefer not to use it.
How can I achieve the synchronization I need?
Thank you very much.

A:

Use MPI_Barrier to collect all the ranks at the end of the program.
In all reasonable implementations of MPI, the ranks in a collective will spin or yield the processor if there are any other processes that have work to do.  This may look a lot like the rank is consuming 100% of the CPU...but if any other process actually has work to do it will be scheduled and allowed to run.


Q:

Unable to deploy application on EC2 instance using AWS CloudFormation template through cfn-init and UserData script

I am trying to deploy sample.war application on EC2 instance at the time of launch. That is when an instance is launched the application should be deployed automatically on it using cfn-init and Metadata. I added a user with policy and authentication with no luck. If I wget with the S3 path, the file is being downloaded. Below is my script. What am I missing in this, or is there any other way to do this?
---
AWSTemplateFormatVersion: 2010-09-09
Description: Test QA Template
Resources:
  MyInstance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: !Ref AMIIdParam
      InstanceType: !Ref InstanceType
    Metadata:
      AWS::CloudFormation::Init:
        config:
          packages:
            yum:
              java-1.8.0-openjdk.x86_64: []
              tomcat: []
              httpd.x86_64: []
          services:
            sysvinit:
              httpd:
                enabled: true
                ensureRunning: true
          files:
            /usr/share/tomcat/webapps/sample.zip:
              source: https://s3.amazonaws.com/mybucket/sample.zip
              mode: '000500'
              owner: tomcat
              group: tomcat
              authentication: S3AccessCreds
      AWS::CloudFormation::Authentication:
        S3AccessCreds:
          type: 'S3'
          accessKeyId: !Ref HostKeys
          secretKey: Fn::GetAtt:
            - HostKeys
            - SecretAccessKey
          buckets: !Ref BucketName
  CfnUser:
    Type: AWS::IAM::User
    Properties:
      Path: '/'
      Policies:
        - PolicyName: 'S3Access'
          PolicyDocument:
           Statement:
             - Effect: 'Allow'
               Action: s3:*
               Resource: '*'
  HostKeys:
    Type: AWS::IAM::AccessKey
    Properties:
      UserName: !Ref CfnUser

A:

I was unable to reproduce this using the following template:
---
AWSTemplateFormatVersion: 2010-09-09
Description: Test QA Template
Resources:
  MyInstance:
    Type: AWS::EC2::Instance
    Properties:
      ImageId: ami-08589eca6dcc9b39c
      InstanceType: t2.micro
      KeyName: default
      UserData:
        Fn::Base64: !Sub |
          #!/bin/bash -xe
          /opt/aws/bin/cfn-init -s ${AWS::StackId} --resource MyInstance --region ${AWS::Region}
    Metadata:
      AWS::CloudFormation::Init:
        config:
          packages:
            yum:
              java-1.8.0-openjdk.x86_64: []
              tomcat: []
              httpd.x86_64: []
          services:
            sysvinit:
              httpd:
                enabled: true
                ensureRunning: true
          files:
            /usr/share/tomcat/webapps/sample.zip:
              source: https://s3.amazonaws.com/mybucket/sample.zip
              mode: '000500'
              owner: tomcat
              group: tomcat

(In other words, use of the above template allowed me to install a sample.zip file using cfn-init.)
Thus there is something permissions-related in the way you're accessing the S3 bucket.
Suffice to say it is a bad practice to use Access Keys. Have a look at this document on best practices of assigning an IAM Role to an EC2 instance and then adding a Bucket Policy that grants appropriate access to that Role.


Q:

Relation between areas of two non-similar triangles with individual proportional sides

Triangle $ABC$ has area $k$ and $D$ is the middle point of $BC$.
We have $AP = 2 \cdot AB$, $AQ = 3 \cdot AD$ and $AR = 4 \cdot AC$. What's the area of triangle $PQR$?
I know that the answer is $k$, but I don't know how to prove it.
Thank you all in advance!

A:

Let $\angle PAQ = \alpha$ and $\angle RAQ = \beta$.
$$A_{PQR} = A_{APQ} + A_{AQR}- A_{APR}$$
$$=\frac12 AP\cdot AQ\sin\alpha + \frac12 AR\cdot AQ\sin\beta - \frac12 AP\cdot AR\sin(\alpha+\beta)$$
$$=\frac12 ( 2AB \cdot 3AD\sin\alpha )+ \frac12 ( 3AD \cdot 4AC\sin\beta)
- \frac12 ( 2AB \cdot4AC\sin(\alpha+\beta))$$
$$= 6 A_{ABD}+ 12 A_{ACD} - 8A_{ABC}
=6\cdot\frac k2+12\cdot\frac k2-8k=k$$


Q:

Incoming call not triggering OnNavigateAway?

I have a WP7 XNA game that needs to save the state whenever the user navigates away. This happens when the users presses presses the Start button, Back button etc. However, the game does not pause and nothing happens when I have an incoming call (even when I take the call).
Does receiving a call not trigger OnNavigateAway ? It feels like this because you don't get the classic back-navigation transition, but it's more like an overlay.

A:

Handle Obscured event to pause a game. This event raised when some UI chrome is above the screen. Calls, Message Box, etc. This tutorials should help you.


Q:

There has been an error processing your request Exception printing is disabled by default for security reasons

Hello i installed a theme from envato after this i cant login into Backend. After login i get the Exception printing error.
Here's the report
a:4:{i:0;s:340:"Warning: is_dir(): open_basedir restriction in effect. File(/etc/pki/tls/certs) is not within the allowed path(s): (/var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/:/tmp/) in /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/composer/composer/src/Composer/Util/RemoteFilesystem.php on line 914";i:1;s:10061:"#0 [internal function]: Magento\Framework\App\ErrorHandler->handler(2, 'is_dir(): open_...', '/var/www/vhosts...', 914, Array)
#1 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/composer/composer/src/Composer/Util/RemoteFilesystem.php(914): is_dir('/etc/pki/tls/ce...')
#2 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/composer/composer/src/Composer/Util/RemoteFilesystem.php(801): Composer\Util\RemoteFilesystem->getSystemCaRootBundlePath()
#3 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/composer/composer/src/Composer/Util/RemoteFilesystem.php(61): Composer\Util\RemoteFilesystem->getTlsDefaults(Array)
#4 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/composer/composer/src/Composer/Factory.php(566): Composer\Util\RemoteFilesystem->__construct(Object(Composer\IO\BufferIO), Object(Composer\Config), Array, false)
#5 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/composer/composer/src/Composer/Factory.php(306): Composer\Factory::createRemoteFilesystem(Object(Composer\IO\BufferIO), Object(Composer\Config))
#6 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/composer/composer/src/Composer/Factory.php(532): Composer\Factory->createComposer(Object(Composer\IO\BufferIO), Array, false)
#7 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/Composer/ComposerFactory.php(47): Composer\Factory::create(Object(Composer\IO\BufferIO), '/var/www/vhosts...')
#8 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/Composer/ComposerInformation.php(362): Magento\Framework\Composer\ComposerFactory->create()
#9 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/Composer/ComposerInformation.php(375): Magento\Framework\Composer\ComposerInformation->getComposer()
#10 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/Composer/ComposerInformation.php(242): Magento\Framework\Composer\ComposerInformation->getLocker()
#11 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/App/ProductMetadata.php(104): Magento\Framework\Composer\ComposerInformation->getSystemPackages()
#12 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/App/ProductMetadata.php(65): Magento\Framework\App\ProductMetadata->getSystemPackageVersion()
#13 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/module-admin-notification/Model/Feed.php(208): Magento\Framework\App\ProductMetadata->getVersion()
#14 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/module-admin-notification/Model/Feed.php(138): Magento\AdminNotification\Model\Feed->getFeedData()
#15 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/module-admin-notification/Observer/PredispatchAdminActionControllerObserver.php(51): Magento\AdminNotification\Model\Feed->checkUpdate()
#16 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/Event/Invoker/InvokerDefault.php(73): Magento\AdminNotification\Observer\PredispatchAdminActionControllerObserver->execute(Object(Magento\Framework\Event\Observer))
#17 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/Event/Invoker/InvokerDefault.php(61): Magento\Framework\Event\Invoker\InvokerDefault->_callObserverMethod(Object(Magento\AdminNotification\Observer\PredispatchAdminActionControllerObserver), Object(Magento\Framework\Event\Observer))
#18 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/Event/Manager.php(66): Magento\Framework\Event\Invoker\InvokerDefault->dispatch(Array, Object(Magento\Framework\Event\Observer))
#19 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/var/generation/Magento/Framework/Event/Manager/Proxy.php(95): Magento\Framework\Event\Manager->dispatch('controller_acti...', Array)
#20 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/App/Action/Action.php(91): Magento\Framework\Event\Manager\Proxy->dispatch('controller_acti...', Array)
#21 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/module-backend/App/AbstractAction.php(226): Magento\Framework\App\Action\Action->dispatch(Object(Magento\Framework\App\Request\Http))
#22 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/Interception/Interceptor.php(74): Magento\Backend\App\AbstractAction->dispatch(Object(Magento\Framework\App\Request\Http))
#23 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/Interception/Chain/Chain.php(70): Magento\Backend\Controller\Adminhtml\Index\Index\Interceptor->___callParent('dispatch', Array)
#24 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/Interception/Chain/Chain.php(63): Magento\Framework\Interception\Chain\Chain->invokeNext('Magento\\Backend...', 'dispatch', Object(Magento\Backend\Controller\Adminhtml\Index\Index\Interceptor), Array, 'adminAuthentica...')
#25 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/module-backend/App/Action/Plugin/Authentication.php(143): Magento\Framework\Interception\Chain\Chain->Magento\Framework\Interception\Chain\{closure}(Object(Magento\Framework\App\Request\Http))
#26 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/Interception/Chain/Chain.php(67): Magento\Backend\App\Action\Plugin\Authentication->aroundDispatch(Object(Magento\Backend\Controller\Adminhtml\Index\Index\Interceptor), Object(Closure), Object(Magento\Framework\App\Request\Http))
#27 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/Interception/Interceptor.php(138): Magento\Framework\Interception\Chain\Chain->invokeNext('Magento\\Backend...', 'dispatch', Object(Magento\Backend\Controller\Adminhtml\Index\Index\Interceptor), Array, 'adminMassaction...')
#28 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/module-backend/App/Action/Plugin/MassactionKey.php(33): Magento\Backend\Controller\Adminhtml\Index\Index\Interceptor->Magento\Framework\Interception\{closure}(Object(Magento\Framework\App\Request\Http))
#29 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/Interception/Interceptor.php(142): Magento\Backend\App\Action\Plugin\MassactionKey->aroundDispatch(Object(Magento\Backend\Controller\Adminhtml\Index\Index\Interceptor), Object(Closure), Object(Magento\Framework\App\Request\Http))
#30 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/var/generation/Magento/Backend/Controller/Adminhtml/Index/Index/Interceptor.php(39): Magento\Backend\Controller\Adminhtml\Index\Index\Interceptor->___callPlugins('dispatch', Array, Array)
#31 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/App/FrontController.php(55): Magento\Backend\Controller\Adminhtml\Index\Index\Interceptor->dispatch(Object(Magento\Framework\App\Request\Http))
#32 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/Interception/Interceptor.php(74): Magento\Framework\App\FrontController->dispatch(Object(Magento\Framework\App\Request\Http))
#33 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/Interception/Chain/Chain.php(70): Magento\Framework\App\FrontController\Interceptor->___callParent('dispatch', Array)
#34 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/Interception/Interceptor.php(138): Magento\Framework\Interception\Chain\Chain->invokeNext('Magento\\Framewo...', 'dispatch', Object(Magento\Framework\App\FrontController\Interceptor), Array, 'install')
#35 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/Module/Plugin/DbStatusValidator.php(69): Magento\Framework\App\FrontController\Interceptor->Magento\Framework\Interception\{closure}(Object(Magento\Framework\App\Request\Http))
#36 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/Interception/Interceptor.php(142): Magento\Framework\Module\Plugin\DbStatusValidator->aroundDispatch(Object(Magento\Framework\App\FrontController\Interceptor), Object(Closure), Object(Magento\Framework\App\Request\Http))
#37 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/var/generation/Magento/Framework/App/FrontController/Interceptor.php(26): Magento\Framework\App\FrontController\Interceptor->___callPlugins('dispatch', Array, Array)
#38 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/App/Http.php(135): Magento\Framework\App\FrontController\Interceptor->dispatch(Object(Magento\Framework\App\Request\Http))
#39 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/vendor/magento/framework/App/Bootstrap.php(258): Magento\Framework\App\Http->launch()
#40 /var/www/vhosts/lvps83-169-4-62.dedicated.hosteurope.de/httpdocs/hosted/assetshop/index.php(39): Magento\Framework\App\Bootstrap->run(Object(Magento\Framework\App\Http))
#41 {main}";s:3:"url";s:97:"/admin_li/admin/index/index/key/6546689fddfbb638bfa01a4cd65b96c1222bf9bc94bdb797d004609fd0f53dbf/";s:11:"script_name";s:10:"/index.php";}

can u help me

A:

Modify the open_basedir settings in your hosting account and set them to none. Find the open_basedir setting given under PHP Settings area of your Plesk/cPanel. Set it to none from the dropdown given there.


Q:

TypeError: $.ajax is not a function

Obviously I need to elaborate. Every single function even ones that can be replaced by vanilla JS, are jQuery functions that work, but the AJAX function does not work.
$.ajax({
    type: "POST",
    data: {
        email: emailInput,
        mode: 0
    },
    url: "main.php",
    cache: false
}).done(function(response) {

});

I tried it without promises, I tried it as $.post, I tried everything but it doesn't work.

A:

Quite late, but have you regular version of jQuery? Slim version doesn't contain ajax functions among others. Check here


Q:

Functional way to reduce object into a string

I'm looking for a good functional way to convert this object:
var globals = {
    foo: "bar",
    foo2: "bar2"
};

...into this string:
'window.foo = "bar"; window.foo2 = "bar2";'

Something almost similar to Array.prototype.reduce().
Use of libs like Lodash is okay.
What I'm not looking for are non-functional approaches like:
var string = "";

// Pseudo code
_.forOwn(...) {
    string += key
}

A:

Use map and join

var globals = {
  foo: "bar",
  foo2: "bar2"
};

var result = Object.keys(globals).map(function(key) {
  return 'window.' + key + ' = "' + this[key] + '";';
}, globals).join(' ');

console.log(result);


Q:

Let $V=\mathbb{R}^\mathbb{R}$, let $W$ be the subset of $V$ consisting of all monotonically inc or dec functions. Is $W$ subspace of $V$?

Let $V=\mathbb{R}^\mathbb{R}$ and let $W$ be the subset of $V$ consisting of all monotonically-increasing or monotonically-decreasing functions. Is $W$ a subspace of $V$?
Any solutions or hints are greatly appreciated. I'm not sure how to approach.

A:

$ x \to -x $ is decreasing ,
$ x \to x^3 $ is increasing,
but $x \to x^3-x $ is neither so W can't be a subspace of $V$.


Q:

Instapaper freezing on startup due to problematic article

I added an article to Instpaper on my iPod Touch, and then I opened the article. It crashed Instapaper, so I deleted the article through my browser and then reopened Instapaper. Now Instapaper freezes on startup.
Is there any way to stop Instapaper from loading the last opened article, so I can get it out of this loop to fix it?
I already tried removing it from the multitask bar, and restarting my device.

A:

force quite the Instapaper app again
login into your Instapaper account on instapaper.com
remove offending article
restart Instapaper app


Q:

Update records with ArcPy update cursor? Geodatabase format

I try to update thousands of rows when all records get the same value.
My code has a loop that runs thousands of times.
Is it possible for the program to make the change to all the columns in one command and save run time ?
For example, php+mySQL can do this:
mysql_query("UPDATE all_records SET Xcenter = $val1, Ycenter = $val2 WHERE ID > 100");

This is my code:
    for row in rows:
    row.setValue("Xcenter", val1)
    row.setValue("Ycenter", val2)
    rows.updateRow(row)

A:

Try the da.UpdateCursor:
import arcpy
feature_class = r'C:\data.gdb\features1'

val1 = 123
val2 = 456

sql = """{0} > 100""".format(arcpy.AddFieldDelimiters(feature_class, 'ID'))

fields_to_update = ['Xcenter','Ycenter']
with arcpy.da.UpdateCursor(feature_class, fields_to_update, sql) as cursor:
    for row in cursor:
        row = val1, val2
        cursor.updateRow(row)

A:

I have a weird feeling that you are looking for arcpy.CalculateField_management It is simple and quick calculate field help


Q:

ElasticSearch - Index a large file using Java API

We have a requirement wherein we have to use ElasticSearch for performing full text search. We have a Spring based application and for integration with ES we can use either Java API of Elastic Search or Spring Data for ElasticSearch.
The input will be of a file type having size around 5MB.
I went through examples for both ES Java API and SpringData, they do have
tutorials available for inserting a JSON document.
But any help with regards to using File as an input to create documents/index is not available.
I am newbie with Elastic Search, any guidance/help on this will be much appreciated.
EDIT:
I could see that there is a Ingest Attachment Processor plugin available in ES (https://www.elastic.co/guide/en/elasticsearch/plugins/master/ingest-attachment.html).
Can anybody point me to a sample CURL request to use this plugin or any Java code to use this plugin

A:

1.You may use Elasticsearch mapper attachments plugin. This plugin uses Apache Tika to ingest almost any well known type of document and make it searchable by Elasticsearch.
https://www.elastic.co/guide/en/elasticsearch/plugins/2.3/mapper-attachments.html
2.You can use Apache Tika  to extract useful content from file and use elasticsearch Bulk Indexing api to index to ES
Hope that helps


Q:

Is there a way to prevent the pretty-print gem from triggering every time a model is instantiate?

Is there a way to prevent the pretty-print gem from triggering every time a model is instantiate? I find it annoying and would prefer to explicitly call the function. Also, how can i sort the attributes being printed out?

A:

Coincidentally I do not use pretty-print for those reasons. You should check out snoop_dogg instead (Full disclosure, I created snoop_dogg).
The gem sorts the attributes alphabetically, and puts them to the console in a similar fashion as pretty-print, but it does not do so automatically. You instead call 'snoop' on the model instance when you want to inspect it in a more human readable way.
Also, 'snoop' takes arguments in the form of model relationships. For example, 'User.first.snoop(:address, :comments)' would print the @user instance as well as that user's associated address and any comments associated with that user.
I think this is what you are looking for. Hope that help! Feel free to contribute too!


Q:

How to display a TextView from another layout

I have a mainactivity layout and another layout with a textview. I want to set value to textview from my mainactivity file and display it in the mainlayout file. How can I go about this. I'm using layout inflator and am getting the refrence id of Textview successfully.
Main Activity:
public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View vi = inflater.inflate(R.layout.layout2, null); //log.xml is your file.
    TextView tv = (TextView)vi.findViewById(R.id.text1);

    System.out.println("Textview= "+tv);
    tv.setText("hELLLLOO");
}
}

Main_Layout.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
</RelativeLayout>

Layout2.xml:
<?xml version="1.0" encoding="utf-8"?>
 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
 >
 <TextView
    android:id="@+id/text1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world"
    android:layout_gravity="center"
    android:textColor="#000000"/>
 </LinearLayout>

A:

You can use intent and pass the value to the next Activity. You only inflate the layout but that is not added to Activity.
You will have to get the reference to RelativeLayout and add the inflated view to it
Have a id for RelativeLAyout
<RelativeLayout android:id="@+id/relativelayout

Then
RelativeLayout rl = (RelativeLayout) findViewById(R.id.relativeLayout);
View vi = inflater.inflate(R.layout.layout2, null); //log.xml is your file.
TextView tv = (TextView)vi.findViewById(R.id.text1);
tv.setText("hELLLLOO");
rl.addView(vi);

You may also use the

http://www.curious-creature.org/2009/02/25/android-layout-trick-2-include-to-reuse/
Or
In MainActivity
Intent intent = new Intent(MainActivity.this,SecondActivity.class);
intent.putExtra("key","hello");
startActivity(intent);

Then in SecondActivity
// Inflate Layout 2 and set text to textview.
String value = getIntent().getStringExtra("key");


Q:

Convert blob to file

I need to convert a blob to file i javascript.
Im using File API
var blob = new Blob(byteArrays, { type: contentType });

This is return from a function reading a cropped images.
The old upload function are using $files as input.
I want to convert that blob to file, and then set the name and type in that object.
How do I do this??

A:

It's easy:
var blob = new Blob(byteArrays, { type: contentType });
var file = new File([blob], filename, {type: contentType, lastModified: Date.now()});

or just:
var file = new File([byteArrays], filename, {type: contentType, lastModified: Date.now()});

The code works in Chrome and Firefox, but not IE.

A:

I solved the file problem like this:
    function base64ToFile(base64Data, tempfilename, contentType) {
    contentType = contentType || '';
    var sliceSize = 1024;
    var byteCharacters = atob(base64Data);
    var bytesLength = byteCharacters.length;
    var slicesCount = Math.ceil(bytesLength / sliceSize);
    var byteArrays = new Array(slicesCount);

    for (var sliceIndex = 0; sliceIndex < slicesCount; ++sliceIndex) {
        var begin = sliceIndex * sliceSize;
        var end = Math.min(begin + sliceSize, bytesLength);

        var bytes = new Array(end - begin);
        for (var offset = begin, i = 0 ; offset < end; ++i, ++offset) {
            bytes[i] = byteCharacters[offset].charCodeAt(0);
        }
        byteArrays[sliceIndex] = new Uint8Array(bytes);
    }
    var file = new File(byteArrays, tempfilename, { type: contentType });
    return file;
}

Next problem is the format that angular-file-upload is reading the file in..

A:

in Edge and Safari, just use blob structure:
var blob = new Blob(byteArrays, { type: contentType });
blob.lastModifiedDate = new Date();
blob.name = name;


Q:

@font-face not working (Shopify)

The src url is correct, but the the text just shows up as a regular serif. Maybe it has to do with Shopify?
@font-face {
font-family: 'TradeGothicLTStdCnNo.18';
src: url('http://cdn.shopify.com/s/files/1/0065/5242/files/tradegothicltstd-cn18-webfont.eot');
src: url('http://cdn.shopify.com/s/files/1/0065/5242/files/tradegothicltstd-cn18-webfont.eot#iefix') format('embedded-opentype'),
     url('http://cdn.shopify.com/s/files/1/0065/5242/files/tradegothicltstd-cn18-webfont.woff') format('woff'),
     url('http://cdn.shopify.com/s/files/1/0065/5242/files/tradegothicltstd-cn18-webfont.ttf') format('truetype'),

font-weight: normal;
font-style: normal;
}

and
#navbar #navpanel .mainnav ul.tier1 > li {
font-size:13px;
font-family: 'TradeGothicLTStdCnNo.18';
}

A:

It was a simple mistake.
the last src url
url('http://cdn.shopify.com/s/files/1/0065/5242/files/tradegothicltstd-cn18-webfont.ttf') format('truetype'),

should end with ; not ,
I thought of deleting the question, but instead decided to answer it myself just in case somebody else makes the same mistake.


Q:

Stimulate SQL like query tool in python/C++

Implement SQL like query tool where from STDIN following things have to be read in the given order:-
1. Number of rows of the table (n) and Number of queries (q).
2. Table fields separated by Comma.
3. n line containing table rows of the table
4. q queries where clause.

We have to print output for each query on STDOUT.
Eg:-
Input:
4,2
"Name","Age","Sex","Salary"

1,"Joy",21,"M",2000

2,"Alan",28,"M",500

3,"John",30,"M",1000

4,"Nemo",45,"F",1500

Salary>=1000

Sex="M" and Salary>499

Output:
2

3

Can you guys tell how should I approach the problem?
And What data structure should I be using to store the table and process the queries ?
PS: I am not asking for the ready made solution, I just need step wise help in solving this question.

A:

I'm guessing the excersise is impelenting SQL like for practice (and not real SQL becuase this is the obvious solution).
I'd have a list of dictionaries (a dict for each row) fill it with the data and than use list comprehension to filter the lines
[ line for line in lines if (line['Sex']=='M') and (line['Salary'] > 499)]

Of course you have a lot of parsing to do to create such a python command - but this is the direction


Q:

Is there a 3rd party library that knows to convert a linq expression to a human readable string representation?

I have a linq expression and I wish to display it in the log in a human readable form. Any one knows any library that can do it? I saw this entry Creating a string from a lambda expression, but it is not that useful, in my opinion.
Thanks.
EDIT
Now that I think about it, my case is probably not that representative, because my linq expression includes a type name inside, which is expanded by the ToString to something totally monstrous, because the type is a generic one. For example, the expression e => e.TypeName == typeof(T).AssemblyQualifiedName where T is my generic context is expanded to:
"e => (e.TypeName == \"Shunra.Infra.DummyEntity.Contract.IDummyEntity`1[[System.Object, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]], Shunra.Infra.DummyEntity.Contract, Version=1.0.0.0, Culture=neutral, PublicKeyToken=807fc02bc4ce69db\")"

Looks like demanding that the assembly qualified name be nicely formatted is not fair at all...

A:

You can just use ToString, the output is fairly readable, at least to a programmer...


Q:

I am using Asp:FileUpload in Ajax updatePanel, Without updatePanel it is working fine but Giving Error with UpdatePanle

I am using Asp:FileUpload in Ajax updatePanel, Without updatePanel it is working fine, Inserting my image into DataBase but with UpdatePanel it is Giving Error (Object reference not set to an instance of an object.)
<asp:FileUpload ID="FileUploader" class="buttonGeneral" runat="server"></asp:FileUpload>

this is Where Error is.
string filePath = FileUploader.PostedFile.FileName;

A:

The solution I found is to Use a PostBack Trigger
https://www.google.com/search?&q=fileupload%20updatepanel


Q:

Perform selector with delay on main thread called from method running in background thread

I have a method which I run in the background, by calling
[self performSelectorInBackground:@selector(getTweets) withObject:nil];

'getTweets' calls a method in a wrapper class which gets the tweets and posts a notification when they're ready. I have an observer which triggers 'showTweets' when this happens.
When showTweets is called, I want to call 'hideTweets' with a delay of 5 seconds. I do this by calling:
self.hideTweetTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self  selector:@selector(hideTweet) userInfo:nil repeats:NO];

However it doesn't seem to fire. I also have a button which calls the showTweets method, but when it's pressed it seems to get stuck in the isHighlighted state.
Since the initial call was in a background thread, am I doing something wrong?
I tried
[[NSRunLoop currentRunLoop] addTimer:self.hideTweetTimer forMode:NSDefaultRunLoopMode];
[[NSRunLoop currentRunLoop] run];

Which seems to work in hiding the tweet, however this seems to cause performance issues. For example, when I load a UIScrollView in a different screen, the scrolling is very sticky.
Basically, all my problems seem to arise from performing something on a background thread, but I'm not sure what... Any help much appreciated. Thanks.

A:

Are you modifying UI elements from those threads? The only thread that should deal with the UI is the main thread. Other threads should communicate their needs to the main thread, which will actually do it for them.
You can call something back to the main thread using:
[self performSelectorOnMainThread:@selector(method) withObject:nil waitUntilDone:YES];