text:
Q: How to Call FrameLayout slider in Different Activities in Android I have 3 activity say first_activity,second_activity,third_activity.I have used FrameLayout to open a slider .!
Now what I want to open the slider on click of button that is available on all three activities.
So now like in the Test 1 there is a button on the left side in the same way i have on all three activities so on click of that i want to open the slider.
This my slider code
public class MainActivity extends Activity {

    // Within which the entire activity is enclosed
    private DrawerLayout mDrawerLayout;

    // ListView represents Navigation Drawer
    private ListView mDrawerList;

    // ActionBarDrawerToggle indicates the presence of Navigation Drawer in the
    // action bar
    private ActionBarDrawerToggle mDrawerToggle;

    // Title of the action bar
    private String mTitle = "";

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTitle = "Test App";
        getActionBar().setTitle(mTitle);

        // Getting reference to the DrawerLayout
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        mDrawerList = (ListView) findViewById(R.id.drawer_list);

        // Getting reference to the ActionBarDrawerToggle
        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
                R.drawable.ic_drawer, R.string.drawer_open,
                R.string.drawer_close) {

            /** Called when drawer is closed */
            public void onDrawerClosed(View view) {
                getActionBar().setTitle(mTitle);
                invalidateOptionsMenu();
            }

            /** Called when a drawer is opened */
            public void onDrawerOpened(View drawerView) {
                // getActionBar().setTitle("Approval Status");
                invalidateOptionsMenu();
            }
        };

        // Setting DrawerToggle on DrawerLayout
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        // Creating an ArrayAdapter to add items to the listview mDrawerList
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
                getBaseContext(), R.layout.drawer_list_item, getResources()
                        .getStringArray(R.array.menus));

        // Setting the adapter on mDrawerList
        mDrawerList.setAdapter(adapter);

        // Enabling Home button
        getActionBar().setHomeButtonEnabled(true);

        // Enabling Up navigation
        getActionBar().setDisplayHomeAsUpEnabled(true);

        // Setting item click listener for the listview mDrawerList
        mDrawerList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // Getting an array of rivers
                String[] menuItems = getResources().getStringArray(
                        R.array.menus);

                // Currently selected river
                mTitle = menuItems[position];

                // Creating a fragment object
                // WebViewFragment rFragment = new WebViewFragment();
                //
                // // Passing selected item information to fragment
                // Bundle data = new Bundle();
                // data.putInt("position", position);
                // data.putString("url", getUrl(position));
                // rFragment.setArguments(data);
                //
                //
                // // Getting reference to the FragmentManager
                // FragmentManager fragmentManager = getFragmentManager();
                //
                // // Creating a fragment transaction
                // FragmentTransaction ft = fragmentManager.beginTransaction();
                //
                // // Adding a fragment to the fragment transaction
                // ft.replace(R.id.content_frame, rFragment);
                //
                // // Committing the transaction
                // ft.commit();

                // Closing the drawer
                mDrawerLayout.closeDrawer(mDrawerList);

            }
        });
    }

    protected String getUrl(int position) {
        switch (position) {
        case 0:
            return "";
        case 1:
            return "";
        case 2:
            return "";
        case 3:
            return "";
        case 4:
            return "";
        case 5:
            return "";
        case 6:
            return "";
        default:
            return "";
        }
    }

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

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /** Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the drawer is open, hide action items related to the content view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);

        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

A: You can't open a drawer in a different activity unless you have a drawer for that activity.
I would suggest you to use fragments.
Further before deciding on your design i suggest you take a look at this link first
http://developer.android.com/design/patterns/navigation.html
In oncreate
if (savedInstanceState == null){
            getUrl(0);
        }

In onItemClick call getUrl(position)
Then in getUrl
  protected String getUrl(int position) {

    FragmentTransaction fragTran = getFragmentManager()
                                 .beginTransaction();

    switch (position) {
    case 0:
            // make one a Fragment
            fragTran.replace(R.id.content_frame, fragment1);
        break;
    case 1:
           // second fragment
           fragTran.replace(R.id.content_frame, fragment2);

        break
    case 2:
          // third fragment
          fragTran.replace(R.id.content_frame, fragment3);
        break;
    }
    // Commit the transaction and close the drawer
    fragTran.commit();
    mDrawerList.setItemChecked(position, true);
    mDrawerLayout.closeDrawer(drawerList);

 }

Example:
public class Fragment1 extends Fragment {
    String[] titles={"A","B","C"};
    @Override
    public View onCreateView(
            LayoutInflater inflater,
            ViewGroup container,
            Bundle savedInstanceState){
        View rootView = inflater.inflate(R.layout.fragment1, container, false);
        return rootView;
    }
}

MainActivity.java
public class MainActivity extends Activity {

    // Fields -----------------------------------------------------------------
    private DrawerLayout drawerLayout;
    private ListView drawerList;
    private ActionBarDrawerToggle drawerToggle;
    private MenuListAdapter menuAdapter;
    private int[] icons;
    private Fragment fragment1;
    private Fragment fragment2;
    private Fragment fragment3;
    private CharSequence drawerTitle;
    private CharSequence title;
    private final String[] titles = new String[]{
            "Title Fragment #1",
            "Title Fragment #2",
            "Title Fragment #3"
    };
    private final String[] subtitles = new String[]{
            "Subtitle Fragment #1",
            "Subtitle Fragment #2",
            "Subtitle Fragment #3"
    };

    // Lifecycle Callbacks ----------------------------------------------------
    @Override
    protected void onCreate(Bundle savedInstanceState) {

        // Base implemenation
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Instantiate the fragments
        fragment1 = new Fragment1();
        fragment2 = new Fragment2();
        fragment3 = new Fragment3();

        // Get the title from this activity
        title = drawerTitle = getTitle();

        // Get the icons from the drawables folder
        icons = new int[]{
                R.drawable.action_about,
                R.drawable.action_settings,
                R.drawable.collections_cloud
        };

        // Get the drawer layout from the XML file and the ListView inside it
        drawerLayout = (DrawerLayout)findViewById(R.id.drawer_layout);
        drawerList = (ListView)findViewById(R.id.listview_drawer);

        // Set a custom shadow over that overlays the main content
        // when the drawer opens
        drawerLayout.setDrawerShadow(
                R.drawable.drawer_shadow, GravityCompat.START);

        // Pass the string arrays to the MenuListAdapter, set the drawer
        // list adapter to it and set up its click listener
        menuAdapter = new MenuListAdapter(
                MainActivity.this, titles, subtitles, icons);
        drawerList.setAdapter(menuAdapter);
        drawerList.setOnItemClickListener(new DrawerItemClickListener());

        // Enable the action bar to have up navigation
        getActionBar().setHomeButtonEnabled(true);
        //getActionBar().setDisplayHomeAsUpEnabled(true);

        // Allow the the action bar to toggle the drawer
        drawerToggle = new ActionBarDrawerToggle(
                this,
                drawerLayout,
                R.drawable.ic_drawer,
                R.string.drawer_open,
                R.string.drawer_close){

            public void onDrawerClosed(View view){
                super.onDrawerClosed(view);
            }
            public void onDrawerOpened(View view){
                getSupportActionBar().setTitle(drawerTitle);
                super.onDrawerOpened(view);
            }
        };
        drawerLayout.setDrawerListener(drawerToggle);

        // If this is the first time opening this activity,
        // start with loading fragment #1
        if (savedInstanceState == null){
            selectItem(0);
        }

    }

    // Methods ----------------------------------------------------------------
    @Override
    public boolean onOptionsItemSelected(MenuItem item){

        // If the user has pressed the action bar icon
        if (item.getItemId() == android.R.id.home){

            // If the drawer is open, close it; vice versa
            if (drawerLayout.isDrawerOpen(drawerList)){
                drawerLayout.closeDrawer(drawerList);
            } else {
                drawerLayout.openDrawer(drawerList);
            }
        }

        // Finish by letting the super class do the rest
        return super.onOptionsItemSelected(item);

    }
    @Override
    protected void onPostCreate(Bundle savedInstanceState){

        // Call the super implementation and synchronize the drawer
        super.onPostCreate(savedInstanceState);
        drawerToggle.syncState();

    }
    @Override
    public void onConfigurationChanged(Configuration newConfig){

        // Call the super implemenation on this activity
        // and the drawer toggle object
        super.onConfigurationChanged(newConfig);
        drawerToggle.onConfigurationChanged(newConfig);

    }
    private void selectItem(int position){

        // Create a new fragment transaction and start it
        FragmentTransaction fragTran = getFragmentManager()
                                       .beginTransaction();

        // Locate the position selected replace the content view
        // with the fragment of the number selected
        switch (position){
            case 0:{
                fragTran.replace(R.id.content_frame, fragment1);
                break;
            }
            case 1:{
                fragTran.replace(R.id.content_frame, fragment2);
                break;
            }
            case 2:{
                fragTran.replace(R.id.content_frame, fragment3);
                break;
            }
        }

        // Commit the transaction and close the drawer
        fragTran.commit();
        drawerList.setItemChecked(position, true);
        drawerLayout.closeDrawer(drawerList);

    }
    public void setTitle(CharSequence title){

        // Save the passed in title and set the action bar title
        this.title = title;
        getActionBar().setTitle(title);

    }

    // Classes ----------------------------------------------------------------
    private class DrawerItemClickListener
    implements ListView.OnItemClickListener{

        @Override
        public void onItemClick(
                AdapterView<?> parent,
                View view,
                int position,
                long id) {

            // When clicked, select open the appropriate fragment
            selectItem(position);

        }

    }

}

Fragment2.java
public class Fragment2 extends Fragment {
    @Override
    public View onCreateView(
            LayoutInflater inflater,
            ViewGroup container,
            Bundle savedInstanceState){
        View rootView = inflater.inflate(R.layout.fragment2, container, false);
        return rootView;
    }
}

Fragment3.java
public class Fragment3 extends Fragment {
    @Override
    public View onCreateView(
            LayoutInflater inflater,
            ViewGroup container,
            Bundle savedInstanceState){
        View rootView = inflater.inflate(R.layout.fragment3, container, false);
        return rootView;
    }
}

activity_main.xml
<android.support.v4.widget.DrawerLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>
    <ListView
        android:id="@+id/listview_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#111"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"/>

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

drawer_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/darker_gray"
    android:orientation="horizontal"
    style="?attr/dropdownListPreferredItemHeight" >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:adjustViewBounds="true"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:gravity="center_vertical|left"
        android:orientation="vertical">

        <TextView
            android:id="@+id/title"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:singleLine="true"
            style="?attr/spinnerDropDownItemStyle"/>
        <TextView
            android:id="@+id/subtitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:singleLine="true"
            style="?attr/spinnerDropDownItemStyle"/>

    </LinearLayout>

</LinearLayout>

Have framen1.xml,framgent2.xml and fragment3.xml and customize the way you want.


text:
Q: Eigenvectors and Invariant Sets Consider a system $\dot x=Ax$
Suppose $A\nu = \lambda\nu,\, \nu\ne0,\,\lambda\in \Bbb R$
Then how do I show that the line $\{ t\nu\,|\,t\in\Bbb R\}$ is invariant?

A: Let $x = t \nu$. Then, $Ax = (A)(t\nu) = t(A)(\nu) = t\lambda \nu \in \{t \nu \mid t \in \Bbb R\}$.

A: Hint: $x(t) = C e^{\lambda t} \nu$ satisfies the ODE.

A: Let $x(0) = tv,\,v$ is an eigenvector of the system $\dot x = Ax, \, t\in\Bbb R$
Therefore, $tv$ is also and eigenvector of $A$
$x(t)=e^{\lambda t}tv$ (Solution of $\dot x = Ax$ with $t_0=0,\, x(t_0) = tv$)
$x(t)=(te^{\lambda t})v$
$x(t)=Tv,\,T=te^{\lambda t},\,T\in\Bbb R$
So, for all $t>t_0,\,x(t)$ lies in the set.

redpajama_set_name: RedPajamaStackExchange


text:
Q: CSS3 transorm rectangle to trapezoid I have  a 100x5 div:

and I need to tranform it into a 30px high symmetric trapezoid with 45° angles (see below) using either matrix3d() or rotateX() and perspective. The angles should be exactly 45°

A: This seems to work in Chrome -
-webkit-transform: perspective(24px) rotateX(39deg) scale(0.6, 6.4);
transform: perspective(24px) rotateX(39deg) scale(0.6, 6.4);

My starting point was this post, though.


text:
Q: Using clip-path property affects a card flip animation in Angular I'm trying to use the clip path property to make an effect to the container of a card in Safari. This card has a flip animation to show information in both sides of it. However when I use this property the information is not shown, but the html elements are there. Have you faced something similar?
Expected:

Reality:


text:
Q: Using clipboard web api in a 'non-secure' setting? I have implemented a small project for myself that I am running on my own webserver on aws. It is something that I made in a couple hours that will be non public facing.
I had originally intended to use the clipboard api function as detailed here (https://developer.mozilla.org/en-US/docs/Web/API/Clipboard). This worked successfully while running local but when I use it on my sever it does not work. This seems to be related to the fact that

This feature is available only in secure contexts (HTTPS), in some or all supporting browsers.

Is there something I can enable in my browser to make it 'secure' and work again? I don't really want to go through the process of adding https to a side project.


text:
Q: (Convex) optimization of a sum of two variables quadratic fractional (rational) function subject to circle constraint I want to solve the below optimization problem.
\begin{align}
\min_{x, y} & \frac{a_1}{x^2} + \frac{a_2}{xy} \\
\mbox{s.t. } &x^2 + y^2 \leq \epsilon \\
&x \geq 0 \\
&y \geq 0
\end{align}
where $a_1$ and $a_2$ are positive constants.
Simple KKT condition approach deduces a quartic equation.
Is there any nice approach to resolve this problem?


text:
Q: Como ler linhas txt e inserir no Database com PHP Preciso pegar o valor de cada linha e cada coluna para inserir no database, porém existem resultados que o campo Observações estão em duas linhas e na verdade é a continuação da linha anterior. Não estou conseguindo colocá-lo na continuação da linha anterior.
Link do TXT
O resultado que eu preciso é esse:

       IDENT ANV
       TIPO
       ADEP
       EOBT
       VEL
       FL
       ROTA
       DEST
       EET
       OBS

       AZU2400
       E190
       SBGR
       11:25
       N396
       290
       DCT DORLU UZ37 VUREP DCT
       SBRJ
       00:40
       EQPT/SDFGHIRWY PBN/A1B1D1O1S2

A: Sua fonte de dados está muito irregular.
Primeiramente ela não está usando delimitadores de quebra de linha (\n \r), o que impossibilita a leitura padronizada, o texto está todo identado por espaços, e como o campo observações aparece as vezes de forma aleatória com 10 ou 6 dígitos, fica muito difícil fazer a extração dos dados.
O que eu recomendo é você primeiro padronizar a fonte de dados e depois fazer o trabalho necessário.
No caso a expressão regular mais próxima que cheguei foi :
/\d{6}.+(\w{3,4}/\w{8,10}){1,4}/g
Mas reitero que sem quebra de linhas e sem padronização, a expressão regular não irá servir.
Para testar utilize o http://regexr.com/


text:
Q: Given $x \in \Bbb{N}$ find $a,b \in \Bbb{N}$ such that $a^2 - b^2 = x$ Do $a$ and $b$ always exist? If not, for what conditions do they exist?

A: Note that $a^2-b^2 = (a+b)(a-b)$ and see that $a+b$ and $a-b$ differ by $2b$ (an even number). So an $a$ and $b$ exist such that $a^2-b^2 = x$ if and only if you can factor $x$ as the product of two integers which are both odd or both even. In fact, then $x$ has to be an odd number (since product of two integers is both odd) or it has to be divisible by $4$ (since it must be divisible by two even numbers).

A: Generally:

*

*If $x=4k$, then $(k+1)^2-(k-1)^2=x$

*If $x=2k+1$, then $(k+1)^2-k^2=x$

*If $x=4k+2$ then there are no solutions, because $a^2\equiv 0 \;\text{or}\; 1\pmod 4$, similar for $b^2$, so $a^2-b^2\equiv 0, 1 \;\text{or}\; 3\pmod 4$.


text:
Q: Parse xml/wsdl string with PHP I consumed using php-curl, a webservice API with soap-wsdl which doesn't return an xml object but a string like:
string(3854) "<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" xmlns:u="http://docs.oasis-open.org/wss/2004/ 01/oasis- 200401-wss-wssecurity-utility-1.0.xsd"><s:Header><o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/ wss/2004/ 01/oasis-200401-wss-wssecurity-secext-1.0.xsd"><u:Timestamp u:Id="_0"><u:Created>2022-03-18T01:53:32.688Z</ u:Created> <u:Expires>2022-03-18T01:58:32.688Z</u:Expires></u:Timestamp></o:Security></s:Header><s:Body><UrbanList xmlns="http://tempuri.org/"><D"...

How to turn the content of this string into an xml and parse this to an array, object, json... anything but a string?

A: Try this
$your_soap_string = 'YOUR SOAP STRING HERE';
$namespaces = ['s:', 'o:', 'u:']; // you need to add all if there are more
$clean_xml = str_ireplace($namespaces, '', $your_soap_string);
$xml = simplexml_load_string($clean_xml);


text:
Q: How to properly store big values in parallel SRAM For a project I need to determine the frequency and phase-shift of up to 16 channels. The frequency range is 0 to 3 kHz and the signalform is square.
My first idea was to use the following circuit to save the signals into a memory IC (SRAM):

(CTR = 16 Bit Address Counter, TMR = 21/32 Bit Timer)
The input channels IN are sampled on each positive CLK cycle.
If an edge occurred, the address counter is incremented and the WR (Write Enable) bit is set.
Then on the negative CLK cycle the SRAM is going to be active and saves the data if the WR bit was set.
The timer TMR is always incremented on each positive CLK cycle.
The sampling frequency (CLK) should be 20Mhz and the measurement period is 100ms:
Gives a 2'000'000 max. value for the timer: I need at least 21 bits to store the timer value:
21 Bits (timer) + 16 Bits (channels) = 37 Bits
But the data bus of the SRAM is only 32 bits wide so I need at least two write cycles to accomplish my task. I don't want to decrease sampling frequency because of the needed accuracy. So that is not an option.
I'm not exactly sure of how I can accomplish the two write cycles except to increase the SRAM write frequency to something ridiculous like 80 MHz. Another idea of mine was to simply just use two SRAMs instead of one, but this seems terrible inefficient.
So it all boils down to the following two questions:

*

*Is a CPLD capable of doing such high-speed logic? (80MHz and up) I have the fear I will experience clock-skew inside the CPLD: I can't test a CPLD because I don't have the adequate equipment to generate such high-speed signals.

*Is this circuit / idea even feasible or already too ''complex''? Are there easier solutions to my problem?


text:
Q: line-height are not the same between divs when copied with javaScript I found this issue which looks to me like a Chrome bug. Interested if others have crossed this one in the past, and if there's any good solution / workaround for it.
The issue: when I copy font-size and line-height from one div to an other, they won't look the same: Line-height will seem to differ. Please see Codepen link in the bottom.
How to reproduce:
Create two divs or textareas with classNames ta-source and ta-target, and add css for only the first one:
.ta-source{font-size: 1.4rem;line-height:1.42857}

Insert some multiline text in both, and then add javascript which copies these two properties to the other, so they would match in style:
var lh = window.getComputedStyle(document.querySelector(".ta-source")).lineHeight
var fs = window.getComputedStyle(document.querySelector(".ta-source")).fontSize

document.querySelector(".ta-target").style.lineHeight=lh;
document.querySelector(".ta-target").style.fontSize=fs;

That's about it, the two line-heights will seem to differ. Interestingly the issue with other line-heights won't occur, like line-height:1.42354. Issue on Firefox or Safari doesn't occur either.
Anyone came across this issue before?
Issue on Codepen: https://codepen.io/anon/pen/gVMeVw

var lh = window.getComputedStyle(document.querySelector(".ta-source")).lineHeight
var fs = window.getComputedStyle(document.querySelector(".ta-source")).fontSize

document.querySelector(".ta-target").style.lineHeight=lh;
document.querySelector(".ta-target").style.fontSize=fs;
.ta-target,.ta-source{height:200px;white-space:pre-wrap;float:left}
.ta-source{font-size: 1.4rem;line-height:1.42857}

  this
  is
  a
  simple
  multi
  line
  text
  where
  lines
  dont
  align
  with the other one

  this
  is
  a
  simple
  multi
  line
  text
  where
  lines
  dont
  align
  with the other one

A: Let's do some math:
You set on .ta-source font-size on 1.4rem, considering that the root element has font-size to 16px, the font-size of 1.4rem will correspond to 22.4px;
on .ta-source you also set line-height:1.42857,when line-height is defined as a unit-less number, the rule is the number will be multiplied with the current font size to set the line height; the current font-size is 22.4px, so it's equivalent to 31,999968px.
Now, when you get
var lh = window.getComputedStyle(document.querySelector(".ta-source")).lineHeight
var fs = window.getComputedStyle(document.querySelector(".ta-source")).fontSize

you receive two rounded numbers in px: you don't receive for lh nor 1,42857 neither 31,999968px, but 32px and for fs you don't get the measure in rem but in px, 22.4px. These measures are applied to ta-target, and I would even say correctly.
The differences, indeed, are on ta-source and in the way the line-height of 1.42857 equivalent to 31,999968px is rendered: some browsers rounds up, others down. Chrome rounds it down, Firefox rounds it up; Chrome rounds it to 31px, FIrefox to 32px (try to set in Chrome line-height on .ta-source to 32px, everything will align!).
So, the problem lies is the subpixel rendering problems. You will find tons of articles on google.


text:
Q: OF/AT THE legal age What differences are there between using 'at' and 'of' as prepositions before 'legal age' and other age-related noun phrases? I have encounter both constructions, though 'of' pops up more frequently in formal contexts. Why is that the case? Another pattern I noticed is that 'of' always immediately follows a noun, whilst 'at' enjoys greater flexibility. Bit what about the example below? Which one is the better fit and why?

*

*He is now [at (the) legal/of legal] age to go off to war.

A: The expression "of age" or, archaically, "of full age", means that an individual has reached the minimum age required.  The person may be well over the minimum age.  In your example, if the age to go to war is 18, then a 40-year old will be of age, just as much as an 18-year old.
The expression "at the age" is usually more specific.  It would refer to an individual who has recently reached the minimum age required.  Again in the example, an 18-year old would be described as being at the age while a 40-year old would not.


text:
Q: ms sql rounding issue in 3 to Nth decimal places i have a problem in this query
select 7.115 + 2.885

result is 10.000
versus this query
select round(7.115,2) + round(2.885,2)

result of it is 10.010
i wonder how to make it correct.

A: It is already correct. When you round it to 2 places, in both cases it is (correctly) being rounding up by effectively adding 0.005. The sum of these two rounding deltas is 0.01 so the result being 10.01 is as expected.
There is nothing to "fix" here - it is behaving correctly and as expected.
If you mean "how do I make it display 10.00 as the result of the addition", do this:
select round(7.115 + 2.885, 2)


text:
Q: Using JAXB to parse JSON in Jersey I'm trying to create a very simple RESTful web service using Jersey. I'm trying to make it so that it consumes and produces a JSON by using JAXB. The problem is that I get an error when I pass a JSON to it.
Below is the resource code. Both status() and echo() are working properly. Please note that on processRequest() I'm currently producing a text response, but that will be changed later to produce a JSON.
package web_service;

import javax.ws.rs.*;
import javax.ws.rs.core.*;

@Path("/")
public class WebService {

    @GET
    @Produces(MediaType.TEXT_PLAIN)
    public String status() {
        return "Web service is up and running.";
    }

    @POST
    @Consumes(MediaType.TEXT_PLAIN)
    @Produces(MediaType.TEXT_PLAIN)
    public String echo(String consumed) {
        return consumed;
    }

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.TEXT_PLAIN)
    public String processRequest(JAXBElement<Request> r) {
        Request request = r.getValue();
        return "Latitude: " + request.latitude +
            "\n:Longitude: " + request.longitude;
    }
}

This is the Request model:
package web_service;

import javax.xml.bind.annotation.XmlRootElement;

@XmlRootElement
public class Request {

    public String latitude;
    public String longitude;

    public Request() {}

    public Request(String latitude, String longitude) {
        this.latitude = latitude;
        this.longitude = longitude;
    }

    // Getters and setters for both
}

My web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:web="http://java.sun.com/xml/ns/javaee"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID"
    version="2.5">

     <servlet>
         <servlet-name>Jersey REST Service</servlet-name>
         <servlet-class>org.glassfish.jersey.servlet.ServletContainer</servlet-class>

         <init-param>
             <param-name>jersey.config.server.provider.packages</param-name>
             <param-value>web_service</param-value>
         </init-param>

         <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>Jersey REST Service</servlet-name>
        <url-pattern>/*</url-pattern>
    </servlet-mapping>
</web-app>

Finally, this is an example of the POST that I'm doing (headers set to 'Content-Type: application/json');
{
    "latitude":"25.764084501106787",
    "longitude":"-80.37422332275389"
}

When I run this, Tomcat gives me the following Exception:
WARNING: WebApplicationException cause:
org.glassfish.jersey.message.internal.MessageBodyProviderNotFoundException: MessageBodyReader not found for media type=application/json, type=class web_service.Request, genericType=class     web_service.Request.

And I get the following response:
415 Unsupported Media Type

Content-Length: 1 kB
Content-Type:   text/html;charset=utf-8
Date:           2013 Nov 4 17:41:20
Server:         Apache-Coyote/1.1

I'm very new to this and this is not making a lot of sense. Hopefully, one of you will be able to give me a hand. Thanks!

A: Try this in your endpoint:
@POST
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
public String processRequest(Coordinates coordinates) {
    return "Latitude: " + coordinates.getLatitude() +
        "\n:Longitude: " + coordinates.getLongitude();
}

where Coordinates is a simple POJO mirroring the JSON content you are posting.
Then use Jackson, which has JAXB support, by adding all the libraries to your project and adding this configuration:
<init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>org.foobar.rest.services;org.codehaus.jackson.jaxrs</param-value>
</init-param>

to the "Jersey REST Service" servlet.

A: Add this to your web.xml
<init-param>
        <param-name>com.sun.jersey.api.json.POJOMappingFeature</param-name>
        <param-value>true</param-value>
    </init-param>

For more details look at jersey documentation : https://jersey.java.net/documentation/1.18/json.html

A: JAXB (Java Architecture for XML Binding) avaialable in java for binding xml not for JSON.Here you are trying to convert JavaScript Object Notation with the help of xml binder in this situation and that is not possible. And i am pretty sure that you must be getting the error generated by " BodyWriter class " in the JAX-RS package....
Anyway If you want to produce and consume JSON using your resource you gonna need "moxy" JAR available in your project library for handing this conversion :)
Hope what i am writing here will be helpful for other programmers

A: this error happends when you are requesting without specified headers.
In your service
@Consumes(MediaType.APPLICATION_JSON)
@Produces(MediaType.TEXT_PLAIN)
Ensure that your request gets the header "content-type" ? application/json and the header "accept" contains text/html

A: I think, there is problem with your Request model class. Your model class is not specifying @XmlaccessType, so by default it is being considered as PUBLIC_MEMBER. As your instance variables are also public along with getters and setters, So JAXB is not able to figure out proper bindings.That's why that exception is coming. So there are two fixes to your problem.
1)You can make your instance variables as private.
2)Or you can explicitly specify @XmlaccessType for your model class and likewise provide   annotations in it which are non-conflicting.


text:
Q: Hibernate + MySQL. Ways to optimize selecting and loading data I'd like to test how selecting and loading data in java application using hibernate and mysql can be optimized.
I divided results I found into 2 groups
MySQL

*

*indexes - for sure

*stored procedures - is there a difference if select is done in stored procedure?

*views - is there a difference if select definition is kept in view?

*query cache - does it work only if we do the same select second time?

Hibernate

*

*hibernate cache - is this similar to query cache? how it can be configured?

*lazy loading - can it help?

Are there any other ways? I use simple queries with several joins and aggregation functions.
I need to demonstate time changes between "before" and "after" optimization.
For more information I tried to read this, but language is to complicated for me.

A: *

*Batch fetching is important when you read e.g. a collection. In that case Hibernate can get many rows of the collection in one SQL request, so that it would be faster.

*Hibernate caching is very good solution (read about EHCache for instance) it can store retrieved data on memory and if nothing changes on his side it can retrieve it without even asking SQL engine what's going on there.

*Lazy loading is a must for One to Many associations (you can kill your solution without this). But fortunately it is set by default in Hibernate for such associations.

You can also read about optimistic lock, which is faster than pessimistic lock in many cases.
Last but not least you should use proper transaction strategy, so that you shouldn't create new transactions when it is not necessary.


text:
Q: Creating a new column in data i have imported from a csv file i have a task that i need to complete in R studio using R language. i'm new to this.
i have a "CSV" file with a table that consists of 80 columns and 568 rows after i sampled 80% of the original data file. now i need to add a column to the table and calculate the (max - min) of each row and that column will show the results of each row in this new data file.
data <- read.csv(file.choose(), header=T)
data

data$maxSubMin <- for(i in 1:568){
  max(data[i,1:78]) - min(data[i,1:78])
}

there are no errors shown in the log, but there is no new column...
somebody knows whats the reason?

A: You can use row-wise apply :
data$maxSubMin <- apply(data[,1:78], 1, function(x) max(x) - min(x))

You can also take diff of range
data$maxSubMin <- apply(data[,1:78], 1, function(x) diff(range(x)))

Using rowMaxs and rowMins from matrixStats :
library(matrixStats)
data$maxSubMin <- rowMaxs(as.matrix(data[,1:78]))- rowMins(as.matrix(data[,1:78]))

A: The issue is that the for loop returns NULL. Hence you don't get a new column. To make your for loop work you have to do the assignment inside the loop, i.e.
for(i in 1:nrow(data)){
  data$maxSubMin[i] <- max(data[i,1:ncol(data)]) - min(data[i,1:ncol(data)])
}

Nonetheless the preferred approach would be to use apply as already suggested by @RonakShah. Using the iris dataset as example data:
#data <- read.csv(file.choose(), header=T)
data <- iris[,-5]

data$maxSubMin <- apply(data, 1, function(x) max(x, na.rm = TRUE) - min(x, na.rm = TRUE))
head(data)
#>   Sepal.Length Sepal.Width Petal.Length Petal.Width maxSubMin
#> 1          5.1         3.5          1.4         0.2       4.9
#> 2          4.9         3.0          1.4         0.2       4.7
#> 3          4.7         3.2          1.3         0.2       4.5
#> 4          4.6         3.1          1.5         0.2       4.4
#> 5          5.0         3.6          1.4         0.2       4.8
#> 6          5.4         3.9          1.7         0.4       5.0


text:
Q: problem with implicit ambiguity between my method and conforms in Predef The following code, which is taken from Apocalisp's excellent blog series:
Type level programming in scala , and modified for an implicit parsing scenario. However, this does not compile, with the following message:
error: ambiguous implicit values:
both method hParseNil in object HApplyOps of type => (com.mystuff.bigdata.commons.collections.hlist.HNil) => com.mystuff.bigdata.commons.collections.hlist.HNil
and method conforms in object Predef of type [A]<:<[A,A]
match expected type (com.mystuff.bigdata.commons.collections.hlist.HNil) => com.amadesa.bigdata.commons.collections.hlist.HNil
val l = hparse[HNil,HNil](HNil)

Can someone please explain why this happens, and if it's fixable?
sealed trait HList

final case class HCons[H, T <: HList](head: H, tail: T) extends HList {
  def :+:[T](v: T) = HCons(v, this)
}

sealed class HNil extends HList {
  def :+:[T](v: T) = HCons(v, this)
}

object HNil extends HNil

// aliases for building HList types and for pattern matching
object HList {
  type :+:[H, T <: HList] = HCons[H, T]
  val :+: = HCons

}

object HApplyOps
{
  import HList.:+:

  implicit def hParseNil: HNil => HNil = _ => HNil

  implicit def hParseCons[InH,OutH,TIn <:HList,TOut<:HList](implicit parse:InH=>OutH,parseTail:TIn=>TOut): (InH :+: TIn) => (OutH :+: TOut) =
    in => HCons(parse(in.head),parseTail(in.tail))

  def hparse[In <: HList, Out <: HList](in:In)(implicit parse: In => Out):Out = in

}

object PG {

  import HList._

  def main(args: Array[String]) {

    import HApplyOps._

    val l = hparse[HNil,HNil](HNil)

  }
}

A: Although i can't tell you exactly the purpose of Predef.conforms, i can tell you the ambiguity error seems correct (unfortunately). In the comment in the source it even says that <:< was introduced because of ambiguity problems of Function1 (says Function2 but i guess that is a mistake). But since <:< is a subclass of Function1 it can be passed in whenever Function1 is expected, so in your case its possible to pass in <:< to hparse.
Now the implicit def conforms[A]: A <:< A has the effect (from what i understand) that whenever a method expects a type A => A, it is sufficient to have an implicit value of A in scope.
In your case the implicit def hParseNil: HNil => HNil has the same priority as conforms and thus both could be equally applied.
I see two possible solutions:

*

*just remove the hParseNil, i think your code still works.

*shadow the Predef's conforms by naming yours the same:
implicit def conforms: HNil => HNil = _ => new HNil

A: You can just replace the function literal hParseNil to a normal function.
implicit def hParseNil(a:HNil): HNil = HNil
instead of
implicit def hParseNil: HNil => HNil = _ => HNil


text:
Q: What is destructive? I know that Ruby has many methods, especially on array or array like objects, for example sort or flatten. However, these methods also have a twin (the one with an exclamation mark) like sort! and flatten!.
Now my questions are:

*

*What is the difference between flatten and flatten! (destructive flatten)?

*A more general question, why is it called destructive?

A: The difference is simply that flatten returns a copy of the array (a new array that is flattened) and flatten! does the modification "in place" or "destructively."  The term destructive means that it modifies the original array.  This is useful for when you know what you want your end result to be and don't mind if the original structure gets changed.
As @padde pointed out, it will consume less memory as well to perform something destructively since the structure could be large and copying will be expensive.
However, if you want to keep your original structure it is best to use the method and make a copy.
Here is an example using sort and sort!.
a = [9, 1, 6, 5, 3]
b = a.sort
c = [7, 6, 3]
c.sort!

Contents:
a = [9, 1, 6, 5, 3]
b = [1, 3, 5, 6, 9]
c = [3, 6, 7]

A:
Array#flatten:- Returns a new array that is a one-dimensional flattening of self (recursively).
Array#flatten!:- Flattens self in place.

a = [1,2,[3,4]]
p a.object_id #=> 74502050
p a.flatten.object_id #=> 74501960
p a.flatten!.object_id #=> 74502050

flatten creates a new array object, as a.flatten.object_id shows a different value from a.object_id.
flatten! modifies the object that a references, which a.flatten!.object_id shows as 74502050.


text:
Q: How can I add a user to my database with SimpleMembership outside of the MVC Controller? I have the following code in my Accounts controller:
WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword);

This works and when I enter in a new line with the words WebSecurity I see intellisense provides me with all the options I expect.
I added the same code to another class but this time I have no options with WebSecurity. The class shows up but there are no methods that I can use.
Does anyone have any idea what might be wrong. How can I add a user outside of my controller to seed the database.
Here's what I am doing:
WebSecurity.CreateAccount("xx", "xx", true)

Here's the error message:
Error   2   'WebMatrix.WebData.WebSecurity.CreateAccount(string, string, bool)' is a 'method' but is used like a 'type'

A: You haven't provided the needed details, but I guess you have this line
WebSecurity.CreateAccount("xx", "xx", true)

not in a method. Like this (this will cause the error you're describing):
class AccountsController
{
   WebSecurity.CreateAccount("xx", "xx", true);
}

Check your syntax. Please post more code around the erroring line if this doesn't work.


text:
Q: SQL Server Entity Framework SaveChanges('insert') Error in Piecemeal Partial Restored Database We were troubling with moving large SQL Server database files from live system to test system. We found a piecemeal restoring solution. Because we only need latest records to test our system. We partitioned table by "id" column which is primary and identity.
It seemed it works with restoring 1 or 2 files over 10 files and with plain "select" and "insert" query.
But in application which we are using Entity Framework (EF) to query database 'insert' query had a problem.(Exception:One of the partitions of index '' for table 'table' partition ID... resides on a filegroup "...." that cannot be accessed because it is offline, restoring, or defunct. This may limit the query result.)
After checking the EF generated query
sp_executesql 'insert into table.... select id from table where @@rowcount>0 and Id=scope_idetity()'

I dig into the problem and I saw that 'scope identity' function needs extras files being restored.
My question is is there a different configuration to solve this issue or is there better solution fits our scenario in which needs large SQL file transfer to test system which only needs latest records.


text:
Q: What is the meaning of '.' in the cpio file This is my the content of my rootfs.cpio file:
[root@xilinx output]#  cpio -idv  < rootfs.cpio
.
init
dev
dev/console
1149 blocks

What is . here ?

A: . is the current directory. All directories on Linux file systems contain the hardlinks . and .. (the parent directory). For example:
 $ ls -a / | head -4
.
..
bin
boot

This is what enables you to do cd ../ to move to the parent directory or use constructs like find . to search the current directory (though the . is actually implied in find).


text:
Q: SQL Count within MAX select I need to crosstab some data from my sample table with counts of the crosstabed values.
In the table below I am displaying a few records for two participants, I need to crosstab this information with grouping on the PID.
Here is some data from the table:
PID   SAMPLE_TYPE  SAMPLE_VOLUME
PID1  PLASMA_EDT   250
PID1  PLASMA_EDT   1200
PID1  PLASMA_EDT   1000
PID1  PLASMA_EDT   1000
PID1  PLASMA_EDT   1000
PID1  SER          500
PID1  SER          500
PID1  SER          1000
PID2  PLASMA_EDT   250
PID2  PLASMA_EDT   1200
PID2  PLASMA_EDT   1000
PID2  PLASMA_EDT   500
PID2  PLASMA_EDT   1000
PID2  SER          500
PID2  SER          1000
PID2  SER          1000

What I need as an output is the following:
PID   PLA_250  PLA_500  PLA_1000  PLA1200  SER_500  SER_1000
PID1  1        0        3         1        2        1
PID2  1        1        2         1        1        2

So I tried with the following but come up with error:
Cannot perform an aggregate function on an expression containing an aggregate or a subquery.

.
SELECT  S.C_PID AS PID,
        MAX(CASE WHEN S.SAMPLE_TYPE = 'PLASMA_EDT' AND S.SAMPLE_VOLUME = '250' THEN COUNT(CONCAT (S.SAMPLE_TYPE, S.SAMPLE_VOLUME)) ELSE '' END) AS 'PLA_250',
        MAX(CASE WHEN S.SAMPLE_TYPE = 'PLASMA_EDT' AND S.SAMPLE_VOLUME = '500' THEN COUNT(CONCAT (S.SAMPLE_TYPE, S.SAMPLE_VOLUME)) ELSE '' END) AS 'PLA_500',
        MAX(CASE WHEN S.SAMPLE_TYPE = 'PLASMA_EDT' AND S.SAMPLE_VOLUME = '1000' THEN COUNT(CONCAT (S.SAMPLE_TYPE, S.SAMPLE_VOLUME)) ELSE '' END) AS 'PLA_1000',
        MAX(CASE WHEN S.SAMPLE_TYPE = 'PLASMA_EDT' AND S.SAMPLE_VOLUME = '1200' THEN COUNT(CONCAT (S.SAMPLE_TYPE, S.SAMPLE_VOLUME)) ELSE '' END) AS 'PLA_1200',
        MAX(CASE WHEN S.SAMPLE_TYPE = 'SER' AND S.SAMPLE_VOLUME = '500' THEN COUNT(CONCAT (S.SAMPLE_TYPE, S.SAMPLE_VOLUME)) ELSE '' END) AS 'SER_500',
        MAX(CASE WHEN S.SAMPLE_TYPE = 'SER' AND S.SAMPLE_VOLUME = '1000' THEN COUNT(CONCAT (S.SAMPLE_TYPE, S.SAMPLE_VOLUME)) ELSE '' END) AS 'SER_1000'
FROM    SAMPLE S
WHERE   S.C_PID IN ('PID1','PID2')
        AND S.SAMPLE_TYPE IN ('PLASMA_EDT','SER')
GROUP BY S.C_PID

How should I be tackling this?
Thanks,
Greg

A: You probably want:
SUM(CASE WHEN S.SAMPLE_TYPE = 'PLASMA_EDT' AND S.SAMPLE_VOLUME = '250' THEN 1 ELSE 0 END) AS 'PLA_250',

A: You can simplify those aggregations
For example:
...
COUNT(CASE WHEN S.SAMPLE_TYPE = 'PLASMA_EDT' AND S.SAMPLE_VOLUME = '250' THEN 1 END) AS [PLA_250],
...


text:
Q: Label Encoding for columns with sentences or long texts - keras I have been searching how to encode multiple columns with long or short texts, but I couldn't really find any good solutions. Here is an example from my data-set:
IP         Country  Domain          Attack           Signature          Thread
0.0.0.0.0  US       somedomain.net  compromized site 8787tgd9347343dex  yes
1.1.1.1.1  US       otherdomain.net trojan           74384399rfg99737h1 yes

So far I have tried LabelEncoder and OneHotEncoder from sklearn, but they didn't work. Any feedback, help, or direction is much appreciated.
EDIT

I figured I would give more details about what I am trying to accomplish
import pandas as pd
from sklearn.preprocessing import LabelEncoder, OneHotEncoder, StandardScaler

df = pd.read_csv("export.csv", sep=",")

labelencoder = LabelEncoder()

def encoder(x = len(df.columns)):
    for i in range(x):
        df.iloc[:, i] = labelencoder.fit_transform(df.iloc[:, i])

encoder()

Now, I have a data frame with the below:

However, this doesn't look like the right way of doing this.
Thanks

A: You could use DictVectorizer from sklearn.feature_extraction
import pandas as pd
from sklearn.feature_extraction import DictVectorizer

data=pd.read_csv('export.csv',encoding = "utf-8", header=0)
vectorizer = DictVectorizer(sparse=False)
X = vectorizer.fit_transform(data[data.columns[0:]].to_dict("records"))

print(X)

For the following input:
          IP Country           Domain            Attack           Signature Thread
0  0.0.0.0.0      US   somedomain.net  compromized site   8787tgd9347343dex    yes
1  1.1.1.1.1      US  otherdomain.net            trojan  74384399rfg99737h1    yes

The output looks something like this:
[[0. 1. 1. 0. 1. 1. 0. 0. 1. 1.]
 [1. 0. 0. 1. 1. 0. 1. 1. 0. 1.]]

Assuming that all the columns are training features, if the last column 'Thread' is a label you should modify the code :
ln=(len(data.columns)-1)
vectorizer = DictVectorizer(sparse=False)
X = vectorizer.fit_transform(data[data.columns[0:ln]].to_dict("records"))
Y = data[data.columns[ln]]

I hope this helps you


text:
Q: How to verify fingerprint of Dropbear RSA host key? When I connect to my Dropbear SSH server for the first time, I get the following message:
me@laptop:~$ ssh me@server
The authenticity of host 'server' can't be established.
RSA key fingerprint is SHA256:NycCxoRiiSAGA7Rvlnuf1gU8pazIpXJKZ3ukdivyam8.
Are you sure you want to continue connecting (yes/no)?

To make sure that this is the correct server, I want to compare the stated fingerprint from that message to the server's real fingerprint. How can I find out the server's RSA host key fingerprint?

A: Locate the host key file on the server:
me@server:~$ ls /etc/dropbear/
authorized_keys  config  dropbear_rsa_host_key

Use dropbearkey to get the public key portion and fingerprint of that host key:
me@server:~$ sudo dropbearkey -y -f /etc/dropbear/dropbear_rsa_host_key
Public key portion is:
ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQCk/0IEQhlDHfe3jd1MafWLEsTMFADflBWiODik6CnHXmXUrp1XmQ0fo16ffRxupnIuieU44VZkfCP8MX+WIVMRc/+UOJAox7U+v7B3T9H0a4ZeB48NyPdUCZ9MVSbk+kWmHn+UoXtPdMZ/htQ13XHJLHU8h2I+4dTUs1TYWeW4b8LppRexUJPCjdc9YxmkwI+ctHs6I1oguqSy6IP+aAlK0+QkNrG8HeFe1Nmg2iL5SuYfJCIgxJylK+s6KVMpzVPv7VNX3bSt1NJvf2etowR7kzTZs+uCJyzdILO2p5yAo9V80/zzwyqV+exPHUjD/SE9tYjEBkzKKNo215xQvAzV me@server
Fingerprint: sha1!! 41:b0:5e:af:8c:4d:2b:ae:fd:75:7d:f1:d5:35:e1:49:14:2e:08:12

The hash algorithm will be different, depending on your version. Pipe the public key portion into ssh-keygen to use a specific hash algorithm:
me@server:~$ sudo dropbearkey -y -f /etc/dropbear/dropbear_rsa_host_key | ssh-keygen -l -f - -E sha256
2048 SHA256:NycCxoRiiSAGA7Rvlnuf1gU8pazIpXJKZ3ukdivyam8 me@server (RSA)
me@server:~$ sudo dropbearkey -y -f /etc/dropbear/dropbear_rsa_host_key | ssh-keygen -l -f - -E sha1
2048 SHA1:QbBer4xNK679dX3x1TahSRMuLBI me@server (RSA)
me@server:~$ sudo dropbearkey -y -f /etc/dropbear/dropbear_rsa_host_key | ssh-keygen -l -f - -E md5
2048 MD5:bb:36:37:3e:ae:36:69:d3:6d:63:b8:a3:97:c3:78:60 me@server (RSA)


text:
Q: Expo - LocationTaskService.java NullPointerException on Intent.getExtras() Creating an Expo app and have it run a sticky notification, results in a NullPointerException after 15-60 minutes.
Here is the RN code
//backgroundTasks.js

import {Permissions} from 'react-native-unimodules';
import * as Location from 'expo-location';
import * as TaskManager from "expo-task-manager";
import {getStore} from "../redux/configureStore";
import {newLocation} from "../redux/actions/device";
import {Log} from "./log";
import {Colors} from "./style/colors";
import * as db from '../utils/db';
import {getTranslator, secondsToInterval} from "./functions";
import {showAlert} from "../redux/actions/app";
import {APP} from "../redux/constants/app";
import {setIgnoreState} from "./state";

export const BG_TRACKING = 'BG_TRACKING';

Log.info(`Unregister all tasks`);
TaskManager.unregisterAllTasksAsync().then(() => {
    Log.info(`Defined new background task ${BG_TRACKING}`);
    TaskManager.defineTask(BG_TRACKING, async ({ data: { locations }, error }) => {
        if(error) {
            Log.error('Error received for locations', error);
        } else {
            locations.forEach(l => getStore().dispatch(newLocation(l)));
        }
    });
});
export const unregister = async () => {
    if(await Location.hasStartedLocationUpdatesAsync(BG_TRACKING)) {
        await Location.stopLocationUpdatesAsync(BG_TRACKING);
    }
};

let permissionIndicationOpen = false;
export const register = async () => {
    let user = getStore().getState().get(APP).get('currentUser');
    if(!user) return;
    let permissionState = await Permissions.getAsync(Permissions.LOCATION);
    if(!permissionState.granted || permissionState.canAskAgain) {
        if(permissionIndicationOpen) return;
        permissionIndicationOpen = true;
        setIgnoreState(true);
        permissionState = await Permissions.askAsync(Permissions.LOCATION);
        setIgnoreState(false);
        if(permissionState.granted) {
            permissionIndicationOpen = false;
        } else {
            const t = await getTranslator();
            getStore().dispatch(showAlert(t('needPermission'), t('locationPermissionNeeded'), {
                onConfirm: () => {
                    permissionIndicationOpen = false;
                    register()
                }
            }));
        }
    }
    const start = async () => {
        const t = await getTranslator();
        try {
            Log.info(`Registering background task ${BG_TRACKING}`);
            let trackingInterval = await db.getValue('trackingInterval');
            if (!trackingInterval) return;
            let interval = +trackingInterval;
            if (interval < 0) interval = 60 * 60 //every hour, but it will be ignored by the server;
            await unregister();
            await Location.startLocationUpdatesAsync(BG_TRACKING, {
                accuracy: Location.Accuracy.Highest,
                timeInterval: interval * 1000,
                foregroundService: {
                    notificationBody: +trackingInterval > 0 ? t('yourPositionIsBeingMonitored', {
                        period: secondsToInterval(t, interval)
                    }) : t('positionSentOnlyOnAlarm'),
                    notificationColor: Colors.primary
                }
            });
            Log.info(`Successfully registered background task ${BG_TRACKING}`);
        } catch (e) {
            Log.error(`Failed registering background task ${BG_TRACKING}`);
            Log.error(e);
        }
    };
    await start();
};

This file is called in the index.js, the entry point.
Then I see this stacktrace in Crashlytics.
Fatal Exception: java.lang.RuntimeException: Unable to start service expo.modules.location.services.LocationTaskService@97ff6c3 with null: java.lang.NullPointerException: Attempt to invoke virtual method 'android.os.Bundle android.content.Intent.getExtras()' on a null object reference
       at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:4222)
       at android.app.ActivityThread.access$2100(ActivityThread.java:231)
       at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1984)
       at android.os.Handler.dispatchMessage(Handler.java:107)
       at android.os.Looper.loop(Looper.java:214)
       at android.app.ActivityThread.main(ActivityThread.java:7682)
       at java.lang.reflect.Method.invoke(Method.java)
       at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:516)
       at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

A: Here is the fix
https://github.com/expo/expo/issues/8483
Apparently, changing the return flag of startService to REDELIVER_INTENT fixes it.


text:
Q: Ember Handlerbars @ How to access inner dict values via parent index? @index, index is not working inside templates. I dont know exactly. Therefore, I have moved to {{_view.contentIndex}} for getting index value.
Question No 1:
How to access second_dict values via parent index ?
Let say, I have two dicts
first_dict = [{"name":"x"},{"name":"y"},{"name":"z"}]
second_dict = [{"name":"x"},{"name":"y"}]

{{#each first in first_dict}}
   {{_view.contentIndex}} # output as 0,1,2
   ???{{second_dict._view.contentIndex.name}} # how to access second_dict value based on parent index ?
{{/each}}

A: Use {{get}} helper and custom {{to-string}} helper:
{{#each first_dict as |first index|}}
  Second dict value: {{get (get second_dict (to-string index)) 'name'}}
{{/each}}

{{get}} helper documentation.

*

*Working demo.

*Full code behind demo.


text:
Q: WMS scale denominators and zoom levels: why are these tables different? I'm trying to understand how WMS scale denominators translate to tile zoom levels.  (Specifically, Google Maps zoom levels.)  I found this answer to What ratio scales do Google Maps zoom levels correspond to? and this OpenStreetMap reference, which are in the same ballpark but differ by about 10%.
Why are they different?
Does it depend on the projection used?
Does it depend on latitude?
The width and height of the WMS request?
Anything else?
Note that I am not interested in true scales here.  Given the min and max scale denominators from the WMS capabilities XML, and using using this approach to calculate the size and position of tiles, I want to know what zoom levels I can expect the WMS endpoint to provide images for.

A: The most likely difference is the screen resolution assumed - the OGC SLD standard says:

The "standardized rendering pixel size" is defined to be 0.28mm ×
0.28mm (millimeters). Frequently, the true pixel size of the final rendering device is unknown in the web environment, and 0.28mm is a
common actual size for contemporary video displays. If the
map-rendering software has information available about the actual
pixel size of the final display device, then an extra processing step
will be needed (if the actual pixel size is different from the
standard pixel size) to adjust the actual rendering scale to calculate
the standard rendering scale, which will then be used to compare to
the scale range of an SLD rule. If the actual display device has
non-square pixels, then a method of "linear equivalence" to square
pixels should be used to calculate the standard rendering scale.
For
example:

actual_linear = sqrt(actual_x_size * actual_y_size)

While I think Google (and others) go with 96DPI - which is about 10% different.


text:
Q: Save user specified settings on flash drive With some help in this forum I already managed to successfully setup Quantum GIS 1.8 on a flash drive (see my post on Running QGis from flash drive).
QGis starts and runs stable on different computers, but I still have problems to port also user speficied settings. To port the settings I use the [--configpath] option as suggested in the QGis-Manual. According to this I changed the qgis.bat batch file this way to start QGis with a qgs-project file:
start "Quantum GIS" /B %OSGEO4W_ROOT%\apps\qgis\bin\qgis.exe --configpath %DRV_LTR%\qgisconfig\ %DRV_LTR%\Daten\TESTPROJEKT.qgs

In general this works fine -  QGis starts with the determined project file on different working stations. And installed Plugins, for example, also appear installed when the flash drive is connected to another working station. But it seems, that the [--configpath] option does not port user speficied settings themselves: Installed Plugins do not appear checked when set to another workstation, removed toolbars on one machine appear on the other, so do by "Customization" hidden parts of QGis.
It seems, that these UI-settings still are saved locally. When removing all entries in the Windows registry, keys appear from new in HKEY_CURRENT_USER\Software\QuantumGIS after running QGis.
I was hoping that the [--configpath] option could also save user specified settings on the flash drive. The overall goal of my work is to supply non-GIS experienced project partners with an easy to handle GIS-Data-Viewer, that can be used without installation. Especially with the new "Customization" dialog QGis 1.8 seems to be perfect fort that, if not used Menus and Toolbars could just be turned off or hidden.
I am thankfull for any suggestions!

A: After reporting the bug to the QGIS developers the problem of ignoring the path of user speficied settings already has been fixed. When using nightly build of QGIS 1.9 through the OSGEO installer the changes are already made - and it seems to work stable!


text:
Q: Check for custom URL scheme in browser I have an application that registers a new URL scheme when it's installed and I'm looking for a reliable way to launch this application from our web interface.
Right now I have an IFrame hidden away which I will update it's source after a button is clicked to launch the application, but it seems that in Internet Explorer the parent window always captures the URL scheme not recognized error and navigates to the location it can't understand anyway.
So my question: Is there a way for a programmer to check to see if a scheme is supported by a browser before attempting to navigate to the new URI to direct a user to download the application first?

A: You cannot check for URL schemes installed on the device.
What you can do is this:
setTimeout(function () { window.location = "appCustomUrlSchemeHere"; }, 25);

window.location = "fallbackUrlHere";
But I imagine that will still cause issues in IE as it will attempt to open the URL scheme.


text:
Q: How can I make a snapshot image of a web page in php? I am using php and I want to take a snapshot of my web page using php. Something similar to this
http://www.moneycontrol.com/gd/mail_indices.php
How can i do that?

A: To take Snapshots of a website, and not as proposed generate an image with text in it, you can use either
http://iecapt.sourceforge.net/ for snapshots using IE's rendering engine or
http://cutycapt.sourceforge.net/ for Webkit (Safari/Chrome) snapshots
I strongly recommend the latter.

A: You can use Imagemagick.

A: Theres is a comprehensive summary of image creation option in Php here. The other option not already mentioned is Cairo.

A: The fastest and surest way in PHP to create images is to look at the GD Library. They have tons of functions to help you create your image easily.
Should you need a font that is available in Windows Font but not in PHP font, you can use this tool to convert it: http://www.wedwick.com/wftopf.exe


text:
Q: gcloud auth activate-service-account logout / revoke / remove / unset I,ve added my service-account successfuly using below command.

gcloud auth activate-service-account --key-file=mycredentialsialreadyhad.json

Now I can't remove or logout from it.
any help would be greatly appreciated.
edit:
i tried this commands and got error

*

*gcloud auth revoke

ERROR: (gcloud.auth.revoke) Cannot revoke GCE-provided credentials.

*gcloud config configurations delete default

ERROR: (gcloud.config.configurations.delete) Deleting named configuration failed because configuration [default] is set as active.  Use gcloud config configurations activate to change the active configuration.

edit2: this gcloud cli is on GCP ubuntu VM

A: I may be late to the party on this, but the solution that I found works is:
gcloud config unset auth/impersonate_service_account

Followed by:
gcloud auth login

A: TLDR; To logout from all accounts
gcloud auth revoke --all

To check active account logins
gcloud auth list

To logout form one account only (take account from command above)
gcloud auth revoke [ACCOUNT]

A: this error happens when you try to remove a service account that was propagated to the machine during the creation time (docs here).
this service account could not be removed from your machine.
in any other case, the following commands should work (as mentioned in other answers here).
gcloud auth revoke --all

OR
gcloud auth revoke [ACCOUNT]

A: UPDATE
Use a command with a specified account because you can't revoke the Compute Engine service account(default).
For example:
gcloud auth revoke serviceaccount@testproject.iam.gserviceaccount.com

and run:
gcloud auth list

It should only display the default service account of the Compute Engine:

[PROJECT-NUMBER]-compute@developer.gserviceaccount.com

A: Use the  below syntax to activate the service account. Here we need to mention service account ID.
gcloud auth activate-service-account testpck@xxxxxx.iam.gserviceaccount.com --key-file=xxxxxx.json --project=xxxxxx
Use the below syntax to revoke the service account:
gcloud auth revoke testpck@xxxxx.iam.gserviceaccount.com
Error encountered in your case because the service account ID was not mentioned in gcloud auth revoke command , which is trying to revoke your active google account.
Permissions are denied if you disable the service account instead of revoke. If you revoke the service account then default account will get activated and that might have permission to storage.

A: In addition to gcloud auth revoke commands mentioned above, I also had to unset the GOOGLE_APPLICATION_CREDENTIALS env variable.
unset GOOGLE_APPLICATION_CREDENTIALS


text:
Q: import requests on AWS Lambda for python 3.8 The trick to use requests from botocore.vendored no longer works with Python 3.8 on AWS Lambda which I assume includes the latest botocore-1.13.
This version no longer embeds requests. Importing it works but the package is actually empty.
[ERROR] AttributeError: module 'botocore.vendored.requests' has no attribute 'post'

Is there a way to import requests on native lambda? It's a basic and it would be a pain to go through the process of packaging the code for very simple Lambda.
Alternatively, anyone has another trick to call API-Gateway without requests?

A: Oh wow, I guess this is a 'breaking-change' on AWS Lambda that we rarely see.
AWS have warned about this before, there's a few options:

*

*Use Serverless Framework and that serverless-python-requirements plugin

*See if the Python3.7 Lambda Layer for requests from this repo works for Python3.8

*Package it yourself using lambci for python3.8

A: Install "requests" locally in your project:
pip install requests -t ./

and then package and deploy it - sample here using the serverless framework:
serverless deploy -s test

A: You can pip install packages at an EFS endpoint.
pip install requests -t efs_endpoint
Mount that EFS endpoint from your Lambda function. Then import sys in your lambda function and add your module installation path:
sys.path.insert(0, '/efs_mnt/path/to/module')
Then you can import the module into your python environment in Lambda.
It's not too difficult to set up EFS and figure out how to mount it- you may need to change ownership of the mount point to allow writes.
You can also import external modules into Lambda in a zip file but you are limited (substantially) in the size.

A: I had the same problem. The way to solve it is to use a custom layer in AWS lambda that contains the relevant site-packages you require.
It worked for me.
One example that show you how to create a layer (via a quick google) is here: https://dev.to/razcodes/how-to-create-a-lambda-layer-in-aws-106m

A: Install the requests dependency separately.
$ pip install requests
Use the below import.
import requests
response = requests.get('https://...')

Removing the vendored verion and alternate solution
Associated PR which introduced this change


text:
Q: PCB Layout - Best way to hand solder under pads
Currently i'm drawing a pcb board in Eagle. Can't get a viable solution to allow people easy handsolder this component (WS2812B).
I will have 60 of this in the PCB, and i like to use them instead of RAW LED because it already contains the capacitor and resistor, so it will spare 60x4 solder joints. Also i find the price lower than source led + capacitor + resistor.
PCB is to be hand soldered like a KIT. No autoplacement machines.
My main ideia is place them at top layer and do vias to solder from bottom layer. Is it viable or there are better solutions?
Regards

A: Seems this device is designed to be cable-mounted. I very doubt people will be able to mount it onto the board through vias. There're several risks to it:

*

*insufficient solder: bad connection through vias, which may break in most critical situation. I think you do not want returns and bad reputation for bad kit design;

*too much solder: risking to short the pins, potentially frying the device.

If you'd be soldering it yourself, probably you can manage to have acceptable soldering quality (after several broken boards), but as others will be soldering it I very doubt they will gain required skill to solder them properly.
Go for separate components, even if it is more cost and more work on soldering.

A: How big are the pads?  With power pads on opamp IC's I'v'e put one or two big holes under the pad and then hand soldered to that... a big blob of solder fills up the hole.

A: You don't provide a datasheet, so I used this one:
https://cdn-shop.adafruit.com/datasheets/WS2812B.pdf
This part does not have a thermal pad under the chip, only four SMD pins, on standard SMD pads, so it will be as easy to solder as any other SMD.
I don't understand why you talk about vias. Just solder them like any other SMT part.


text:
Q: values of the corners of the div finding the four values of the corners of the div area

A: relative to the document:
var offset = $('#div').offset();
var x1 = offset.left;
var y1 = offset.top;
var x2 = x1 + $('#div').width();
var y2 = y2 + $('#div').height();


text:
Q: JavaScript Classes and Variable Scope I'm relatively new to JS and I'm having issues properly emulating OOP principles.
I guess I have two questions. Question the first is regarding the many ways to declare variables.
Say I have a class:
function clazz(a)
{
    this.b = 2;
    var c = 3;
    this.prototype.d = 4; // or clazz.prototype.d = 4?
}

var myClazz = new clazz(1);

Am I correct in the following assessments:
a is a private variable that is instance specific (i.e. different instances of clazz will have unique and independent variables 'a'). It can be accessed from within clazz as: 'a'.
b is a public variable that is instance specific. It can be accessed from within clazz as 'this.b' and from outside clazz as 'myClazz.b'.
c is a private variable that is static, or class specific (i.e. different instances of clazz will share the same 'c' variable). It can be accessed from within any instance of clazz as 'c' and changes in instance of clazz are reflected in all instances of clazz.
d is a public variable that is static/class specific. It can be accessed from anywhere via 'clazz.prototype.d' or 'myClazz.prototype.d'.
The overall issue I have with my understanding of the variable scheme is that there's no way to declare a private variable that is NOT static (i.e. a unique version for every instance of the class).
The second question is with respect to different types of class declarations.
I've been using:
var MySingleton = new function() {...};

to create singletons. Is this correct? I'm also unsure as to the effect of the "new" keyword in this situation as well as appending () function braces to the end of the declaration as so:
var MySingleton = new function() {...}();

I've been using this pattern to declare a class and then instantiate instances of that class:
function myClass() {...};
var classA = new myClass();
var classB = new myClass();

Is this the proper method?

A: OK, lets go over this:

*

*'a' is an argument passed to the constructor of your class. It will only exist for the duration of the constructor's invocation. This means you should probably store its value somewhere.

*'b' is a public instance member. It is instance specific (altho, since you're assigning the value in the constructor, all instances will initially have the same value for 'b').

*'c' is a private instance member. It will, however, only be accessible inside your constructor since it is only defined in that scope. Unless you refer to it from a closure inside your constructor function, its fate will be similar to that of 'a' above.

*'d' is a public instance member. Each instance of your class will have a member 'd' with the value 4 initially. Note however that assigning a reference type object to a prototype member of your class (such as 'd') will make every instance member 'd' refer to the same object. Example:
MyClass.prototype.d = { prop1: 'val1', prop2: 'val2' };
var a = new MyClass();
var b = new MyClass();
a.d.prop1 = 'foo'; // is the same as: b.d.prop1 = 'foo';

*Static members of the class are defined using:
function MyClass()
{
  // ...
}
MyClass.staticMemeber = 'I am a static member';

You should probably not treat MyClass.prototype as a place to hold your static members/methods.Everything assigned to a classes' prototype is in turn a member of each of its instances.

*When ()'s are attached to a function definition (right after the block), the function is executed. That means:
var myFunc = function() { alert('blah'); }();

would result in nothing more than a method invocation. The following code:
 var MySingleton = new function() {...}();

would mean 'use the return value from function() as the constructor for MySingleton'.

A: You are right for a and b:
a is an argument, available only within the scope of the constructor function.
bis a public instance variable, available on all instances created with that constructor function.
c is a private variable, accessible only within the constructor function.
The d declaration is invalid, because the prototype object is meant to be used only on constructor functions, like Clazz.prototype.d = 3;, if you do it like this, the variable will be shared, but you can assign a value on an specific instance, and the default value will be shadowed (through the prototype chain).
For "private variables" you can use the way you declare c, for example:
function Clazz(){
    var c = 3; // private variable

    this.privilegedMethod = function () {
      alert(c);
    };
}

Privileged methods, are public, but they can access "private" variables declared inside the constructor function.
For creating singletons, the easiest way is maybe to use an object literal, like:
var myInstance = {
  method1: function () {
    // ...
  },
  method2: function () {
    // ...
  }
};

And if you want private members on your singleton instance, you can:
var myInstance = (function() {
  var privateVar = '';

  function privateMethod () {
    // ...
  }

  return { // public interface
    publicMethod1: function () {
      // all private members are accesible here
    },
    publicMethod2: function () {
    }
  };
})();

This is has been called the module pattern, it basically allows you to encapsulate private members on an object, by taking advantage of the use of closures.
More info:

*

*Private Members in JavaScript

*Introduction to Object Oriented JavaScript
Edit: About the syntax you post:
var mySingleton = new (function() {
  // ...
})();

By using the new operator, you are declaring and using in one step an "anonymous constructor function", which will generate a new object instance, it is valid but I personally would prefer the "module" pattern approach, to create my own object instance (and avoid new).
Also, reading new function () {}, I think that is not really intuitive and may create confusion, if you don't understand well how the new operator works.
About the parentheses, they are optional, the new operator will call the function constructor without parameters if you don't add them (see ECMA-262, 11.2.2).


text:
Q: Which character does this "stunt" lightsaber belong to? It appeared in Star Wars Ep II Does anyone know which character this stunt lightsaber belonged to in Star Wars: Attack of the Clones?
A bit of background: I worked on the film for nearly 12 months. Was generously gifted the lightsaber below at the end of principal photography. Forgot I had it. Thought I'd look into it before dumping it back into the box. It has a green screw on saber (which special effects were of course then added to)

A: This lightsaber style was used by a variety of Jedi in Attack of the Clones (and was used in all three prequels, although only on a belt in Ep.1). Your stunt prop style saw a lot of use from a number of background Jedi on Geonosis in Ep.2, including from Jedi named Jedi such as Luminary Unduli and Plo Koon.
Of the original six saber designs created during pre-production on Episode 1, two were hand picked by Ewan and Liam, and the others became the basically the same 4 sabers every Jedi uses in the prequels aside from the Anakin and new Mace designs made for Ep.2. I am not counting Sith sabers, nor the new Anakin and Obi-Wan from Ep.3.  But for everyone else you see wielding a saber in Episode 2 and 3...they are using these original saber designs. So, your particular stunt saber could have been used by any number of background stunt jedi or one of the more well known Jedi Council jedi. It's a great hilt design that shares some of the same detailing found on the emitter end of Darth Maul's lightsaber prop.

Attached is another stunt example of this prop that I have had access to in the past.

A: It could be Jedi Master Luminara Unduli's lightsaber.
This is a scan from The Visual Dictionary of Star Wars, Episode II - Attack of the Clones.

The caption states that her lightsaber follows a "common lightsaber design".
In fact, the same page shows Plo Koon's lightsaber, which is very similar:

The main difference is in the color of the "radiator casing", which is golden in Luminara Unduli's saber and silver/steel coloured in Plo Koon's; moreover, Plo Koon's lightsaber shows blue markings at the opposite end.
This image, a particular taken from the image gallery in her official databank page, shows her some years later, in the Clone Wars animated series, using the same lightsaber:

There is a non-matching detail: the color of the round buttons, which are green and grey in the question image and red and green in these images. However, this could be due to degradation of the paint on the prop, especially as the buttons would be right in the grip of the person holding the lightsaber.
Additional images showing the lightsaber (click to enlarge), found by our most excellent chancellor @Valorum:


text:
Q: PubSub script not accepting variables I found a PubSub script on the internet, which works quite well, unfortunately I don't completely understand how it works...
This wasn't a problem until now. For a project I need to call a function via this pubsub script and pass it some arguments. However, the function seems to not accept any arguemnts and only passes the changed variable of its event.
Here is the line of code which subscribes to a PubSub event and calls a function:
events.on( 'scrollChanged', self.translate );

As you can probably tell, the event is a scroll event and the passed value is the amount of pixels scrolled.
This line stands inside a jQuery plugin, which I'm currently developing and should act as a function call, which we would normally wirte like this: self.translate()
Until now, everything works well, but the translate function also needs some other variabels from the init-function (from which it is called).
So normally I would write:
[...]
init: function( options, this ) {
  // Logic
  self.translate(var1, var2);
},

translate: function( var1, var2 ) {
  // Logic
}
[...]

To have the function update while scrolling I need to call it with the events.on( 'scrollChanged', self.translate ); funtion and also pass the yScroll variable for some calculations. But if I pass the two variables to this, I only get error messages which tell me, that the function is undefined.
// Exchanged `self.translate(var1, var2);` in the above code by:
events.on( 'scrollChanged', self.translate(var1, var2) );

So I'm guessing, that the PubSub code does not accept any other variables?!
Hope that anyone can help me out.

PubSub Code
var events = {
  events: {},
  on: function (eventName, fn) {
    this.events[eventName] = this.events[eventName] || [];
    this.events[eventName].push(fn);
  },
  off: function(eventName, fn) {
    if (this.events[eventName]) {
      for (var i = 0; i < this.events[eventName].length; i++) {
        if (this.events[eventName][i] === fn) {
          this.events[eventName].splice(i, 1);
          break;
        }
      };
    }
  },
  emit: function (eventName, data) {
    if (this.events[eventName]) {
      this.events[eventName].forEach(function(fn) {
        fn(data);
      });
    }
  }
};

The error occurs in this line of the emit-function:

fn(data);

and tells me, that fn is not defined.
Here's the code of the emit which works well, if no arguments are passed:
$(window).scroll(function(){
  var yScroll = $(this).scrollTop();

  events.emit('scrollChanged', yScroll);
});

A: Pass function reference to .on() at second parameter instead of calling function immediately by invoking with (); define rest parameters as second parameter to emit, use destructuring assignment, spread element at fn to define arguments passed to fn as an array within fn function body

var events = {
  events: {},
  on: function (eventName, fn) {
    this.events[eventName] = this.events[eventName] || [];
    this.events[eventName].push(fn);
  },
  off: function(eventName, fn) {
    if (this.events[eventName]) {
      for (var i = 0; i < this.events[eventName].length; i++) {
        if (this.events[eventName][i] === fn) {
          this.events[eventName].splice(i, 1);
          break;
        }
      };
    }
  },
  emit: function (eventName, ...data) {
    if (this.events[eventName]) {
      this.events[eventName].forEach(function(fn) {
        fn(data);
      });
    }
  }
};

function cb() {
  var [args] = [...arguments];
  console.log(args, args[0], args[1]); // `["abc", 123]`, `"abc"`, `123`
}

events.on("scrollChanged", cb);
events.emit("scrollChanged", "abc", 123);


text:
Q: How do I convert a functional DSL into a Monad in Haskell? The following Haskell code is a simple "console IO" DSL:
data Ap a = Ap { runAp :: ApStep a }

data ApStep a =
    ApRead   (String -> Ap a)
  | ApReturn a
  | ApWrite  String (Ap a)

ioRead    k   = Ap $ ApRead k
ioReturn  a   = Ap $ ApReturn a
ioWrite   s k = Ap $ ApWrite s k
ioWriteLn s   = ioWrite (s ++ "\n")

apTest =
  ioWriteLn "Hello world!" $
  ioRead $ \i ->
  ioWriteLn ("You wrote [" ++ i ++ "]") $
  ioReturn 10

uiRun ap =
  case runAp ap of
    ApRead k     -> uiRun (k "Some input")
    ApReturn a   -> return a
    ApWrite s k  -> putStr s >> uiRun k

run = uiRun apTest

It works OK however I would like to write the "application" apTest using a monad
instead of using $. In other words like this:
apTest = do
  ioWriteLn "Hello world!"
  i <- ioRead
  ioWriteLn $ "You wrote [" ++ i ++ "]"
  return 10

The problem is that the code is resisting all my attempts to turn the "function style" DSL into a monad. So the question is how to implement a monad instance for this DSL that allows you to write apTest monad style instead of "$" style?

A: Is my thing a monad?
I don't have any specific help for you, but I have a bit of general guidance that is way too long for a comment. When my intuition tells me I want to make something an instance of Monad, the first thing I do is sit down with a pen and a piece of paper and I ask myself,

Is my thing really a monad, though?

As it turns out, a lot of times it isn't – it was just my intuition wanting to jump on the bandwagon a bit too quickly. You can't very well create a Monad instance for your thing if your thing isn't a monad. Here's my checklist of three things that need to be covered before I call my thing a monad.
When I have decided that my thing is a monad, I have usually also in the process accidentally come up with everything I need to create a monad instance for my thing, so this is not a useless exercise in rigor. This actually will give you the implementations of the two operations you need to create a monad instance for your thing.
What are monads?
For your thing to be a monad, it needs to have two operations. These are commonly, in the Haskell world, referred to as return and (>>=) (pronounced "bind".) A monad can be seen as a computation with a "context" of some kind. In the case of IO, the context is side effects. In the case of Maybe, the context is failure to provide a value, and so on. So a monad is something that has a value, but there's something more than just the value. This something more is often referred to as a "context" for lack of a better word.
Operations
Anyway, the signatures involved are
return :: Monad m => a -> m a
(>>=) :: Monad m => m a -> (a -> m b) -> m b

This means that return takes any old value a and puts it into the context of your monad somehow. This is often a fairly easy function to implement (there aren't too many ways you can put any a value into a context.)
What's interesting is (>>=). It takes a value a inside your monad context and a function from any value a to a new value b but inside your monad context. It then returns the b value with context. You need to have a sensible implementation of this before you even consider making a Monad instance for your thing. Without (>>=), your thing is definitely not a monad.
Laws
However, it isn't enough to have return and (>>=)! I said the implementation needs to be sensible. This also means that your thing must have implementations of return and (>>=) that obey the monad laws. They are as follows:

*

*return a >>= f should be the same thing as f a

*m >>= return should be the same thing as just m

*(m >>= f) >>= g should be the same thing as m >>= (\x -> f x >>= g)
These make a lot of sense* (the first two are trivial and the third one is just an associativity law), and we need all monads to obey them. This is not checked by the compiler (but it might assume they will hold) so it is your responsibility to make sure they hold.
If your monad-to-be obeys these laws, you get a monad! Congratulations! The rest is just paperwork, i.e. defining the instance as
instance Monad MyThing where
  return a = {- definition -}
  m >>= f  = {- definition -}

and then you are ready to use do syntax as well!

* More information on the Haskell wiki page on monad laws.

A: I think this is what you were aiming for.  The only change I made was to condense Ap and ApStep into a single type.
data Ap a =
    ApRead   (String -> Ap a)
  | ApWrite  String (Ap a)
  | ApReturn a

instance Monad Ap where
    return = ApReturn
    m >>= f = case m of
        ApRead      k  -> ApRead  (\x -> k x >>= f)
        ApWrite str m' -> ApWrite str (m' >>= f)
        ApReturn    r  -> f r

ioWriteLn :: String -> Ap ()
ioWriteLn str = ApWrite str (ApReturn ())

ioRead :: Ap String
ioRead = ApRead ApReturn

apTest :: Ap Int
apTest = do
    ioWriteLn "Hello world!"
    i <- ioRead
    ioWriteLn ("You wrote [" ++ i ++ "]")
    return 10

Although written in monadic style using do notation, apTest is identical to the following hand-written chain of constructors:
apTest :: Ap Int
apTest =
    ApWrite "Hello, world!"             $
    ApRead                              $ \i ->
    ApWrite ("You wrote [" ++ i ++ "]") $
    ApReturn 10

This is a special case of a free monad, so you can simplify your code dramatically by just writing:
{-# LANGUAGE DeriveFunctor #-}

import Control.Monad.Free

data ApF next = Read (String -> next) | Write String next deriving (Functor)

type Ap = Free ApF

ioWriteLn :: String -> Ap ()
ioWriteLn str = liftF (Write str ())

ioRead :: Ap String
ioRead = liftF (Read id)

To learn more about free monads, you can read my post on free monads, which goes into more detail about how you convert DSLs to free monads and builds an intuition for how they work.

A: Sure it's a monad.  In fact it would be simpler to express it as a free monad [1] but we can work with what you've got.
Here's how we know it's a monad: if you have a type data Foo a = ... where Foo represents some sort of recursive tree structure where as only occur at the leaves then you have a monad.  return a is "give me a tree consisting of one leaf labelled by a", and >>= is "substitution at the leaves".
In your case Ap is a tree structure where

*

*ApReturn a is a leaf

*there are two sorts of interior nodes

*

*ApRead is a node which has no label and has one descendant coming off it for every value of type String

*ApWrite is a node which is labelled by a String and has only one descendant coming off it

I've added the monad instance to your code below.  return is just AppReturn (plus the Ap wrapper).  >>= is just recursively applying >>= and substituting at the leaves.
A couple of hints for the future

*

*Put type signatures on everything top-level.  Your colleagues, Stack Overflow commenters and your future self with thank you.

*The Ap wrapper was unnecessary.  Consider removing it.

Enjoy!
data Ap a = Ap { runAp :: ApStep a }

data ApStep a =
    ApRead      (String -> Ap a)
    |   ApReturn    a
    |   ApWrite     String (Ap a)

ioRead    k   = Ap $ ApRead k
ioReturn  a   = Ap $ ApReturn a
ioWrite   s k = Ap $ ApWrite s k
ioWriteLn s   = ioWrite (s ++ "\n")

apTest =
  ioWriteLn "Hello world!" $
  ioRead $ \i ->
  ioWriteLn ("You wrote [" ++ i ++ "]") $
  ioReturn 10

uiRun ap =
  case runAp ap of
    ApRead k        -> uiRun (k "Some input")
    ApReturn a      -> return a
    ApWrite s k     -> putStr s >> uiRun k

run = uiRun apTest

instance Monad Ap where
    return = Ap . ApReturn
    Ap (ApReturn a) >>= f = f a
    Ap (ApRead r) >>= f = Ap (ApRead (\s -> r s >>= f))
    Ap (ApWrite s a) >>= f = Ap (ApWrite s (a >>= f))

monadRead = Ap (ApRead (\s -> return s))
monadWrite s = Ap (ApWrite s (return ()))
monadWriteLn = monadWrite . (++ "\n")

apTestMonad = do
  monadWriteLn "Hello world!"
  i <- monadRead
  monadWriteLn $ "You wrote [" ++ i ++ "]"
  return 10

monadRun = uiRun apTestMonad

[1] http://www.haskellforall.com/2012/06/you-could-have-invented-free-monads.html


text:
Q: How can I plot all columns of data frame as linear regression in a single subplot? I am able to do so by following code but it is not subplot it is by loop:
for col in data.columns:
  sns.lmplot(x=col, y='Amount', hue='Class', data=data, line_kws={"color": "red"})
  plt.show()

Output:

But, when I use this below code for subplot which I generally do it plot only one plot:
plt.gcf().set_size_inches(0.75, 0.5)

plt.subplot(6,5,1enter code here)
sns.lmplot(x='V1', y='Amount', hue='Class', data=data, line_kws={"color": "red"})

plt.subplot(6,5,2)
sns.lmplot(x='V2', y='Amount', hue='Class', data=data, line_kws={"color": "red"})

plt.subplot(6,5,3)
sns.lmplot(x='V3', y='Amount', hue='Class', data=data, line_kws={"color": "red"})

plt.subplot(6,5,4)
sns.lmplot(x='V4', y='Amount', hue='Class', data=data, line_kws={"color": "red"})
......
......

plt.subplot(6,5,30)
sns.lmplot(x='Amount', y='Amount', hue='Class', data=data, line_kws={"color": "red"})

plt.suptitle("Features VS Amount (Class wise)", fontsize=20)
plt.show()

Output: