text:
Q: Is an inertial force needed to be added to second Newton's law when transforming from cartesian to cylindrical coordinates? Let's consider I have a particle moving on the $x,y$ plane. On this particle acts the Lorentz force, however it does not necessary perform a rotation by the axes origin $(x,y)=(0,0)$. I would like to re-write the Lorentz force in the "global" cylindrical coordinate system where  the origin $(x,y)=(0,0)$ is the same as the $r=0$. Of course the particle motion will be described by $ R=r,\phi,z$ and $u=u_r, u_{\phi}, u_z$ in that coordinate system. Should I add an inertial force in this system, such as $m\frac{du}{dt} = F_L + F_{int}$, in my description?

A: No, you should not, unless you "move" into a rotating or to another non inertial reference frame. The coordinates of a non inertial RF are expressed not only via the original ones, but also explicitly via time $t$ and in a "complicated" manner.

A: First you write the equations of motion in Inertial system $\vec{R}=[x,y]^T$
$$m\,\vec{\ddot{R}}=F_L(\vec{R},\vec{\dot{R},t,\bar{q}})\tag 1$$
$F_L$ is the Lorentz force and $\bar{q}$ the electric charge
now you can transformed equation (1) to polar coordinates with:
$\vec{R}(x,y)\mapsto\vec{R}(r,\phi)$
$\vec{\dot{R}}=\frac{\partial \vec{R}}{\partial \vec{q}}\vec{\dot{q}}$
$\vec{\ddot{R}}=\frac{\partial \vec{R}}{\partial \vec{q}}\vec{\ddot{q}}+\vec{f_z}(\vec{q},\vec{\dot{q}})$
with: $\vec{q}=[r,\phi]^T\quad$,$\vec{\dot{q}}=[\dot{r},\dot{\phi}]^T$
$\Rightarrow$ equation (1)
$$m\,\left(\frac{\partial \vec{R}}{\partial \vec{q}}\vec{\ddot{q}}+\vec{f_z}(\vec{q},\vec{\dot{q}})\right)=F_L(\vec{q},\vec{\dot{q}},t,\bar{q})\tag 2$$
multiply equation (2) from the left with $J^T=\left(\frac{\partial \vec{R}}{\partial \vec{q}}\right)^T$ we obtain :
$$m\,J^T\,J\,\vec{\ddot{q}}=J^T\,F_l-m\,J^T\,\vec{f}_z\tag 3$$
Equation (3) are the equations of motion in polar coordiantes


text:
Q: Windows form using access database I am using MS ACCESS database for my windows application. In development PC I have install Microsoft Access Database Engine. Do I need to install this on the PCs where I will be installing this windows form application. If not what is the solution to this so that my application can interact with the database like is there any dlls or anything such that need to be included in the application's reference. My database is in .accdb format not .mdb

A: For your program to interact with the Microsoft Access DB, you would have to create the DB in .accdb first. Once that is done, goto

Control Panel->Administrative Tools->Data Sources(ODBC)->System DSN.

Here select Microsoft Access Driver(*.accdb, *.mdb).A pop up window opens. There first give a name to your file.

Remember to use this name in your code to access your MS Accesss DB

Then click Add to navigate and add your .accdb file and click OK. Now your DB is live for you in local system for you to use.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is there any opensource HTTP streaming filter for DirectShow? So I have a live video from a web camera. I want to stream it onto some port using DirectShow filter. How to do such thing?

A: vlc might work for ya


text:
Q: PWC1406: Servlet.service() threw exception java.io.IOException: Invalid chunk header When client send data to server I am developing an application using J2ME to send the GPS coordinates received to the server and i am new to developing client server application.
Everything works fine with the use of Nokia N97mini or E71. But when i tried it on HTC HD2, i get the exception from the server. I am using Netbeans 6.5.1 GlassFish V2 as Server. I have no idea why this error occurs only on the HTC HD2. Any help will be greatly appreciated. Thanks...
Below is the error message:
StandardWrapperValve[FindHospitalServlet]: PWC1406: Servlet.service() for servlet FindHospitalServlet threw exception
java.io.IOException: Invalid chunk header
    at org.apache.coyote.http11.filters.ChunkedInputFilter.doRead(ChunkedInputFilter.java:171)
    at org.apache.coyote.http11.InternalInputBuffer.doRead(InternalInputBuffer.java:719)
    at org.apache.coyote.Request.doRead(Request.java:482)
    at org.apache.coyote.tomcat5.InputBuffer.realReadBytes(InputBuffer.java:342)
    at org.apache.tomcat.util.buf.ByteChunk.substract(ByteChunk.java:378)
    at org.apache.coyote.tomcat5.InputBuffer.readByte(InputBuffer.java:351)
    at org.apache.coyote.tomcat5.CoyoteInputStream.read(CoyoteInputStream.java:159)
    at java.io.DataInputStream.readUnsignedShort(DataInputStream.java:320)
    at java.io.DataInputStream.readUTF(DataInputStream.java:572)
    at java.io.DataInputStream.readUTF(DataInputStream.java:547)
    at myPackage.FindHospitalServlet.doPost(FindHospitalServlet.java:28)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
    at org.apache.catalina.core.ApplicationFilterChain.servletService(ApplicationFilterChain.java:427)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:315)
    at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:287)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:218)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:648)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:593)
    at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:94)
    at com.sun.enterprise.web.PESessionLockingStandardPipeline.invoke(PESessionLockingStandardPipeline.java:98)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:222)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:648)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:593)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:587)
    at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1096)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:166)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:648)
    at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:593)
    at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:587)
    at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:1096)
    at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:288)
    at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.invokeAdapter(DefaultProcessorTask.java:647)
    at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.doProcess(DefaultProcessorTask.java:579)
    at com.sun.enterprise.web.connector.grizzly.DefaultProcessorTask.process(DefaultProcessorTask.java:831)
    at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.executeProcessorTask(DefaultReadTask.java:341)
    at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:263)
    at com.sun.enterprise.web.connector.grizzly.DefaultReadTask.doTask(DefaultReadTask.java:214)
    at com.sun.enterprise.web.portunif.PortUnificationPipeline$PUTask.doTask(PortUnificationPipeline.java:380)
    at com.sun.enterprise.web.connector.grizzly.TaskBase.run(TaskBase.java:265)
    at com.sun.enterprise.web.connector.grizzly.ssl.SSLWorkerThread.run(SSLWorkerThread.java:106)

Below is the code that i wrote to connect to the server:
private void connectFindHospServlet()
{
    String url = "http://172.22.190.13:8080/UpdateServlet/FindHospitalServlet";
    StringBuffer sb = new StringBuffer();

    String info = lat+"!"+lng+"!";

    try
    {
        HttpConnection c = (HttpConnection) Connector.open(url);
        c.setRequestProperty("User-Agent","Profile/MIDP-2.0, Configuration/CLDC-1.0");
        c.setRequestProperty("Content-Language","en-US");
        c.setRequestMethod(HttpConnection.POST);

        DataOutputStream os = (DataOutputStream)c.openDataOutputStream();
        os.writeUTF(info);
        os.flush();
        os.close();

        // Get the response from the servlet page.
        DataInputStream is =(DataInputStream)c.openDataInputStream();

        int ch;
        sb = new StringBuffer();

        while ((ch = is.read()) != -1)
            sb.append((char)ch);

        is.close();
        c.close();

        if(sb.toString().charAt(0) == 'n')
        {
            formDisplayResultFindHosp();
            display.setCurrent(formDisplayResultFindHosp);
        }
        else
        {
            PlannerMain pm = new PlannerMain();
            hospInfo = pm.getFindHospInfo(sb.toString().substring(0, sb.length()-2));
            formDisplayResultFindHosp(hospInfo);
            display.setCurrent(formDisplayResultFindHosp);
        }
    }
    catch (Exception e)
    {
        System.out.println("Error recieve find user");
    }
}

Any information needed to better help in understanding the problem, do let me know. I will try to provide as much as possible.

A: The server is apparently attempting to read it in as a chunked stream. This can be caused by that the client has automatically set the Transfer-Encoding: chunked header because the Content-Length header has not been set before writing the request body.
So, first step to fix this problem would be setting the HTTP Content-Length header:
c.setRequestProperty("Content-Length", info.getBytes("UTF-8").length);


text:
Q: What's the meaning of "hot codepath" (or "hot code path")? I read this sentence (about computer programming):

As long as this is not in your hot codepath, the extra step should not cause issues.

What does it mean?

A: This isn't an English question, it's a programming question. It's also a duplicate of this question whose principal essential answer by Konrad Rudolph starts out this way:

Compiler hot paths are code execution paths in the compiler in which most of the execution time is spent, and which are potentially executed very often.


text:
Q: get late employee from database using entity framework I am working in web app and I have 2 table 1 employees, 2-log_time(emp_id:int , log_time :datetime ,log_type : string ) i use calendar to select date and i wont Retrieve employee that log_lime=calunder.selectedday and log time>8 am .
2-retrive late employee between two selected date ,
any idea

A: SELECT Employees.Emp_id,Employees.First_Name,Employees.Manager_Id,Log_Time.Log_Time FROM Log_Time join Employees on(Employees.Emp_id=Log_Time.Emp_Id) WHERE (convert (date,Log_Time) BETWEEN '{0}' AND '{1}') and convert(time,Log_Time.Log_Time)>='08:00:00'
this is worked


text:
Q: How to use dynamic cast with variadics? I have a working functor_wrapper class for 2 parameters that I'm having trouble generalising into variadic template parameters.
In particular, I'm having trouble getting the syntax right while converting this line in 2 parameters to variadics:
2 Parameter CODE
return m_cb( dynamic_cast<T const&>( t ), dynamic_cast<U const&>( u ));

Broken Variadic CODE
return m_cb( dynamic_cast<I const&>( t ),
                            dynamic_cast<typename... const& Cs>( u... ));

For anyone who wants to know, this wrapper class is part of a multiple_dispatch class.  In order to provide a common type/interface to the client, I have this Functor_Wrapper class and operator() that takes the parent class type.  When dispatching, I downcast by dynamic_cast<>ing the parameters down to the correct types.
UPDATE
I just realised that I have another problem:  my virtual operator() in my Parent_Functor_Wrapper needs to be converted to n parameters of P const& so I need to unroll the signature somehow!
The same applies to the concrete implementation of operator() in Functor_Wrapper.
UPDATE 2
Posting complete code so the programming context can be better understood.
UPDATE 3
Accepting ildjam's answer because it addresses the original problem.  I need to think some more about how to deal with the pure virtual operator().  Meanwhile, the code below works fine if you comment out #define USE_VARIADICS, and run the hard-coded version.  I will post a separate question if I cannot resolve this issue.
CODE
#include <typeinfo>
#include <functional>
#include <stdexcept>
#include <cassert>
#include <map>
#include <array>
#include <iostream>

#define USE_VARIADICS
#ifdef USE_VARIADICS
template<typename P,typename R,typename... Cs>
struct Parent_Functor_Wrapper
{
        using cb_func = std::function<R(P const&, P const& )>;

        virtual R operator()( P const&, P const& ) = 0;
};

// parent class, return type, concrete classes...
template<typename P,typename R,typename I,typename... Cs>
struct Functor_Wrapper :
        public Parent_Functor_Wrapper<P,R,Cs...>
{
        using cb_func = std::function<R(I const&, Cs const& ...)>;
        cb_func  m_cb;

        // dynamic_cast<typename... const& Cs>( u... ) -> dynamic_cast<Cs const&>(u)...
        Functor_Wrapper( cb_func cb ) : m_cb( cb ) { }
        virtual R operator()( P const& t, Cs const& ... u ) override
        {
                return m_cb( dynamic_cast<I const&>( t ),
                        dynamic_cast<Cs const&>( u )...);
        }
};
#else
template<typename P,typename R>
struct Parent_Functor_Wrapper
{
        using cb_func = std::function<R(P const&, P const& )>;

        virtual R operator()( P const&, P const& ) = 0;
};

template<typename P,typename R,typename T,typename U>
struct Functor_Wrapper :
        public Parent_Functor_Wrapper<P,R>
{
        using cb_func = std::function<R(T const&, U const&)>;
        cb_func  m_cb;

        Functor_Wrapper( cb_func cb ) : m_cb( cb ) { }
        virtual R operator()( P const& t, P const& u ) override
        {
                return m_cb( dynamic_cast<T const&>( t ), dynamic_cast<U const&>( u ));
        }
};
#endif

template<typename T,unsigned N>
struct n_dimension
{
        using type = typename n_dimension<T,N-1>::type;
};

template<typename T>
struct n_dimension<T,1>
{
        using type = std::tuple<T>;
};

template<typename K>
K gen_key( K* p=nullptr, size_t idx=0 )
{
        return *p;
};

template<typename K,typename T,typename... Ts>
K gen_key( K* p=nullptr, size_t idx=0 )
{
        K m_instance;
        if ( p==nullptr )
                p = &m_instance;
        *(p->begin() + idx) = typeid( T ).hash_code();
        gen_key<K,Ts...>( p, ++idx );
        return m_instance;
};

template<typename F,typename P,typename... Cs>
struct multiple_dispatcher { multiple_dispatcher() { } };

template<typename F,typename P,typename I,typename... Cs>
struct multiple_dispatcher<F,P,I,Cs...>
{
        using functor_type = Parent_Functor_Wrapper<P,std::string>;
        using key_type     = std::array<size_t,F::n_dimension::val>;
        using map_type     = std::map<key_type,functor_type*>;
        using value_type   = typename map_type::value_type;

        map_type   m_jump_table;

        multiple_dispatcher( std::initializer_list<value_type> const& cb_mapping )
        {
                for( const auto& p : cb_mapping )
                        m_jump_table.insert( p );
        }

        template< typename T, typename U >
        typename F::return_type operator()( T& x, U& y )
        {
                auto k = key_type{ { x.get_id(), y.get_id() } };
                auto func = m_jump_table.at( k );
                return (*func)( x, y );
        }

        size_t size() const { return m_jump_table.size(); }
};

// =============================================================================

struct A { virtual ~A() { }
        virtual size_t get_id() const { return typeid( A ).hash_code(); }
};
struct B : public A { virtual ~B() { }
        virtual size_t get_id() const override { return typeid( B ).hash_code(); }
};
struct C : public A { int x; virtual ~C() { }
        virtual size_t get_id() const override { return typeid( C ).hash_code(); }
};

struct Functor_Pairs
{
        using return_type = std::string;
        enum n_dimension { val = 2 };

  static std::string MyFn(A const& arg1, A const& arg2) { return "A,A"; }
  static std::string MyFn(A const& arg1, B const& arg2) { return "A,B"; }
  static std::string MyFn(A const& arg1, C const& arg2) { return "A,C"; }
  static std::string MyFn(B const& arg1, A const& arg2) { return "B,A"; }
  static std::string MyFn(B const& arg1, B const& arg2) { return "B,B"; }
  static std::string MyFn(B const& arg1, C const& arg2) { return "B,C"; }
  static std::string MyFn(C const& arg1, A const& arg2) { return "C,A"; }
  static std::string MyFn(C const& arg1, B const& arg2) { return "C,B"; }
  static std::string MyFn(C const& arg1, C const& arg2) { return "C,C"; }
};

// =============================================================================

std::string (*MyFun_aa)(A const&, A const&) = &Functor_Pairs::MyFn;
std::string (*MyFun_ab)(A const&, B const&) = &Functor_Pairs::MyFn;
std::string (*MyFun_ac)(A const&, C const&) = &Functor_Pairs::MyFn;
std::string (*MyFun_ba)(B const&, A const&) = &Functor_Pairs::MyFn;
std::string (*MyFun_bb)(B const&, B const&) = &Functor_Pairs::MyFn;
std::string (*MyFun_bc)(B const&, C const&) = &Functor_Pairs::MyFn;
std::string (*MyFun_ca)(C const&, A const&) = &Functor_Pairs::MyFn;
std::string (*MyFun_cb)(C const&, B const&) = &Functor_Pairs::MyFn;
std::string (*MyFun_cc)(C const&, C const&) = &Functor_Pairs::MyFn;

Functor_Wrapper<A,std::string,A,A>   w_aa( MyFun_aa );
Functor_Wrapper<A,std::string,A,B>   w_ab( MyFun_ab );
Functor_Wrapper<A,std::string,A,C>   w_ac( MyFun_ac );
Functor_Wrapper<A,std::string,B,A>   w_ba( MyFun_ba );
Functor_Wrapper<A,std::string,B,B>   w_bb( MyFun_bb );
Functor_Wrapper<A,std::string,B,C>   w_bc( MyFun_bc );
Functor_Wrapper<A,std::string,C,A>   w_ca( MyFun_ca );
Functor_Wrapper<A,std::string,C,B>   w_cb( MyFun_cb );
Functor_Wrapper<A,std::string,C,C>   w_cc( MyFun_cc );

// =============================================================================

int main( int argc, char* argv[] )
{
        B  b;
        C  c;

        A& arg1 = b;
        A& arg2 = c;

        using md_type = multiple_dispatcher<Functor_Pairs,A,B,C>;
        using K       = md_type::key_type;

        md_type  md
        {
                std::make_pair( gen_key<K,A,A>(), &w_aa ),
                std::make_pair( gen_key<K,A,B>(), &w_ab ),
                std::make_pair( gen_key<K,A,C>(), &w_ac ),
                std::make_pair( gen_key<K,B,A>(), &w_ba ),
                std::make_pair( gen_key<K,B,B>(), &w_bb ),
                std::make_pair( gen_key<K,B,C>(), &w_bc ),
                std::make_pair( gen_key<K,C,A>(), &w_ca ),
                std::make_pair( gen_key<K,C,B>(), &w_cb ),
                std::make_pair( gen_key<K,C,C>(), &w_cc )
        };

        std::cerr << "N = " << md.size() << std::endl;
        std::cerr << "RESULT = " << md( arg1, arg2 ) << std::endl;

        assert( !std::string( "B,C" ).compare( md( arg1, arg2 )) );

#if 0
        std::cerr << typeid( A ).hash_code() << std::endl;
        std::cerr << typeid( B ).hash_code() << std::endl;
        std::cerr << typeid( C ).hash_code() << std::endl;
#endif

        return 0;
}

A: You need to change:
dynamic_cast<typename... const& Cs>( u... )

to:
dynamic_cast<Cs const&>( u )...

The former (invalid syntax aside) is attempting to expand Cs into a single dynamic_cast while the latter expands each type in Cs into its own dynamic_cast.
That being said, I don't think your override will work since your base's operator() signature is R operator()( P const&, P const& ) and your derived's signature is not (unless Cs const&... coincidentally happens to expand into P const&)…


text:
Q: sonar-scala github repo has been archived The sonar-scala repo has a note

This repository has been archived by the owner on Jan 30, 2023. It is now read-only

The last commit was made on on May 10, 2022. It is no longer possible to submit issue. Hope  its is OK to ask for support here.
Installed Sonarqube Community Edition v9.8.0 using helm-chart-sonarqube.
I added the sonar-scala plugin  with this helm custom value
plugins:
 install:
   - "https://s01.oss.sonatype.org/content/repositories/releases/com/sonar-scala/sonar-scala_2.13/9.0.0/sonar-scala_2.13-9.0.0-assembly.jar"

Which is equivalent to copying the *.jar into /opt/sonarqube/extensions/plugins directory and restart the Sonarqube server.
The server failed to start because of this error
2023.02.05 05:23:41 ERROR web[][o.s.s.p.Platform] Background initialization failed. Stopping SonarQube
org.springframework.beans.factory.BeanCreationException: Error creating bean with name '
jdk.internal.loader.ClassLoaders$AppClassLoader@1d44bcfa-org.sonar.server.language.LanguageValidation':
Initialization of bean failed; nested exception is java.lang.IllegalStateException:
There are two languages declared with the same key 'scala' declared by the plugins 'scala' and 'sonarscala'.
Please uninstall one of the conflicting plugins.

It seems there is no possibility to uninstall the built-in sonarscala. Is there a way to make the sonar-scala plugin work in conjunction with sonarscala. In case I must only use the default sonarscala how is it compared to the sonar-scala plugin, in terms of features and quality?


text:
Q: Triggering table update javascript function for a table row separate from the html? I'm trying to keep a strict separation of javascript with html merging together and my current issue is that I have multiple html tables on a page, whenever you click on a box in the table it is editable and should on clicking off the box update the table sending the information to the SQL database dynamically.
Now my issue is that the way I currently have it doing it which is inside the html row is not something I'm a fan of as shown below:
onblur="update_table(this, 'column name', 'row id', 'sql table name')"

I'm trying to work out how I can give the function this information without passing it through directly as variables into the function.
So rather than having a trigger onblur, have a listener in the javascript,
something like this:
 $('.A Class Name for rows or something').on('blur', function () {

My thought process is that I should have a specific class name that all rows have so that it listens in on that class name? Now I'm just wondering how I get the information from the row like column name, row id and what sql table it needs to go to.
Please let me know if this doesn't make sense!

A: To add metadata to an element you can use data attributes. Then you can read those from the element when the event occurs on it. Try this:
<input type="text" class="foo" data-columnname="column name" data-rowid="row id" data-sqltablename="sql table name" />

$('.foo').on('blur', function() {
  var $el = $(this);
  update_table(this, $el.data('columnname'), $el.data('rowid'), $el.data('sqltablename'));
});

It's also worth noting that there's a couple of potential code smells here. Firstly, either pass the element reference (ie. this) to the function or the relevant properties, not both. Secondly, requiring both the 'table name' and 'column name' in the client-side function is a little odd. It's also potentially an attack vector exposing this information to any user viewing the site.

A:
Now I'm just wondering how I get the information from the row like column name, row id and what sql table it needs to go to.

My first instinct is that information shouldn't be in the HTML at all. And whether it is or not, any updates to the DB should be rigorously checked, since the client side of this is infinitely hackable. But including that information in the HTML makes it easier to hack.
You could replace your onblur with data-* attributes on the row. Instead of the onblur, you might have:
data-column="column name" data-rowid="row id" data-table="sql table name"

or
data-q="sql table name,column name,rowid"

or similar.
Then you could have a class on the table that says you should do this blur behavior, and use event delegation to catch blur from cells in tables where you've enabled this:
$(document.body).on("blur", ".handle-blur td", function() {
    var q = $(this).attr("data-q"); // ...or the individual ones...
    // ...call `update_table` here...
});

But, again, I don't think I'd put this in the HTML at all. I'd probably reach for some kind of MVC or MVVM solution (React, etc.) so the information wasn't quite as exposed. It doesn't change the need to rigorously validate on the server side, but it helps a bit with obscurity.


text:
Q: How to draw the material Sliding Tabs with navigation drawer and custom icon on toolbar?
I want a layout exactly like this.I have searched a lot about this and tried the following links.

*

*Android 5.0 material tabs with toolbar

*Material tabs with toolbar like design
This is my code I have tried so far.
MainActivity
import android.os.Bundle;
import android.support.design.widget.NavigationView;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
import android.widget.Toast;

import com.astuetz.PagerSlidingTabStrip;

public class MainActivity extends AppCompatActivity {

    NavigationView navigationView;
    DrawerLayout drawerLayout;
    ActionBarDrawerToggle actionBarDrawerToggle;
    Toolbar mToolbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mToolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(mToolbar);
        getSupportActionBar().setDisplayShowHomeEnabled(true);

        navigationView = (NavigationView) findViewById(R.id.nvView);
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        ViewPager pager = (ViewPager) findViewById(R.id.pager);
        if (pager != null) {
            pager.setAdapter(new SampleFragmentPagerAdapter(getSupportFragmentManager()));
        }

        // Bind the tabs to the ViewPager
        PagerSlidingTabStrip tabs = (PagerSlidingTabStrip) findViewById(R.id.tabs);
        if (tabs != null) {
            if (pager != null) {
                tabs.setViewPager(pager);
            }
        }

        navigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
            @Override
            public boolean onNavigationItemSelected(MenuItem menuItem) {

                if (menuItem.isChecked()) menuItem.setChecked(false);
                else menuItem.setChecked(true);

                drawerLayout.closeDrawers();

                switch (menuItem.getItemId()) {

                    case R.id.home:

                        Toast.makeText(getApplicationContext(), "Home Selected", Toast.LENGTH_SHORT).show();

                        return true;

                    case R.id.about:

                        Toast.makeText(getApplicationContext(), "About Us Selected", Toast.LENGTH_SHORT).show();
                        return true;

                    case R.id.Share:

                        Toast.makeText(getApplicationContext(), "Share Selected", Toast.LENGTH_SHORT).show();
                        return true;

                    default:

                        Toast.makeText(getApplicationContext(), "Somethings Wrong", Toast.LENGTH_SHORT).show();
                        return true;

                }
            }
        });

        actionBarDrawerToggle = new ActionBarDrawerToggle(this, drawerLayout, R.string.open, R.string.close) {

            @Override
            public void onDrawerClosed(View drawerView) {

                super.onDrawerClosed(drawerView);
            }

            @Override
            public void onDrawerOpened(View drawerView) {

                super.onDrawerOpened(drawerView);

            }
        };
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
            case android.R.id.home:
                int id = item.getItemId();

                if (drawerLayout.isDrawerOpen(navigationView))
                {
                    drawerLayout.closeDrawer(navigationView);
                }
                else
                {
                    drawerLayout.openDrawer(navigationView);
                }

        }
        return super.onOptionsItemSelected(item);

    }

    @Override
    protected void onPostCreate(Bundle savedInstanceState) {
        super.onPostCreate(savedInstanceState);
        actionBarDrawerToggle.syncState();
    }

    public static class SampleFragmentPagerAdapter extends FragmentPagerAdapter{

        final int PAGE_COUNT = 3;
        private String tabTitles[] = new String[] { "Tab1", "Tab2", "Tab3" };

        public SampleFragmentPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public int getCount() {
            return PAGE_COUNT;
        }

        @Override
        public Fragment getItem(int position) {
            return PageFragment.newInstance(position + 1);
        }

        @Override
        public CharSequence getPageTitle(int position) {
            // Generate title based on item position
            return tabTitles[position];
        }

        public static class PageFragment extends Fragment {
            private int mPage;
            public static final String ARG_PAGE = "ARG_PAGE";

            public static PageFragment newInstance(int page) {
                Bundle args = new Bundle();
                args.putInt(ARG_PAGE, page);
                PageFragment fragment = new PageFragment();
                fragment.setArguments(args);
                return fragment;
            }

            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                mPage = getArguments().getInt(ARG_PAGE);
            }

            // Inflate the fragment layout we defined above for this fragment
// Set the associated text for the title
            @Override
            public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
                View view = inflater.inflate(R.layout.custom, container, false);
                TextView tvTitle = (TextView) view.findViewById(R.id.text);
                tvTitle.setText("Fragment #" + mPage);
                return view;
            }

    }
}
}

activity_main
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clickable="true"
    android:focusableInTouchMode="true">

    <android.support.design.widget.CoordinatorLayout
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/overview_coordinator_layout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

            <android.support.v7.widget.Toolbar
                android:id="@+id/toolbar"
                android:layout_width="match_parent"
                android:layout_height="?attr/actionBarSize"
                android:background="?attr/colorPrimaryDark"
                app:layout_scrollFlags="enterAlways|scroll" />

        </android.support.design.widget.AppBarLayout>

        <com.astuetz.PagerSlidingTabStrip
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="48dip"
            />

        <android.support.v4.view.ViewPager
            android:id="@+id/pager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_below="@+id/tabs"
            tools:context=".MainActivity" />

    </android.support.design.widget.CoordinatorLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/nvView"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@android:color/white"
        app:menu="@menu/drawer" />

</android.support.v4.widget.DrawerLayout>

With this code I am just getting navigation drawer without navigation Icon and no viewpager is implemented with this.

A: Try this tutorial I think it will help you ..
https://codelabs.developers.google.com/codelabs/material-design-style/index.html?index=..%2F..%2Findex#0


text:
Q: PSQL - Iterate over table and return results as table
Working on a table with columns
some_id, some_parent_id, some_param.
I need to create a procedure or function that accept some_id as input and searches for its parent row.
When parent row is found, it will search again for parent row of that row... and so on...until parent row is null.
Function should returns all entries found during iteration.

So in this case if a function is called with value 3 it will return rows 2 and 1 and stop there cause some_parent_id is null
This is my attempt at storing results in temp table but all i get is NULL. What am I missing?
CREATE OR REPLACE FUNCTION my_function(
    input_id int)
RETURNS TABLE(
    r_id int,
    r_parent_id int,
    r_param int,
) AS $$
    DECLARE
        temp_table record;
        search_id int;
    begin
        search_id := input_id;
        for temp_table in (
            select some_id, some_parent_id, some_param FROM mytable where some_id = search_id)
        loop
            search_id := temp_table.some_parent_id;
            return next;
        end loop;
        return;
    END;
$$ LANGUAGE plpgsql;

select * from  my_function (3754);

I appreciate any help

A: One option uses a recursive query instead of a loop:
with recursive cte as (
    select some_id, some_parent_id, some_param
    from mytable
    where some_id = input_id
    union all
    select t.some_id, t.some_parent_id, t.some_param
    from mytable t
    inner join cte c on t.some_id = c.some_parent_id
)
select * from cte

You can use this query in your function as follows:
create or replace function my_function(input_id int)
returns table(
    r_id int,
    r_parent_id int,
    r_param text
) as $$
with recursive cte as (
    select some_id, some_parent_id, some_param
    from mytable
    where some_id = input_id
    union all
    select t.some_id, t.some_parent_id, t.some_param
    from mytable t
    inner join cte c on t.some_id = c.some_parent_id
)
select * from cte
$$
language sql;

Demo on DB Fiddle with your sample data:
select * from my_function(2);

| r_id | r_parent_id | r_param |
| ---- | ----------- | ------- |
| 2    | 1           | value2  |
| 1    |             | value1  |


text:
Q: RefineryCMS integration with existing Rails 3.1+ app I am following the guide at RefineryCMS site and when I try to rails generate refinery:cms I keep getting this error:
`require': cannot load such file -- refinerycms-base (LoadError)

The Gemfile looks as follows:
    source 'https://rubygems.org'
gem 'rails', '3.2.2'
gem 'devise' #,'~> 1.4.0'
# Bundle edge Rails instead:
# gem 'rails'#, :git => 'git://github.com/rails/rails.git'

gem 'sqlite3'
#gem 'refinerycms'#, :git => 'git://github.com/resolve/refinerycms.git'
gem 'refinerycms-core'#,       :git => 'git://github.com/resolve/refinerycms.git'
  gem 'refinerycms-dashboard'#,  :git => 'git://github.com/resolve/refinerycms.git'
  gem 'refinerycms-images'#,     :git => 'git://github.com/resolve/refinerycms.git'
  gem 'refinerycms-pages'#,      :git => 'git://github.com/resolve/refinerycms.git'
  gem 'refinerycms-resources'#,  :git => 'git://github.com/resolve/refinerycms.git'
  gem 'refinerycms-settings'#,  :git => 'git://github.com/parndt/refinerycms-settings.git'
    gem 'refinerycms-generators'#, :git => 'git://github.com/resolve/refinerycms-generators.git'

# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'

  # See https://github.com/sstephenson/execjs#readme for more supported runtimes
  # gem 'therubyracer'

  gem 'uglifier', '>= 1.0.3'
end

gem 'jquery-rails'

# To use ActiveModel has_secure_password
# gem 'bcrypt-ruby'#, '~> 3.0.0'

# To use Jbuilder templates for JSON
# gem 'jbuilder'

# Use unicorn as the app server
# gem 'unicorn'

# Deploy with Capistrano
# gem 'capistrano'

# To use debugger
# gem 'ruby-debug19'#, :require => 'ruby-debug'

I tried both paths - gems from github and just gems, but not luck...
EDIT:
Had to create passwords_controller.rb and users_controller.rb with the same syntax (names change respectively):
class UsersController < Devise::SessionsController
end

Now stuck at the very last step of example at http://refinerycms.com/guides/attaching-refinery-cms-as-part-of-a-larger-rails-31x-devise
Getting :
uninitialized constant Refinery::Role

When I try to run the server for the first time..
Full trace:
refinerycms-core (2.0.1) lib/refinery/application_controller.rb:53:in `just_installed?'
refinerycms-core (2.0.1) lib/refinery/application_controller.rb:73:in `refinery_user_required?'
activesupport (3.2.2) lib/active_support/callbacks.rb:418:in `_run__3443719849843969127__process_action__2929810487798718614__callbacks'
activesupport (3.2.2) lib/active_support/callbacks.rb:405:in `__run_callback'
activesupport (3.2.2) lib/active_support/callbacks.rb:385:in `_run_process_action_callbacks'
activesupport (3.2.2) lib/active_support/callbacks.rb:81:in `run_callbacks'
actionpack (3.2.2) lib/abstract_controller/callbacks.rb:17:in `process_action'
actionpack (3.2.2) lib/action_controller/metal/rescue.rb:29:in `process_action'
actionpack (3.2.2) lib/action_controller/metal/instrumentation.rb:30:in `block in process_action'
activesupport (3.2.2) lib/active_support/notifications.rb:123:in `block in instrument'
activesupport (3.2.2) lib/active_support/notifications/instrumenter.rb:20:in `instrument'
activesupport (3.2.2) lib/active_support/notifications.rb:123:in `instrument'
actionpack (3.2.2) lib/action_controller/metal/instrumentation.rb:29:in `process_action'
actionpack (3.2.2) lib/action_controller/metal/params_wrapper.rb:205:in `process_action'
activerecord (3.2.2) lib/active_record/railties/controller_runtime.rb:18:in `process_action'
actionpack (3.2.2) lib/abstract_controller/base.rb:121:in `process'
actionpack (3.2.2) lib/abstract_controller/rendering.rb:45:in `process'
actionpack (3.2.2) lib/action_controller/metal.rb:203:in `dispatch'
actionpack (3.2.2) lib/action_controller/metal/rack_delegation.rb:14:in `dispatch'
actionpack (3.2.2) lib/action_controller/metal.rb:246:in `block in action'
actionpack (3.2.2) lib/action_dispatch/routing/route_set.rb:67:in `call'
actionpack (3.2.2) lib/action_dispatch/routing/route_set.rb:67:in `dispatch'
actionpack (3.2.2) lib/action_dispatch/routing/route_set.rb:30:in `call'
journey (1.0.3) lib/journey/router.rb:68:in `block in call'
journey (1.0.3) lib/journey/router.rb:56:in `each'
journey (1.0.3) lib/journey/router.rb:56:in `call'
actionpack (3.2.2) lib/action_dispatch/routing/route_set.rb:594:in `call'
railties (3.2.2) lib/rails/engine.rb:479:in `call'
railties (3.2.2) lib/rails/railtie/configurable.rb:30:in `method_missing'
journey (1.0.3) lib/journey/router.rb:68:in `block in call'
journey (1.0.3) lib/journey/router.rb:56:in `each'
journey (1.0.3) lib/journey/router.rb:56:in `call'
actionpack (3.2.2) lib/action_dispatch/routing/route_set.rb:594:in `call'
warden (1.1.1) lib/warden/manager.rb:35:in `block in call'
warden (1.1.1) lib/warden/manager.rb:34:in `catch'
warden (1.1.1) lib/warden/manager.rb:34:in `call'
actionpack (3.2.2) lib/action_dispatch/middleware/best_standards_support.rb:17:in `call'
rack (1.4.1) lib/rack/etag.rb:23:in `call'
rack (1.4.1) lib/rack/conditionalget.rb:25:in `call'
actionpack (3.2.2) lib/action_dispatch/middleware/head.rb:14:in `call'
actionpack (3.2.2) lib/action_dispatch/middleware/params_parser.rb:21:in `call'
actionpack (3.2.2) lib/action_dispatch/middleware/flash.rb:242:in `call'
rack (1.4.1) lib/rack/session/abstract/id.rb:205:in `context'
rack (1.4.1) lib/rack/session/abstract/id.rb:200:in `call'
actionpack (3.2.2) lib/action_dispatch/middleware/cookies.rb:338:in `call'
dragonfly (0.9.10) lib/dragonfly/cookie_monster.rb:9:in `call'
activerecord (3.2.2) lib/active_record/query_cache.rb:64:in `call'
activerecord (3.2.2) lib/active_record/connection_adapters/abstract/connection_pool.rb:443:in `call'
actionpack (3.2.2) lib/action_dispatch/middleware/callbacks.rb:28:in `block in call'
activesupport (3.2.2) lib/active_support/callbacks.rb:405:in `_run__3630594588424266621__call__617064894437263144__callbacks'
activesupport (3.2.2) lib/active_support/callbacks.rb:405:in `__run_callback'
activesupport (3.2.2) lib/active_support/callbacks.rb:385:in `_run_call_callbacks'
activesupport (3.2.2) lib/active_support/callbacks.rb:81:in `run_callbacks'
actionpack (3.2.2) lib/action_dispatch/middleware/callbacks.rb:27:in `call'
dragonfly (0.9.10) lib/dragonfly/middleware.rb:13:in `call'
rack-cache (1.2) lib/rack/cache/context.rb:136:in `forward'
rack-cache (1.2) lib/rack/cache/context.rb:245:in `fetch'
rack-cache (1.2) lib/rack/cache/context.rb:185:in `lookup'
rack-cache (1.2) lib/rack/cache/context.rb:66:in `call!'
rack-cache (1.2) lib/rack/cache/context.rb:51:in `call'
actionpack (3.2.2) lib/action_dispatch/middleware/reloader.rb:65:in `call'
actionpack (3.2.2) lib/action_dispatch/middleware/remote_ip.rb:31:in `call'
actionpack (3.2.2) lib/action_dispatch/middleware/debug_exceptions.rb:16:in `call'
actionpack (3.2.2) lib/action_dispatch/middleware/show_exceptions.rb:56:in `call'
railties (3.2.2) lib/rails/rack/logger.rb:26:in `call_app'
railties (3.2.2) lib/rails/rack/logger.rb:16:in `call'
actionpack (3.2.2) lib/action_dispatch/middleware/request_id.rb:22:in `call'
rack (1.4.1) lib/rack/methodoverride.rb:21:in `call'
rack (1.4.1) lib/rack/runtime.rb:17:in `call'
activesupport (3.2.2) lib/active_support/cache/strategy/local_cache.rb:72:in `call'
rack (1.4.1) lib/rack/lock.rb:15:in `call'
actionpack (3.2.2) lib/action_dispatch/middleware/static.rb:61:in `call'
railties (3.2.2) lib/rails/engine.rb:479:in `call'
railties (3.2.2) lib/rails/application.rb:220:in `call'
rack (1.4.1) lib/rack/content_length.rb:14:in `call'
railties (3.2.2) lib/rails/rack/log_tailer.rb:14:in `call'
rack (1.4.1) lib/rack/handler/webrick.rb:59:in `service'

Thanks!

A: Try removing refinerycms-generators from your Gemfile. This gem is now obsolete as the generators were moved into refinerycms-core


text:
Q: Undefined Local Variable or Method 'food' Working in Ruby, I'm getting an error saying
'add': undefined local variable or method 'food' for #<FoodDB:...

This is the code I'm trying to run
require_relative 'FoodDB.rb'

class Manager
  def initialize
     food = FoodDB.new
     self.create_foodDB(food)
  end

  def create_foodDB(food)
    counter = 1
    word = []
    file = File.new("FoodDB.txt","r")
    while (line = file.gets)
      food.addFood(line)
      counter = counter + 1
    end
    file.close
  end
end

manager = Manager.new

input_stream = $stdin
input_stream.each_line do |line|
  line = line.chomp
  if line == "quit"
    input_stream.close
  end
end

This is FoodDB.rb's code
class FoodDB
  def initialize
    food = []
  end

  def addFood(str)
    food.push(str)
  end
end

I'm not sure what's the problem since it seems like I'm definitely calling the correct method from the FoodDB class. All help is appreciated, thank you!

A: You need to change food in the FoodDB class to an instance variable:
class FoodDB
  def initialize
    @food = []
  end

  def addFood(str)
    @food.push(str)
  end
end

An instance variable will be available throughout all methods of an instance, while the food variable you used was local to its lexical scope, i.e. only available within the initialize method.


text:
Q: Maxima of sum of exponential. I want to find the maxima of $f=e^{-x}+e^{-2x}$, $x \ge 0$. I know the maximum happens at $x=0$, however when I differentiate and equate to zero I get : $\,e^{x}=-2$ which leads to $x=\ln(-2)$. Can any one point why the differentiation method doesn't lead to the correct answer?

A: Note that $$f'(x)=-e^{-x}-2e^{-2x}=-e^{-2x}(e^x+2)=-\frac{e^x+2}{e^{2x}}$$ is negative for all $x$ in the domain of definition of $f$, so $f$ is strictly decreasing. Then $f$ has a maximum precisely if its given domain of definition has a least element, in this case $0$.
We can only use the first derivative test (setting the first derivative equal to $0$ and solving) at points on the interior of the domain of definition. Indeed, your work shows that $f$ has no maximum on the positive numbers. However, if we look to the single boundary point of the domain of definition (namely $x=0$), we can manually show that $f$ has a maximum there (using an argument like the one I gave above). We simply can't apply the first derivative test there, and this example is an excellent reason why.
More generally, suppose $D\subseteq\Bbb R$, and that $g:D\to\Bbb R$ is a function that is differentiable in the interior of $D$ and continuous on $D$. Then if $g$ obtains a maximum, it will be either at a critical point in the interior of $D$, or at a point on the boundary of $D$.

A: Let $f(x)= e^{-x}+e^{-2x}$ then
$$
f'(x)=-e^{-x}-2e^{-2x}=-e^{-x}( 1+2e^{-x})=0
$$
implies
$
( 1+2e^{-x})=0
$ or $
e^{-x}=0
$. But it's impossible.  Then $f(x)$  doesn't have a minimum in $\mathbb{R}$. And as we know that $f$ is decreasing, $f$ has no minimum in $(0,\infty)$!


text:
Q: How do I prevent internet explorer from rewriting my text? I have a javascript variable that contains an url, populated by outputting a script tag from php. The intention is to change the webpage to that url under certain circumstances.
var url = "/somepage?q=3&region=1";
The problem is that the url contains the sequence "&reg" which internet explorer changes to "®" without being asked.
I've tried escaping the whole url with htmlspecialchars, which breaks other browsers. Turning off quirks mode might help, but it's not an option with the current system. Adding  to the script tag did nothing.
edit:
I figured out one solution, "escaping" the url with concatenation.
var url = '<?php implode( "&'+'", explode( '&', '/somepage?q=3&region=1' ) ); ?>';
I also realized I should probably mention how I change the page:
document.location.href = url;
edit:
Turns out I had an error in my script tag. A minimal example that shows the same "problem":
<script type="text/javascript" />
    var url = "/test?mode=preview&region=1";
</script>

The self-closing start tag is the important thing here.

A: It should be var url = "/somepage?q=3&region=1";
Always use & in URLs so the browser understands this a query separator and doesn't think it refers to some htmlentity (the problem here is IE doesn't care if the semicolon is present or not and assumes &reg should be ®)
EDIT: the real context was added after I answered and as pointed out in the question itself and in comments, you shouldn't use & if you intend to use the variable to redirect using some window.location
BUT, since we have PHP at hand, I would suggest using some PHP code like this if the javascript redirect is not part of some other complex script:
<?php
header('Location: http://domain/somepage?q=3&region=1');
exit();
?>


text:
Q: Problem with this for loop || ValueError: I/O operation on closed file. || I am geting this error message when I execute the following code in Pyhton.

"ValueError: I/O operation on closed file."

I can't get it to read the tasks.txt file and I can't seem to fix it.
elif menu == 'va':
            task_list = open("tasks.txt", "r+") #opens task file
            for line in task_list:
                assignee, title, description, due_date, date, completed = line.split(", ")
                print(f'''
                Name: {assignee}
                Title: {title}
                Description: {description}
                Due Date: {due_date}
                Date Assigned: {date}
                Task Complete: {completed}''')
                task_list.close()

Any help greatly appreciated.
I tried to indent the task-list.close() file so that it is outside of the for loop as looking on here I think that might be causing it to close before it can print. I'm not sure.

A: task_list.close() closes the file, meaning that subsequent calls to task_list will fail with the IO error you are seeing.
You should de-dent this to move it outside the loop, so that it will only close the file once the loop has finished executing
elif menu == 'va':
            task_list = open("tasks.txt", "r+") #opens task file

            #start loop through file
            for line in task_list:
                assignee, title, description, due_date, date, completed = line.split(", ")
                print(f'''
                Name: {assignee}
                Title: {title}
                Description: {description}
                Due Date: {due_date}
                Date Assigned: {date}
                Task Complete: {completed}''')

            #loop has finished - close file
            task_list.close()

Alternatively, you can let Python do all of the work for managing the file state for you! By using a with block, we tell the interpreter that we need the file open whilst we are in the block - and when it reaches the end of the block, the file is closed automatically.
Updated code:
elif menu == 'va':
            with open("tasks.txt", "r+") as task_list: #open file

                #begin loop
                for line in task_list:
                    assignee, title, description, due_date, date, completed = line.split(", ")
                    print(f'''
                    Name: {assignee}
                    Title: {title}
                    Description: {description}
                    Due Date: {due_date}
                    Date Assigned: {date}
                    Task Complete: {completed}''')

            #with has finished, so file is automatically closed


text:
Q: Pages in Printing Is it possible to know which page I am printing in MS Word? Or which page has been printed recently? I am trying to find out using vsto. There are methods like Application.PrintOut()
and property like Application.PrintPreview but nothing to find which page I am printing.


text:
Q: How to conditional select table rows using SQL How do I query this table if I wanna select rows with same CHANGE_KEY and SYSTEM_KEY = 1 and SERVER_KEY = 2, to clarify I'm not interesting in rows with only SYSTEM_KEY = 1 like the first row in the following table because SERVER_KEY = 2 is also needed, a correct result table will only contain the two last rows in the following table because the CHANGE_KEY 4 has both SYSTEM_KEY=1 and SERVER_KEY=2
   CHANGE_KEY  SYSTEM_KEY  SERVER_KEY  HARDWARE_KEY
    ----------- ----------- ----------- ------------
    1           1           NULL        NULL
    1           NULL        1           NULL
    1           NULL        NULL        1
    2           NULL        1           NULL
    3           NULL        1           NULL
    4           NULL        1           NULL
    5           NULL        1           NULL
    5           NULL        1           NULL
    4           NULL        2           NULL
    4           1           NULL        NULL

A: Unless I'm missing something, it's as easy as this.
Select * From MyTable Where Change_Key = 4 AND (System_Key = 1 OR System_Key = 2)

A: SELECT * FROM
table
WHERE CHANGE_KEY = 4
AND
    (
     SYSTEM_KEY = 1
     OR
     SERVER_KEY = 2
    )

EDIT: I made changes, following your edit.

A: SELECT *
FROM mytable
WHERE CHANGE_KEY = 4
AND (SYSTEM_KEY = 1
OR SERVER_KEY = 2)

Edit: You've edited the question to say that the last two rows in the table should be in the result-set.  However, an AND will not achieve this, I believe you're looking for an OR so have modified my response.

A: SELECT * FROM your_table WHERE change_key = 4 AND system_key = 1 AND server_key = 2

A: In MySql, i would write something like this:
SELECT * FROM table_name WHERE CHANGE_KEY=4 AND SYSTEM_KEY=1 AND SERVER_KEY=2;

A: SELECT * FROM table_name WHERE change_key = 4 AND system_key = 1 AND system_key = 2


text:
Q: How can I do a action when I hover a different tag or element? CSS only How can I select a div when I hover a child h1 with css3 only.
I want the div to have a animated opacity:0, done with keyframes. I can do the keyframes part by myself. Just need help with the selection.

A: Ho ho .... the thing that you are asking is known as JS dom manipulation. For that a language is developed -- JavaScript. Any selection of HTML element and further manipulation is out of scope of CSS. It is only for styling and not for node manipulation dear!
Try out jQuery with .parentsUntil selector and your problem will be solved. Also, there is no such selector which would turn heel from end element to go to parent by CSS only. Though with SASS/LESS there may be some possibliites. But only CSS3 -- Nil, ie 0.

A: Does something simple like that work as you wish?

.wrapper{
  background:red;
  transition: opacity 1s ease-in-out;
}
.header:hover {
  opacity: 0.5;
}

Title


text:
Q: Decimal to Binary C I have to write a C program that converts decimal to binary using numbers between 0 to 255. using 3 functions and no global variables. When I get it to run it just prints all zeros for some reason. This is what I have so far:
#include <stdio.h>

int getNumber();
int dectoBin(int, int binarray[], int);
void printBin(int binary[], int dec);

int main(){
    int M = 7;
    int binarray[M];
    int dec = getNumber();
    printf("The decimal number you entered was: %d", dec);
    *binarray = decToBin(dec, binarray, M);
    printBin(binarray, dec);
    return 0;
}

int getNumber(){
    int dec;
    printf("Enter any a number between 0 and 255: ");
    scanf("%d",&dec);
    return 0;
}

int decToBin(int dec, int binarray[], int M){
    int i, j;
    if(dec>255)
        printf("Please enter a number between 0 and 255");
    else
        for(i=7; i>=0;i--){
            j = dec >>i;
            if(j & 1){
                binarray[i] = 1;
            }
            else {
                binarray[i] = 0;
            }
        }
    return *binarray;
}

void printBin(int binary[], int dec){
    int i;
    if(dec > 255){
        printf("PLese use another number");
        main();
    }
    else
    {
        for(i =7; i > 0;i--){
            printf("%d", binary[i]);
            printf("\n");
        }
    }

}

A: In your function:
int getNumber(){
int dec;
printf("Enter any a number between 0 and 255: ");
scanf("%d",&dec);
return 0;
}

You return 0, you should return dec:
int getNumber(){
int dec;
printf("Enter any a number between 0 and 255: ");
scanf("%d",&dec);
return dec;
}

A: In printBin you only prints 7 bits instead of 8 bits.
Change for(i =7; i > 0;i--){ to for(i = 7; i >= 0; i--){
And in main change: int M = 7; to int M = 8;. You need 8 bits for the range 0..255.
*binarray = decToBin(dec, binarray, M); is plain wrong and not necessary, write decToBin(dec, binarray, M) ;. The decToBin function takes already care of filling the binarray array.
Otherwise the architecture of your program is poor:

*

*The test if the input is between 0 and 255 should be in getNumber or
in main, but not in printBin.

*The call to main() inside the printBin function is completely
wrong, even if the program works correctly.
I leave this as an exercise to the reader to find out why.


text:
Q: Question regarding Unix/Linux kernel programming I would like to learn about linux/Unix kernel programming for scalable multi processors (smps). I found this book UNIX(R) Systems for Modern Architectures http://www.amazon.com/UNIX-Systems-Modern-Architectures-Multiprocessing/dp/0201633388/ref=pd_rhf_p_t_3 . Is there any other good resources or a better book since its released in 1994. Thank you very much in advance.
Thanks & Regards,
Mousey.

A: Definitely buy this excellent book! You will get thorough introduction into:

*

*caches, their types, and how to deal with them in the kernel,

*synchronization and what hardware primitives are behind it,

*general kernel designs as related to concurrency (cli/sti, giant lock, cli+spinlock, etc.)

The book is general enough not to be out of date by now. The only thing I don't remember mentioned there is NUMA, but I don't think there are any good published texts on this subjects yet except for maybe Gorman's Linux memman paper (somebody correct me if I'm wrong here).
I think the book was really worth the money.

A: Understanding the Linux Kernel is a great book about how the Linux kernel is built, it describes Linux 2.2, 2.4 and 2.6 (Third Edition).
If you want to make drivers, there's Linux Device Drivers , and is also a reference about how Linux is built.

A: For Linux, Rusty's Unreliable Guide to Kernel Locking is a must-read. After that, you can also read the file Documentation/spinlocks.txt located in the Linux kernel sources.


text:
Q: Why is the infimum in the Hopf-Lax formula a minimum? It is said in Evan's Partial Differential Equations that the Hopf-Lax formula
$$
u(x,t)=\inf_{y\in{\Bbb R}^n}\left\{tL(\frac{x-y}{t})+g(y)\right\}
$$
is actually a minimum where $g$ is assumed to be Lipschitz continuous and the Lagragian $L$ is convex and
$$
\lim_{|v|\to\infty}\frac{L(v)}{|v|}=\infty.
$$
Question: why is this true?

A quick search for "Hopf-Lax formula" in Google returns the following proof, which looks promising:

But it seems to me that it proves nothing since the formula underscored is true for all $y\in{\Bbb R}^n$ by the definition of the infimum.

A: Fix $x,t$. Observe that the function
$$\varphi(y):=tL\left(\dfrac{x-y}{t}\right)+g(y),\ y\in\mathbb{R}^{n}$$
is continuous, being the sum of the two continuous functions. Using the hypothesis that $g$ is Lipschitz, we have the estimate
$$\varphi(y)\geq tL\left(\dfrac{x-y}{t}\right)-\left\|g\right\|_{Lip}\left|y-x\right|-\left|g(x)\right|=\left|x-y\right|\left[\dfrac{L\left(\frac{x-y}{t}\right)}{\frac{\left|x-y\right|}{t}}-\left\|g\right\|_{Lip}-\dfrac{\left|g(x)\right|}{\left|x-y\right|}\right]$$
I claim that the expression in brackets tends to $+\infty$ as $\left|y\right|\rightarrow+\infty$. Indeed, it is clear that $\lim\frac{\left|g(x)\right|}{\left|x-y\right|}=0$ and $\lim \dfrac{L(\frac{x-y}{t})}{\frac{\left|x-y\right|}{t}}=+\infty$ by hypothesis. Whence, there exists an $R>0$ such that $\left|y\right|>R$ implies that $\varphi(y)>u(x,t)+\delta$, for fixed $\delta>0$.
By Weierstrass' extreme value theorem, $\varphi$ attains its minimum on the closed ball $\overline{B}(0,R)$ at some point $y_{*}$. And by definition of infimum, there exists $y'\in\overline{B}(0,R)$ such that $\varphi(y')<u(x,t)+\delta/2$. So
$$\inf_{\left|y\right|>R}\varphi(y)\geq u(x,t)+\delta>u(x,t)+\delta/2>\varphi(y')\geq\varphi(y_{*})$$
and by construction $\inf_{\left|y\right|\leq R}\varphi(y)\geq\varphi(y_{*})$. These two results yield that $u(x,t)\geq\varphi(y_{*})$, from which equality is immediate.


text:
Q: host node module on local server and install them in application using npm I am working on creating a node package which has this structure:
my_module(folder)

--package.json (inside the my_module folder)
--other files/folder (inside the my_module folder)

The package.json file looks like this:
{
  "name": "my_package",
  "version": "0.0.1",
  "description": "Test Package"
}

I am packaging this in my_package.tgz format and hosting that file in my local tomcat server http://url_to_server/my_package.tgz . I can download the file using this url.
In some local application I am trying to install that package using npm install "http://url_to_server/my_package.tgz" --save-dev and it throws error saying that it is not a package. What am i missing?

A: I had problem in packaging the the files in folder .I packaged same folder using this command.
tar -zcvf source-folder-name.tar.gz source-folder-name

and I was able to download and install properly.


text:
Q: С# табы и разделение кода на дополнения/модули Допустим нужно написать софт, многозадачный.
К примеру, у него будет 2-5 табов с формами и кнопками.
Вопрос, визуально задачи разделить можно, а как их разделить програмно ?
Допустим сделать что-то ввиде модулей ? дополнений, над которыми можно было бы работать отдельно, а не в общем коде.

A:
Вопрос, визуально задачи разделить можно, а как их разделить програмно?

Если хотите разделить, т.е. не видеть код для других табов:

*

*Напишите отдельные классы для каждого таба.

*Используйте свойства и методы класса в "общем коде".

Чтобы не создавать лишние классы, можно грамотно написать методы и собрать в одном классе. Т.е. вынести повторяющиеся задачи в функции, все функции не должны изменять внешние переменные и решать только 1 задачу (только читает файл и возвращает результат, а не считает его).


text:
Q: Karate DSL variable is not resolved in array initialization In my karate feature I want to initialize an array with a variable in it.
To my understanding, that should be possible with a single line like this: * def array = [Id]
However, that sets the variable array to ["Id"]. But using set works.
See example:
  Scenario: WTF
    * def Id = 123
    * print "Id", Id
    * print "[Id]", [Id]
    * def array = [Id]
    * print "array", array
    * set array[0] = Id
    * print "array", array

Produces the output
Id 123
[Id] [123]
array ["Id"]
array [123]

How can * def array = [Id] be changed to produce the array with the variable in it?

A: Here you go:
Scenario: FTW
* def id = 123

# karate recommended
* def array = [ '#(id)' ]
* match array == [123]

# js developers like this
* def array = ([id])
* match array == [123]

And please read this for a full explanation: https://github.com/karatelabs/karate#enclosed-javascript


text:
Q: Passing structure to a function I was practicing different methods to assign values to the structure variables. But, when
I tried this I am getting some garbage value. Here is the code.
#include<iostream>
using namespace std ;

struct Distance{
    int feet ;
    int inches;
};

void get_val(Distance );
void disp(Distance);

int main(){

    Distance l, m ;                   //Objects
    get_val(l);
    get_val(m);
    disp(l);
    disp(m);
    return 0  ;
}

void get_val(Distance length){
    cout<<"\nEnter Length "
        <<"\nFeet  : ";
    cin>>length.feet;
    cout<<"\nInches : ";
    cin>>length.inches;
}
void disp(Distance length){
    cout<<"\nLength : \n"
        <<"Feet : "<<length.feet
        <<"\nInches : "<<length.inches ;
}

Why am I getting garbage value as the Output ?

A: pass them by reference.
void get_val(Distance&);

void get_val(Distance &length){}

You change value of structure created in main function in another function so you have to pass them by reference or use pointers.
Edited:
Thanks to  Benjamin Lindley .

A: The comments so far tell you what to do, but don't seem to go into the reasons why you need to do that.
In C++ (as well as C) when you pass data to a function, it makes a copy of that data which is local to that function- it's not the original data! Not to mention it takes up memory and adds a little more time to the execution time (although it won't matter until you get into larger structures).
So the solution is to instead pass the memory location of the data- a reference to it. The reference is "copied" in that it just takes the location (probably a size_t or something that could represent the position in memory) and copies that, but uses that location to "reference" the actual data. It removes a bit of the overhead in copying and allows you to modify the original data.
In C you would use a pointer instead of a reference, in C++ it's generally favorable to use a reference (because it means the thing you pass is already initialized and not going to segfault). You've probably seen the syntax and already used it, but I'm copying it here for redundancy:
void get_val(Distance&);
void disp(const Distance&);
//...

void get_val(Distance& length){
    cout<<"\nEnter Length "
        <<"\nFeet  : ";
    cin>>length.feet;
    cout<<"\nInches : ";
    cin>>length.inches;
}

void disp(const Distance& length){
    cout<<"\nLength : \n"
        <<"Feet : "<<length.feet
        <<"\nInches : "<<length.inches ;
}

You use a reference just like a regular variable (and just as a hint, variables are a type of reference themselves! You call the function the same way- get_val(l); and disp(l);.) A const reference is just a reference you can't change. Usually you'll use them for functions that simply read the value and don't do anything else.

A: You need to pass a Distance to get_val by reference. Then signature of get_val needs to be
void get_val(Distance& length);

With your implementation, there are two problems:

*

*You are modifying a local copy of Distance in get_val.

*You haven't initialized l or m.

A: Use pass by reference (with the use of const)
i.e.
void get_val(Distance &length)
void disp(const Distance &length){

A: You should pass the object of structure by reference.  Use:
get_val (Distance& l);

In your case object is being passed by value. Hence when you call the function get_val (Distance l), the value gets stored in l's member variables but when the control returns back to the main, the values you stored are not reflected because they were stored in a "copy" of object and not actual object.
There are some advantages of using reference but one that definitely stands out is that it prevents creating a new copy of object and reduces the overhead of calling the copy constructor and reduces memory footprint. Second being you can modify original object.

A: When you pass it that way you're just passing a copy of Distance. So the Distance object inside get_val is merely a copy of l and m and neither l nor m gets updated.
What you want to do instead is pass pointers to l and m:
void get_val(Distance *length) {
    cout<<"\nEnter Length "
        <<"\nFeet  : ";
    cin>>length->feet;
    cout<<"\nInches : ";
    cin>>length->inches;
}

Then call it like this:
get_val(&l);
get_val(&m);

Either that or write the function to pass by reference (see R Sahu's answer).


text:
Q: How to fix NameNotFoundException in android webview I got PackageNotFoundException com.google.android.webview, after 25/March/2019 in my app, The users mostly affected used android version 5, 6 or 7, the user mostly uses Samsung or LGE devices. The exception I saw in an analytics tool and has affected many users since then.
I read a few threads saying crash occurs in lollipop devices after web view gets updated, but in my case, I am getting the exception in devices with android version 6or 7 as well, I already tried reproducing the error but no luck with that.
Stack trace for the Error:
Caused by android.content.pm.PackageManager$NameNotFoundException
com.google.android.webview
android.app.ApplicationPackageManager.getPackageInfo (ApplicationPackageManager.java:235)
android.webkit.WebViewFactory.fetchPackageInfo (WebViewFactory.java:107)
android.webkit.WebViewFactory.getProviderClass (WebViewFactory.java:183)
android.webkit.WebViewFactory.getProvider (WebViewFactory.java:158)
android.webkit.WebView.getFactory (WebView.java:2290)
android.webkit.WebView.ensureProviderCreated (WebView.java:2285)
android.webkit.WebView.setOverScrollMode (WebView.java:2344)
android.view.View. (View.java:4065)
android.view.View. (View.java:4186)
android.view.ViewGroup. (ViewGroup.java:591)
android.widget.AbsoluteLayout. (AbsoluteLayout.java:55)
android.webkit.WebView. (WebView.java:609)
android.webkit.WebView. (WebView.java:554)
android.webkit.WebView. (WebView.java:537)
android.webkit.WebView. (WebView.java:524)
java.lang.reflect.Constructor.newInstance (Constructor.java)
android.view.LayoutInflater.createView (LayoutInflater.java:631)
com.android.internal.policy.PhoneLayoutInflater.onCreateView (PhoneLayoutInflater.java:58)
android.view.LayoutInflater.onCreateView (LayoutInflater.java:706)
android.view.LayoutInflater.createViewFromTag (LayoutInflater.java:774)
android.view.LayoutInflater.createViewFromTag (LayoutInflater.java:716)
android.view.LayoutInflater.rInflate (LayoutInflater.java:847)
android.view.LayoutInflater.rInflateChildren (LayoutInflater.java:810)
android.view.LayoutInflater.rInflate (LayoutInflater.java:855)
android.view.LayoutInflater.rInflateChildren (LayoutInflater.java:810)
android.view.LayoutInflater.rInflate (LayoutInflater.java:855)
android.view.LayoutInflater.rInflateChildren (LayoutInflater.java:810)
android.view.LayoutInflater.inflate (LayoutInflater.java:527)
android.view.LayoutInflater.inflate (LayoutInflater.java:429)
android.view.LayoutInflater.inflate (LayoutInflater.java:380)
android.support.v7.app.AppCompatDelegateImplV9.setContentView (AppCompatDelegateImplV9.java:287)
android.support.v7.app.AppCompatActivity.setContentView (AppCompatActivity.java:139)
android.app.Activity.performCreate (Activity.java:6904)
android.app.Instrumentation.callActivityOnCreate (Instrumentation.java:1136)
android.app.ActivityThread.performLaunchActivity (ActivityThread.java:3266)
android.app.ActivityThread.handleLaunchActivity (ActivityThread.java:3415)
android.app.ActivityThread.access$1100 (ActivityThread.java:229)
android.app.ActivityThread$H.handleMessage (ActivityThread.java:1821)
android.os.Handler.dispatchMessage (Handler.java:102)
android.os.Looper.loop (Looper.java:148)
android.app.ActivityThread.main (ActivityThread.java:7325)
java.lang.reflect.Method.invoke (Method.java)
com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run (ZygoteInit.java:1230)
com.android.internal.os.ZygoteInit.main (ZygoteInit.java:1120)


text:
Q: MinGW and Boost warning errors? I'm using Boost (1.47.0 self compiled) and MinGW 4.6 (for C++0x features) for my application, but I get a load of warnings (I use -Werror) in Boost's JSON parsing code.
I don't get these errors on Linux or in MSVC (MSVC Boost is self compiled from the exact same source tree). Here are the errors and the lines they point to.
boost\property_tree\detail\json_parser_write.hpp|35|error: comparison is always true due to limited range of data type [-Werror=type-limits]
        if (*b == 0x20 || *b == 0x21 || (*b >= 0x23 && *b <= 0x2E) ||
            (*b >= 0x30 && *b <= 0x5B) || (*b >= 0x5D && *b <= 0xFF))
            result += *b;

boost\property_tree\detail\json_parser_read.hpp|115|error: unused parameter 'e' [-Werror=unused-parameter]
        void operator()(It b, It e) const
        {
            c.string += *b;
        }

The errors seem sound, but is there a workaround that I'm missing?

A: Regarding the first, I am guessing 'b' is defined as 'char *'? Whether char defaults to unsigned or signed is compiler-dependant AFAIK. It is possible mingw is defaulting the char to signed, making the comparisons with 0x0FF outside the possible range.
The second is self-explanatory, the warning is doing exactly what it is supposed to be doing, you should probably just disable that warning.


text:
Q: Create sub-arrays depending on object values (Two groupings for two objects) I have an array of objects (dictionary is the term in Python but in this case I am using Javascript). What I am trying to do is to group everything in different objects. My first attempt is to create two arrays based on the Inventory values. Then for each of the two arrays, I want to create three different arrays based on the Objective values.
I think I have lost the logic as it doesn't work for the second grouping (Objective).

var inventory = [
    {ID: "K111", Objective: "One", Inventory: "Second" },
    {ID: "K112", Objective: "Two", Inventory: "Second" },
    {ID: "K113", Objective: "One", Inventory: "Second" },
    {ID: "K114", Objective: "Three", Inventory: "Second" },
    {ID: "K132", Objective: "One", Inventory: "First" }
];

var OBJECTIVE = ["One", "Two", "Three"];
var INVENTORY = ["Second", "First"];

//Create arrays per Inventory (2 possible values)
for (var i = 0; i < INVENTORY.length; i++) {

  var variable = inventory.filter(function(el) {
      return el.Inventory == INVENTORY[i];
  });

  window['arr'+i] = variable;
  document.getElementById("arr"+i).innerHTML =JSON.stringify(variable);

}

//Create arrays per Objective for each array created above
for (var i = 0; i < OBJECTIVE.length; i++) {

  j = i + 2;
  var variable = arr0.filter(function(el) {
      return el.Objective == OBJECTIVE[i];
  });

  window['arr'+j] = JSON.stringify(variable);
  document.getElementById("arr"+j).innerHTML =JSON.stringify(variable);

}

for (var i = 0; i < OBJECTIVE.length; i++) {

  var variable = arr1.filter(function(el) {
      return el.Objective == OBJECTIVE[i];
  });

  window['arr'+j] = JSON.stringify(variable);
  document.getElementById("arr"+j).innerHTML =JSON.stringify(variable);

}

A: You could instead return one object using reduce method where you group first by Inventory and then by Objective. To return array of arrays as a result you can use Object.values with map.

var data = [{ID: "K111", Objective: "One", Inventory: "Second" },{ID: "K112", Objective: "Two", Inventory: "Second" },{ID: "K113", Objective: "One", Inventory: "Second" },{ID: "K114", Objective: "Three", Inventory: "Second" },    {ID: "K132", Objective: "One", Inventory: "First" }];

var res = data.reduce((r, e) => {
  let {Objective, Inventory} = e;
  r[Inventory] = r[Inventory] || {}
  r[Inventory][Objective] = r[Inventory][Objective] || {}
  Object.assign(r[Inventory][Objective], e);
  return r;
}, {})

var array = Object.values(res).map(Object.values)

console.log(array)
console.log(res)


text:
Q: Sum using variables then evaluated with values gives different result than sum with values I'm trying to do a sum symbolically. However, Mathematica is giving me a different result if I do the sum with numbers or symbols. What's causing this error?
$Assumptions = m \[Element] Integers && n \[Element] Integers && m >= 0 && n >= 0;

f[i_, j_] := If[OddQ[Min[i, j]], (Min[i, j] + (-1)^Max[i, j])/2, Ceiling[Min[i, j]/2]];

Table[f[i, j], {i, 0, 1}, {j, 0, 4}] // TableForm

F = Sum[f[i, j], {i, 0, m}, {j, 0, n}];
F /. {m -> 1, n -> 4}
Sum[f[i, j], {i, 0, 1}, {j, 0, 4}]

Result
0 0 0 0 0
0 0 1 0 1

4

2

A: I'm not entirely sure why MMA is ignoring the $Assumptions, but here is the correct expression:
Table[
      Sum[f[i, j], {i, 0, n}, {j, 0, m}] ==
      1/48 (-3 (-1 + (-1)^m) (-1 + (-1)^n) + 12 m n +
      2 Min[m, n] (2 + 3 (-1)^m + 3 (-1)^n - 2 Min[m, n]^2 + 6 m n))
, {n, 0, 12}, {m, 0, 12}] // Flatten // Tally
(* {{True, 169}} *)


text:
Q: Reading Json data containing special symbols like curly braces, square brackets etc I have json data saved as a string in a database. The structure of JSON data is fine with the problem that it contains regex expressions and even urls which contains curry braces {} or square brackets [] etc. I can replace  some of special symbols with the encodings available e.g hex or decimal encodings. and do string manipulations to take care of these. I was just wondering is there another way for handling this situation. I am getting following exception for the strings containing this type of Json data.
  org.json.JSONException: Expected a ',' or '}' at character 22891 of {"wires":[{"id"....so on

Please let me know if I need to elaborate more.

A: Here's the first thing coming to my mind:
When putting the thing in the database try php addslashes/stripslashes (assuming you are using php to contact the database).


text:
Q: How do you prove that co-variance is a linear operator? I mean how do you prove linearity property of co-variances with a proper domain and range?

A: In fact, it is a bilinear operator, meaning that its domain is the product of two vector spaces and it is linear in each entry:
Let $L^2(\Omega;\mathbb{R})$ (just $L^2$ for short) be the vector space of real valued random variables s.t. $E[\vert X \vert^2] < \infty$. Then we have $\text{Cov}: L^2 \times L^2 \rightarrow \mathbb{R}$ via $\text{Cov}(X,Y) = E[(X - E[X])(Y - E[Y]))$ is bilinear.
I will prove the linearity for the first entry - symmetry of the operator then gives linearity in the second.
Let $X_1, X_2 \in L^1$ and $\lambda \in \mathbb{R}$, then
$$ \begin{align} \text{Cov}(\lambda X_1 + X_2,Y) &= E[(\lambda X_1 + X_2 - E[\lambda X_1 + X_2])(Y - E[Y])) \\
& = E[\lambda (X_1 - E[X_1])(Y - E[Y])) + (X_2 - E[X_2])(Y - E[Y])) = E[\lambda (X_1 - E[X_1])(Y - E[Y]))] + E[(X_2 - E[X_2])(Y - E[Y])) \\
&=\lambda \text{Cov}(X_1,Y) + \text{Cov}(X_2,Y)
 \end{align} $$
In essence, it comes down to the fact that the expected value is linear.


text:
Q: I cannot play 70% of the activities on Destiny This hasn't happened to me before and I'm worried. I have purchased the expansion pass, and I have PlayStation Plus. This has happened to my ex-friend five months ago, but I cannot remember what he did to fix it. I can go into patrol, strikes and the daily missions; But I cannot go into the weekly heroic, nightfall, daily crucible or the raids.

A: This issue could result from several reasons, some that would already not apply to the specific case listed by OP.
The Taken King requirement increases
With the release of The Taken King, a lot of activities had their minimum requirements increased. Crucible now requires level 10, while dailies and weeklies have higher respective light requirements.
"Online Play" permission issues (Xbox and PS4 only1)
All listed 'problem activities' appear to require PlayStation Plus or Xbox Live. As a result you will not be able to access them, unless you have a valid subscription, in most cases. OP reports having PlayStation Plus, but I would recommend confirming your registration is live. You can do this by attempting to manually join a strike that attempts to place you into matchmaking, or be deliberately attempting to access the crucible.
It is also entirely likely that there is problems registering your permissions to access the service, even when you have an active subscription. Try turning your machine off and back on again. I have seen this problem arise commonly, but it appears to fix itself.
Bungie Intervention
Given that all problem dailies are associated with player interaction, it is a possibility that Bungie have banned your account from accessing the service. This is not something they will do without warning, so you will likely be made aware that a 'ban' is in place. Bungie will generally do this if you act in an unfair manner. That includes using exploits or mods, taking advantage of another player's use of exploits or mods, and impersonating Bungie. You can find out more on game banning at Bungie's FAQ.
1Should not apply to PlayStation 3, which does not require PlayStation Plus for online to play

A: What EXP and Light levels are you?
I recently finished the "main story" of The Taken King expansion myself and a lot of stuff is locked until you hit level 40. A bunch of stuff is not even visible.
As soon as you reach EXP 40 a lot more of the content shows up. Even then you need to be a certain Light Level to actually play some of them, anything Heroic for example (light level 240+ from memory).

A: The DLC wont work unless it is from the same region as the game.
ie. Disk for US and DLC-s from UK PSN store won't work together. The solution is to go and buy the correct region base game, either used on disk, or from PSN and all things start working. Or the correct region DLC-s. AFAIK Sony nor Bungie will not give you your money back for the wrong region content.
Also the Season pass does not automatically download individual expansions from the perspective of the PSN Store. So if you have the season pass you need to go to PSN and "buy" the specific DLC. It will be priced as zero since you have the season pass. if you are missing one of the pre TTK expansions, then this will also activate the possibility to purchase the TTK standalone addon.
And then there are the PSN realated topics - what comes to mind is that you go and check that your PS4 console is registered as your primary active console and then redownload the DLC content from PSN.


text:
Q: UnrecognizedFlagError: Unknown command line flag 'f' When I am trying to run the following code in jupyter notebook(for graph clustering)
This is my main run file from which I am trying to import the other code snippets and trying to run the entire code.
import tensorflow.compat.v1 as tf

tf.random.set_seed(1234)
flags = tf.compat.v1.flags
FLAGS = flags.FLAGS

for name in list(flags.FLAGS):
    delattr(flags.FLAGS,name)
flags.DEFINE_float('learning_rate', 0.001, 'initial learning rate.')

# left to default values in main experiments
flags.DEFINE_integer('epochs', 2000, 'number of epochs to train.')
#logging, saving, validation settings etc.
flags.DEFINE_integer('print_every', 20, "How often to print training info.")
flags.DEFINE_string('dataset', '20news', 'dataset')
flags.DEFINE_integer('emb', 100, "How often to print training info.")
flags.DEFINE_float('beta',2.0, 'weight for beta loss')
flags.DEFINE_boolean('shareW', False, 'share the w')

adjs,xs, ys, cnets,Gs= load_data(FLAGS.dataset,norm=True)
n_networks = len(xs)
n_clusters = [len(np.unique(y)) for y in ys]

The error message that I am getting is:
UnrecognizedFlagError                     Traceback (most recent call last)
Input In [14], in <cell line: 35>()
     30 flags.DEFINE_string('output_dir', './', 'output_dir')
     31 flags.DEFINE_integer('hdim', 128, 'hidden represenation size')
---> 35 adjs,xs, ys, cnets,Gs= load_data(FLAGS.dataset,norm=True)
     36 n_networks = len(xs)
     37 n_clusters = [len(np.unique(y)) for y in ys]

File ~/anaconda3/lib/python3.9/site-packages/tensorflow/python/platform/flags.py:81, in _FlagValuesWrapper.__getattr__(self, name)
     78 # To maintain backwards compatibility, implicitly parse flags when reading
     79 # a flag.
     80 if not wrapped.is_parsed():
---> 81   wrapped(_sys.argv)
     82 return wrapped.__getattr__(name)

File ~/anaconda3/lib/python3.9/site-packages/absl/flags/_flagvalues.py:649, in FlagValues.__call__(self, argv, known_only)
    647 for name, value in unknown_flags:
    648   suggestions = _helpers.get_flag_suggestions(name, list(self))
--> 649   raise _exceptions.UnrecognizedFlagError(
    650       name, value, suggestions=suggestions)
    652 self.mark_as_parsed()
    653 self.validate_all_flags()

UnrecognizedFlagError: Unknown command line flag 'f'

Please, can anyone help me with this. Thanking you in advance.


text:
Q: How to store UDF return value for incoming events using Stream Analytics? I need to translate the C# code below into something that can be used by Azure Stream Analytics.
I've got a C# application that is similar to the following:
var inputEvents = new List<Event>();
foreach (var file in files){
    (List<Event> events, DateTime maxDate) = ProcessEvents(file, inputEvents);
    inputEvents = events.Where(e => e.Duration == null).ToList();
}

Where ProcessEvents() passes inputEvents to other helper methods
I need to implement this whole code using Stream Analytics. The var file part is implemented by gathering a bunch of events using Collect(). Each batch is sent to a UDF which acts as ProcessEvents(). However, ProcessEvents() returns other events that are needed for the next iteration. Since UDF is stateless, the next batch won't be able to use the returned events from the previous batch.
How do I rewrite the C# code above in Stream Analytics?
I've tried the following:

*

*Use UDA to store the returned events. Failed because for some reason it can't store a JSON array and constantly modify it.

*Use Reference Data input to store the returned events. Failed because they can only be used in Stream Analytics using a JOIN and not within a UDF.

Stream Analytics T-SQL Query:
WITH eventsCollection AS (SELECT COLLECT() AS allEvents
FROM EventHubStreamMessage
GROUP BY SessionWindow(minute,2,4)),

step1 AS (
    SELECT UDF.SampleProcessEvents(allEvents) as Source
    FROM eventsCollection
)

SELECT *
INTO [StorageTable]
FROM step1

Stream Analytics UDF Code (short version):
function main(allEvents){
    allEvents = JSON.stringify(allEvents);
    var inputEvents = new Array ();

    return processEvents(JSON.parse(allEvents), inputEvents)
}

function processEvents(allEvents, inputEvents){
    for (i=0l i<allEvents.length; i++){
        if (allEvents[i].Event =="ON"){
            powerOn(inputEvents);
        }
    }
}

function powerOn(inputEvents){
    return true;
}


text:
Q: get geotag info for photos using PHImageManager I'm trying to list geo tag info (longitude and latitude) for all photos, obtained using
PHImageManager.defaultManager().requestImageForAsset(fetchResult.objectAtIndex(1) as! PHAsset, targetSize: CGSize(width: 100.0, height: 100.0), contentMode: PHImageContentMode.AspectFill, options: options) { (image, info)

however, info doesn't seem to contain this information,
is there any way to get this information using Photos framework?
thank you,
Anton

A: PHAsset itself hold the CLLocation (i.e geo location) for the image.
There is no need to request image data for it.
All you need to do is
fetchResult.objectAtIndex(1).location

Here is the link to the documentation page for PHAsset https://developer.apple.com/reference/photos/phasset


text:
Q: Dynamic test data for test.each Jest Is it possible to assign values at runtime for below Jest test.each example:
describe('jb-tests', () => {
    jest.setTimeout(700000);
    let table: Array<number[][]> = [[]];
    beforeAll(() => {

        //Below lines are just hardcoded values
        table = [];
        let test = [[1,2,3],[4,5,6],[7,8,9]]
        table.push(test);

    });

    test.each(table)('.add(%i, %i)', (a, b, expected) => {
        console.log("inside");
    });
});

This test case is stuck and not showing any output. If I remove the jest.setTimeout then it fails with message "Exceeded timeout of 5000 ms for a test."

A: Building on the comment from @jonrsharpe, you can however specify values in the test.each() call.
describe('jb-tests', () => {
    jest.setTimeout(700000);

    test.each([
        [1,2,3],
        [4,5,6],
        [7,8,9],
    ])('.add(%i, %i)', (a, b, expected) => {
        expect(a + b).toBe(Expected);
    });
});

However, if you really need data from an external source, and want to process it, you can load it in the test code, or a beforeAll().  Note that the beforeAll() is evaluated at the very start, so what is loaded there is done at the start of processing the file, not as each test is run.
import * as NodeJSFS from 'fs/promises';

describe('jb-tests', () => {
    jest.setTimeout(700000);

    let table: Array<number[][]> = [[]];
    beforeAll(async () => {
        const FileContent$: Buffer = await NodeJSFSPromises.readFile('testdata.txt');

        // Loop through FileContent$ (map, etc.) and load your table (table.push)
        ...
    });

    describe('adding addition describe for this section', () => {
        for (const data of table) {
            ... // Parse data (one element of table)
            it(`should add ${a} + ${b} to be ${Expected}', () => {
                expect(a + b).toBe(Expected);
            });
        }
    });

A: Just found an alternate solution: Populate the test data dynamically and then use describe block to execute test cases using test.each.
let test_data: Array<number[]> = [];

for(let i=0;i<3;i++){
    test_data.push([i+0,i+1,i+2]);
}

describe('jb-tests', () => {
    test.each(test_data)('.add(%i, %i, %i)', (a, b, c) => {
        expect(a + b + c).toBeGreaterThan(0);
    });
});


text:
Q: PHP - simple download script I'm making a simple download script, where my users can download their own images etc.
But I'm having some weird problem.
When I've downloaded the file, it's having the contents from my index.php file no matter what filetype I've downloaded.. My code is like so:
$fullPath = $r['snptFilepath'] . $r['snptFilename'];

if (file_exists($fullPath)) {

    #echo $fullPath;

    // setting headers
    header('Content-Description: File Transfer');
    header('Cache-Control: public'); # needed for IE
    header('Content-Type: '.$r['snptFiletype'].'');
    header('Content-Disposition: attachment; filename='. $filename . '.' . $r['snptExtension']);
    header('Content-Length: '.$r['snptSize'].'');
    readfile($fullPath)or die('error!');
} else {
    die('File does not exist');
}

$r is the result from my database, where I've stored size, type, path etc. when the file is uploaded.
UPDATE
When I'm uploading and downloading *.pdf files it's working with success. But when I'm trying to download *.zip and text/rtf, text/plain it's acting weird.
By weird I mean: It downloads the full index.php file, with the downloaded file contents inside of it.
ANSWER
I copied this from http://php.net/manual/en/function.readfile.php and it's working now. It seems that : ob_clean(); did the trick! Thanks for the help everyone.
#setting headers
    header('Content-Description: File Transfer');
    header('Content-Type: '.$type);
    header('Content-Disposition: attachment; filename='.basename($file));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . filesize($file));
    ob_clean();
    flush();
    readfile($file);
    exit;

A: I copied this from http://php.net/manual/en/function.readfile.php and it works now. ob_clean(); did the trick..
    #setting headers
    header('Content-Description: File Transfer');
    header('Cache-Control: public');
    header('Content-Type: '.$type);
    header("Content-Transfer-Encoding: binary");
    header('Content-Disposition: attachment; filename='. basename($file));
    header('Content-Length: '.filesize($file));
    ob_clean(); #THIS!
    flush();
    readfile($file);

A: Try this function , or implement these headers to your code
    function force_download($filename) {
    $filedata = @file_get_contents($filename);

    // SUCCESS
    if ($filedata)
    {
        // GET A NAME FOR THE FILE
        $basename = basename($filename);

        // THESE HEADERS ARE USED ON ALL BROWSERS
        header("Content-Type: application-x/force-download");
        header("Content-Disposition: attachment; filename=$basename");
        header("Content-length: " . (string)(strlen($filedata)));
        header("Expires: ".gmdate("D, d M Y H:i:s", mktime(date("H")+2, date("i"), date("s"), date("m"), date("d"), date("Y")))." GMT");
        header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");

        // THIS HEADER MUST BE OMITTED FOR IE 6+
        if (FALSE === strpos($_SERVER["HTTP_USER_AGENT"], 'MSIE '))
        {
            header("Cache-Control: no-cache, must-revalidate");
        }

        // THIS IS THE LAST HEADER
        header("Pragma: no-cache");

        // FLUSH THE HEADERS TO THE BROWSER
        flush();

        // CAPTURE THE FILE IN THE OUTPUT BUFFERS - WILL BE FLUSHED AT SCRIPT END
        ob_start();
        echo $filedata;
    }

    // FAILURE
    else
    {
        die("ERROR: UNABLE TO OPEN $filename");
    }
}


text:
Q: C++ templates problem I am new to templates in c++.
i was trying some small programs.
    CPP [80]> cat 000001.cpp 000001.hpp
#include <iostream>
#include <string>
#include "000001.hpp"

int main()
{
    int i = 42;
    std::cout << "max(7,i):   " << ::max(7,i) << std::endl;

    double f1 = 3.4;
    double f2 = -6.7;
    std::cout << "max(f1,f2): " << ::max(f1,f2) << std::endl;

    std::string s1 = "mathematics";
    std::string s2 = "math";
    std::cout << "max(s1,s2): " << ::max(s1,s2) << std::endl;
}

template <typename T>
inline T const& max (T const& a, T const& b)
{
        return  a < b ? b : a;
}

when i compile this program:
i get an error below:
    CPP [78]> /opt/aCC/bin/aCC -AA 000001.cpp
Error (future) 229: "/opt/aCC/include_std/string.cc", line 164 # "Ambiguous overloaded function call; a
    function match was not found that was strictly best for ALL arguments. Two functions that matched
    best for some arguments (but not all) were "const unsigned long &max<unsigned long>(const unsigned
    long &,const unsigned long &)" ["000001.hpp", line 2] and "const unsigned long &std::max<unsigned
    long>(const unsigned long &,const unsigned long &)" ["/opt/aCC/include_std/algorithm", line 1762]."
    Choosing "const unsigned long &max<unsigned long>(const unsigned long &,const unsigned long &)"
    ["000001.hpp", line 2] for resolving ambiguity.
            _C_data = _C_getRep (max (_RW::__rw_new_capacity (0, this),
                                 ^^^
Warning:        1 future errors were detected and ignored. Add a '+p' option to detect and fix them before they become fatal errors in a future release. Behavior of this ill-formed program is not guaranteed to match that of a well-formed program

Could nybody please tell me what exactly the error is?

A: You are probably including <iostream.h> instead of <iostream> somewhere. The former hasn't existed for some time now, but for compatibility reasons, you compiler still accepts the include and replaces it with
#include <iostream>
using namespace std;

This causes std::max to be brought to the global namespace, thus resulting in an ambiguity. Replace <iostream.h> with <iostream> or rename your max function and the problem should disappear.
Edit: You've apparently fixed the include, but I bet you still have using namespace std; somewhere. You need to get rid of that. In fact you should never use using namespace in the global scope.
Edit: You might also have using std::max somewhere. You need to get rid of it too.

A: The code you've posted compiles just fine, there must be something else that is wrong inside "000001.hpp". Can you post the contents of that file too?
Edit: If you do as avakar says but the problem persists, that must be due to some problem with your compiler. There are two obvious workarounds I can think of: rename your max function to something else, or put it in a namespace:
namespace Foo
{
    template <typename T>
    inline T const& max (T const& a, T const& b)
    {
        return  a < b ? b : a;
    }
}

int main()
{
    int i = 42;
    std::cout << "max(7,i):   " << Foo::max(7,i) << std::endl;

    double f1 = 3.4;
    double f2 = -6.7;
    std::cout << "max(f1,f2): " << Foo::max(f1,f2) << std::endl;

    std::string s1 = "mathematics";
    std::string s2 = "math";
    std::cout << "max(s1,s2): " << Foo::max(s1,s2) << std::endl;
}

A: I don't know which compiler you are using but the second error tells you that the two following functions are clashing :
::max
std::max

It seems really weird, you may have a using namespace std; somewhere or worse, that one of your include use iostream.h as noted in the first error. Could you give more information about your compiler/toolchain and the content of your .hpp file?

A: It says that two definitions for
max<unsigned long>

were found. One definition is in 000001.hpp and the other is in /opt/aCC/include_std/algorithm. The compiler chose the one in 000001.hpp for now, so no error is present now. But it says that these two definitions may cause errors in the future.

A: I don't know if this causes the problem, but anyhow; you shouldnt use the name max for your global (or local) function as it is a part of STL.


text:
Q: Unresolved class 'FileProvider' I am trying to take a picture on an android device and following this tutorial.
The below code gives me an error on android.support.v4.content.FileProvider. Android studio says Unresolved class 'FileProvider'.
I have the following AndroidManifest.xml file:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.example.camera">

<uses-permission android:name="android.permission.CAMERA" />

<application
    android:label="@string/app_name">

    <activity android:name=".LandingPageActivity" />

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.provider"
        android:exported="false"
        android:grantUriPermissions="true">
        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/provider_paths" />
    </provider>

</application>

</manifest>

I have added implementation 'com.android.support:support-v4:28.0.0' to my build.gradle file.
apply plugin: 'com.android.application'

android {
    compileSdkVersion 28
    defaultConfig {
        applicationId "com.example.camera"
        minSdkVersion 15
        targetSdkVersion 28
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        vectorDrawables.useSupportLibrary = true
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'androidx.appcompat:appcompat:1.1.0-alpha02'
    ...others
    implementation 'com.android.support:support-v4:28.0.0'
}

apply plugin: 'com.google.gms.google-services'

I have tried this solution with no luck.

A: You're using AndroidX dependencies (such as your androidx.appcompat dependency), so you need to use the AndroidX FileProvider, which has a package name of androidx.core.content.FileProvider:
<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.provider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/provider_paths" />
</provider>

A: <provider
            android:name="androidx.core.content.FileProvider"
            android:authorities="${applicationId}.fileprovider"
            android:exported="false"
            android:grantUriPermissions="true">

      <meta-data
                android:name="android.support.FILE_PROVIDER_PATHS"
                android:resource="@xml/provider_paths" />

</provider>