text:
Q: Why can't the AD be located at the top of the screen in android Tabbed activity? I create a tabbed activity, and I have set the AD named android:id="@+id/adView" located at the top of screen using android:layout_alignParentTop="true".
After I run the app, I find the four tabs are located at the top of the screen. How can I make the AD located at the above of Tab? Thanks!
Current

I hope

activity_main.xml
<RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <com.google.android.gms.ads.AdView
        xmlns:ads="http://schemas.android.com/apk/res-auto"
        android:id="@+id/adView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        ads:adSize="SMART_BANNER"
        android:layout_alignParentTop="true"
        ads:adUnitId="@string/ad_unit_id" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="fill_parent"
        android:layout_below="@+id/adView"
        android:layout_above="@+id/linearLayout1"
        android:paddingTop="12dip"
        android:paddingLeft="7dip"
        android:paddingRight="7dip"
        android:orientation="vertical" >

        <android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
            xmlns:tools="http://schemas.android.com/tools" android:id="@+id/pager"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            tools:context=".MainActivity" />

    </LinearLayout>

    <LinearLayout
        android:id="@+id/linearLayout1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:gravity="center"
        android:orientation="horizontal"
        android:layout_alignParentBottom="true"
        android:weightSum="4" >

        <Button
            android:id="@+id/btnClose"
            android:layout_width="0dip"
            android:layout_height="fill_parent"
            android:layout_gravity="center"
            android:layout_weight="1"
            android:text="Close" />
    </LinearLayout>

</RelativeLayout>

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

    <TextView android:id="@+id/section_label1" android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="New Button"
        android:id="@+id/button"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

MainActivity.java
public class MainActivity extends ActionBarActivity implements ActionBar.TabListener {

    SectionsPagerAdapter mSectionsPagerAdapter;
    ViewPager mViewPager;

    private AdView adView;

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

        adView=(AdView) findViewById(R.id.adView);
        SetAD(adView);

        // Set up the action bar.
        final ActionBar actionBar = getSupportActionBar();
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Create the adapter that will return a fragment for each of the three
        // primary sections of the activity.
        mSectionsPagerAdapter = new SectionsPagerAdapter(getSupportFragmentManager());

        // Set up the ViewPager with the sections adapter.
        mViewPager = (ViewPager) findViewById(R.id.pager);
        mViewPager.setAdapter(mSectionsPagerAdapter);

        // When swiping between different sections, select the corresponding
        // tab. We can also use ActionBar.Tab#select() to do this if we have
        // a reference to the Tab.
        mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageSelected(int position) {
                actionBar.setSelectedNavigationItem(position);
            }
        });

        // For each of the sections in the app, add a tab to the action bar.
        for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {
            // Create a tab with text corresponding to the page title defined by
            // the adapter. Also specify this Activity object, which implements
            // the TabListener interface, as the callback (listener) for when
            // this tab is selected.
            actionBar.addTab(
                    actionBar.newTab()
                            .setText(mSectionsPagerAdapter.getPageTitle(i))
                            .setTabListener(this));
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    public  void SetAD(AdView adView) {
        if (true) {
            AdRequest adRequest = new AdRequest.Builder()
                    .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
                    .build();
            adView.loadAd(adRequest);
        }else{
            adView.setVisibility(View.GONE);
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onTabSelected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
        // When the given tab is selected, switch to the corresponding page in
        // the ViewPager.
        mViewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    @Override
    public void onTabReselected(ActionBar.Tab tab, FragmentTransaction fragmentTransaction) {
    }

    public class SectionsPagerAdapter extends FragmentPagerAdapter {

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

        @Override
        public Fragment getItem(int position) {
            // getItem is called to instantiate the fragment for the given page.
            // Return a PlaceholderFragment (defined as a static inner class below).
            //return PlaceholderFragment.newInstance(position + 1);

            Fragment fragment;
            switch(position){
                case 0:
                    fragment = new PlaceholderFragment();
                    break;
                case 1:
                    fragment = new PlaceholderFragment1();
                    break;
                case 2:
                    fragment = new PlaceholderFragment1();
                    break;
                case 3:
                    fragment = new PlaceholderFragment();
                    break;
                default:
                    throw new IllegalArgumentException("Invalid section number");
            }

            //set args if necessary
            Bundle args = new Bundle();
            args.putInt(PlaceholderFragment.ARG_SECTION_NUMBER, position + 1);
            fragment.setArguments(args);

            return fragment;

        }

        @Override
        public int getCount() {
            // Show 3 total pages.
            return 4;
        }

        @Override
        public CharSequence getPageTitle(int position) {
            Locale l = Locale.getDefault();
            switch (position) {
                case 0:
                    return getString(R.string.title_section1).toUpperCase(l);
                case 1:
                    return getString(R.string.title_section2).toUpperCase(l);
                case 2:
                    return getString(R.string.title_section3).toUpperCase(l);
                case 3:
                    return getString(R.string.title_section4).toUpperCase(l);
            }
            return null;
        }
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number1";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment newInstance(int sectionNumber) {
            PlaceholderFragment fragment = new PlaceholderFragment();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main, container, false);

            return rootView;
        }
    }

    /**
     * A placeholder fragment containing a simple view.
     */
    public static class PlaceholderFragment1 extends Fragment {
        /**
         * The fragment argument representing the section number for this
         * fragment.
         */
        private static final String ARG_SECTION_NUMBER = "section_number";

        /**
         * Returns a new instance of this fragment for the given section
         * number.
         */
        public static PlaceholderFragment1 newInstance(int sectionNumber) {
            PlaceholderFragment1 fragment = new PlaceholderFragment1();
            Bundle args = new Bundle();
            args.putInt(ARG_SECTION_NUMBER, sectionNumber);
            fragment.setArguments(args);
            return fragment;
        }

        public PlaceholderFragment1() {
        }

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_main1, container, false);

            Button cw= (Button)rootView.findViewById(R.id.buttonAA);

            final LayoutInflater my=inflater;
            cw.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                     Toast.makeText(my.getContext(), "CW", Toast.LENGTH_SHORT).show();
                }
            });

            return rootView;
        }
    }

}

A: The reason is that your layout is inside an ActionbarActivity and when you set your layout it will always within the action bar (in you case the titlebar and tabs).
To achieve what you want create your own custom titlebar and tabs.

A: Solution-1:
If you want to align Tabbar at top of the screen and get rid of ActionBar, You can try this:
<style name="MyTheme" parent="android:Theme.Holo.Light">
     <item name="android:windowActionBar">false</item>
     <item name="android:windowNoTitle">true</item>
</style>

Add these both items in your styles.xml under res/values folder to remove actionbar from Activity.
Also you have to set theme for this activity in manifest like below:
 <activity
        android:name=".MainActivity"
        android:theme="@style/MyTheme" />

Solution-2:
Consider using ToolBar , that way you can easily position your tabs in layout. here is link to use Toolbar

A: Your ActionBar seems doesn't has any menu item. So it's possible to hide the ActionBar and place the ad on top of the Tab. In your MainActivity, call:
...
setContentView(R.layout.activity_main);
getSupportActionBar().hide();

And your layout for activity_main should look like this:
<RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:ads="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        ads:adSize="SMART_BANNER"
        android:layout_alignParentTop="true"
        ads:adUnitId="@string/ad_unit_id" />

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/adView"/>

</RelativeLayout>

Consider using Toolbar, and you will found a better way. And if you are using Toolbar, your layout should look like this:
<RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
        android:layout_alignParentTop="true" />

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:adSize="SMART_BANNER"
        app:adUnitId="@string/ad_unit_id"
        android:layout_below="@+id/toolbar" />

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@+id/adView"/>

</RelativeLayout>

A: You have to create and manage a layout for the tabs, so you're free to place it where needed: if you use actionbar's tabs, they will be placed under the AB. See for example this solution. I believe it is under the sdk samples folder.

A: You need custom tab layout. For example you can use ready-to-use solution ViewPagerIndicator.
Your main layout will be like this:
<RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

    <com.google.android.gms.ads.AdView
        android:id="@+id/adView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:adSize="SMART_BANNER"
        app:adUnitId="@string/ad_unit_id"
        android:layout_alignParentTop="true" />

    <com.viewpagerindicator.TabPageIndicator
        android:id="@+id/page_indicator"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@id/adView" />

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_below="@id/page_indicator"/>

</RelativeLayout>

Bind indicator to your ViewPager
//Set the pager with an adapter
ViewPager pager = (ViewPager)findViewById(R.id.pager);
pager.setAdapter(new TestAdapter(getSupportFragmentManager()));

//Bind the title indicator to the adapter
TabPageIndicator tabIndicator = (TabPageIndicator)findViewById(R.id.page_indicator);
tabIndicator.setViewPager(pager);


text:
Q: Public ip socket networking I have a server object and client object that can connect and communicate with each other.
The client connects using the servers private IP address.
But I would like to be able to use public IP addresses to be able to communicate over the internet.
I get the public ip address using a url www.whatsmyip.com as a url.
I paste this public ip address where needed, but the client is unable to seemingly find the server using the public IP address

A: It doesn't have anything to do with code, as long as the server is binding to INADDR_ANY. It has to do with correct port forwarding at the server-side firewall.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Supremum and infimum of S Let $$S=\left \lbrace \frac{n}{n+1} : n \in \mathbb{N} \right \rbrace.$$
With this said, I need to determine, with a proof, the supremum and infimum of $S$.
Please show all work and why.

A: The question is easy, can't post an image as of yet. I arranged the set into a strictly monotonically increasing sequence (that is 1/2, 2/3, 3/4,...and so on). Infimum is then, the first term itself, 1/2 (however if you include 0 in N, then infimum is 0). Since the sequence is monotonically increasing, showing that an upper bound exists (any number larger than 1 will do) is enough to show supremum exists and you can take limit of the terms n/(n+1), as n increases n/(n+1) tends to reach 1 and so supS is 1. Do avoid asking to show all the work. Also note that supS does not belong to S.

A: The way I might approach this problem would be:  1). Show that the sequence is strictly increasing.  2). Show that the limit of $\{s_n\}$ is 1
Invoke the Monotone Convergence Theorem and properties of increasing sequences and you should be able to find the apparent $\inf$ and $\sup$.

A: For the infimum, note that $n^2+2n+1>n^2+2n \implies(n+1)(n+1)>n(n+2)\implies\frac{n+1}{n+2}>\frac{n}{n+1}$, so each term is greater than the last. Therefore the infimum is the first term, as $\frac{1}{2}<\frac{n}{n+1}\forall n \in\mathbb{N}:n>1.$ For the supremum, due to the increasing nature of the sequence, there is no greatest term. Then any supremum will be a limit point of the series. It is obvious that $1$ is a limit point of the sequence. There cannot be a lesser limit point, as for any $\epsilon>0$ you can find a term $p$ such that $d(1,p)<\epsilon$. Specifically, $d(1,p)=1-p=1-\frac{n}{n+1}=\frac{1}{n+1}>\epsilon$ for any $n>\frac{1}{\epsilon}-1$. Therefore $\inf S=\frac{1}{2}$ and $\sup S=1.$
For future reference, we have a few guidelines we tend to follow here to allow for better and clearer answers and more help for all. You should always give it a go yourself first, and then tell us what you've gotten so far. Even if you haven't gotten anything, just say so, that you have no clue how to advance, maybe just go through a couple check where some basic step take you; as long as you show you've at least tried and aren't just asking us to do a homework problem for you.


text:
Q: Can I handle back button within methods in vuejs 2? I need some help in vuejs 2. I want to detect back button pressed event. I did some research and found this,
document.addEventListener("backbutton", yourCallBackFunction, false");

I think it is global event. I need something local, within a method. where i can use some logic.
methods: {
    backButtonPressed() {
    }
}

Or can i bind the global one to local function? Can anyone help me with that? TIA

A: Is easy, if you need to catch that behavior only your component, you can use beforeRouteLeave function in the root of your component.
Example:
beforeRouteLeave (to, from, next) {
 const answer = window.confirm('Do you really want to leave?)
   if (answer) {
      next()
   } else {
      next(false)
   }
 }

But if you need to add this behavior globally, you need catch with beforeEnter in the routes.

A: Add the event on your mounted method on your root Vue component (the one the Vue instance is tied to.
var app = new Vue({
  el: '#app',
  data: {
    message: 'Hello Vue!'
  },
  methods: {
    yourCallBackFunction () {
      // Your logic
    }
  }
  mounted () {
    document.addEventListener("backbutton", this.yourCallBackFunction, false);
  },
  beforeDestroy () {
    document.removeEventListener("backbutton", this.yourCallBackFunction);
  }
})

We also remove it on beforeDestroy to keep things tidy.
Note: I've not personally used the back button event so have added it to this example only because you say it's working but need a way to globally handle it. This code will do just that.
Note: As per @Luke's comment - we add the listener in the mounted event so it doesn't execute for in the SSR context. If SSR isn't a factor / consideration then we can use the created lifecycle hook.

A: If you are using vue-router(no idea if you don't, why...) a good solution is to use in your component:
  beforeRouteLeave(to, from, next) {
 if (from.name === 'nameOfFromRoute' && to.name === 'nameOfToRoute' ) {
   next(false);
 } else {
   next();
 }
 console.log({ to, from });

},

A: This was one variation I found to work as well, a little less verbose and uses router.push in the beforeDestroy lifecycle method

*

*Listen for popstate

*Push the desired name/path to redirect

The code below would be a better understanding.
beforeDestroy() {
  window.addEventListener("popstate", (event) => {
    this.$router.push({ path: <your path> });
  });
},

This implementation was on Nuxt 2.14.6 and works just as well with all versions of Vue.

A: If still someone come across this issue.
A solution for an event listener for browser-back is https://developer.mozilla.org/de/docs/Web/API/WindowEventHandlers/onpopstate

window.onpopstate = function() {
  alert('browser-back');
};

A: I have a similar problem and solved using @click="backFunction"
and created the function on methods like this:
methods: {
backFunction(){
//yourlogic
},


text:
Q: Copy group of folders with Applescript I have been working on this project for my job, which involves backing up selected information from a computer to one of our servers. So far I have posted a couple of questions and gotten a lot of valuable help, so thanks everyone for that! The current bug that I have hit is when attempting to duplicate a selection involving multiple errors. If I try and duplicate one folder it works just fine, but multiple just isn't quite working. The code is below
display dialog "Please enter your augnet username" default answer "username"
set username to (text returned of result)

set server to "smb://orgs.augsburg.edu"

try
    mount volume server
on error
    display dialog "Either you are already connected, or there was a problem reaching the server. Please disconnect and try again."
end try

delay 3

tell application "Finder"
    set backup to make new folder at folder "ORGS:Information Technology:www:kb_images:Migration Testing:" with properties {name:username}
end tell

set theSelection to choose folder with prompt "Please select what you would like to transfer" with multiple selections allowed

tell application "Finder" to duplicate folder theSelection to backup

Any help any of you can give me involving a selection with multiple folders is very much appreciated!

A: The choose folder  … with multiple selections allowed command will return a list of alias objects pointing to folders (unless canceled, of course). Just iterate over that list with a repeat loop:
set selectedFolders to choose folder with prompt "Yadda" with multiple selections allowed
repeat with selectedFolder in selectedFolders
    -- do something with the folder
end repeat

Generally speaking, when in doubt what a command returns, just execute it and look at the output in the AppleScript Editor result window. In your case, it would look something like this:

– which tells you all you need to know: the returned data is a list (it's enclosed in braces, { and }) and contains alias objects denoted by their HFS path. As to basics like looping, the Applescript Language Guide (reachable through AppleScript Editor's help menu) has all the details you need.
Finally, I'd recommend using System Events instead of Finder for the copy operation, as it is faster and operates in the background.


text:
Q: A general equation for Pythagorean triples of rational numbers This question was asked by a friend of mine and I have no idea how to proceed. I am looking for a general solution for the equation $p^2+q^2=r^2$ where $p,q,r$ are rational numbers.
PS: I am not looking for such trivial solutions which can be constructed by Pythagorean triples, e.g., $\frac{6^2}{15^2}+\frac{8^2}{15^2}=\frac{2^2}{3^2}$

A: There are no other rational solutions than those based on the Pythagorian triples.
If $$p^2 +q^2 =r^2,$$ or $$\left(\frac{P'}{P''}\right)^2+\left(\frac{Q'}{Q''}\right)^2=\left(\frac{R'}{R''}\right)^2,$$ multiplying by the common denominator gives an equation in integers $$\left(P'Q''R''\right)^2+\left(P''Q'R''\right)^2=\left(P''Q''R'\right)^2.$$

A: Theorem. If $p, q > 0$ are (rational) integers such that
$$x := p^{2} - q^{2},$$
$$y := 2pq,$$
$$z := p^{2} + q^{2},$$
$$p+q \equiv 1\ \ (mod\ \ 2),$$
$$p > q,$$
$$(p, q) = 1,$$
then the triple
$(x, y, z)$
is a solution of the Diophantine equation
$x^{2} + y^{2} = z^{2}.$
In other words, the triples $(x, y, z)$ so generated are primitive (in the sense that $(x, y, z) = 1$) solutions of the equation $x^{2} + y^{2} = z^{2}$.
Indeed, one can find this theorem or its equivalents in many elementary number theory texts. For instance, the famous number theory book of Hardy and Wright.

A: In General formula generic for Pythagorean triples looks a little different.
$$x^2+y^2=az^2$$
If the number can be represented as a sum of squares.  $a=t^2+k^2$
The solution has the form:
$$x=-tp^2+2kps+ts^2$$
$$y=kp^2+2tps-ks^2$$
$$z=p^2+s^2$$
All numbers can be any character.


text:
Q: Nested struct keys exploded into column values Within the JSON objects I am attempting to process, I am being given a nested StructType where each key represents a specific location, which then contains a currency and price:
-- id: string (nullable = true)
-- pricingByCountry: struct (nullable = true)
   |-- regionPrices: struct (nullable = true)
   |-- AT: struct (nullable = true)
       |-- currency: string (nullable = true)
       |-- price: double (nullable = true)
   |-- BT: struct (nullable = true)
       |-- currency: string (nullable = true)
       |-- price: double (nullable = true)
   |-- CL: struct (nullable = true)
       |-- currency: string (nullable = true)
       |-- price: double (nullable = true)
...etc.

and I'd like to explode it so that rather than having a column per country, I can have a row for each country:
+---+--------+---------+------+
| id| country| currency| price|
+---+--------+---------+------+
|  0|      AT|      EUR|   100|
|  0|      BT|      NGU|   400|
|  0|      CL|      PES|   200|
+---+--------+---------+------+

These solution make sense intuitively: Spark DataFrame exploding a map with the key as a member and Spark scala - Nested StructType conversion to Map, but unfortunately don't work because I'm passing in a column and not a whole row to be mapped. I don't want to manually map the whole row--just a specific column that contains nested structs. There are several other attributes at the same level as "id" that I'd like to maintain in the structure.

A: I think it can done as below:
// JSON test data
val ds = Seq("""{"id":"abcd","pricingByCountry":{"regionPrices":{"AT":{"currency":"EUR","price":100.00},"BT":{"currency":"NGE","price":200.00},"CL":{"currency":"PES","price":300.00}}}}""").toDS

val df = spark.read.json(ds)

// Schema to map udf output
val outputSchema = ArrayType(StructType(Seq(
  StructField("country", StringType, false),
  StructField("currency", StringType, false),
  StructField("price", DoubleType, false)
)))

// UDF takes value of `regionPrices` json string and converts
// it to Array of tuple(country, currency, price)
import org.apache.spark.sql._
val toMap = udf((jsonString: String) => {
  import com.fasterxml.jackson.databind._
  import com.fasterxml.jackson.module.scala.DefaultScalaModule

  val jsonMapper = new ObjectMapper()
  jsonMapper.registerModule(DefaultScalaModule)

  val jsonMap = jsonMapper.readValue(jsonString, classOf[Map[String, Map[String, Double]]])
  jsonMap.map(f => (f._1, f._2("currency"), f._2("price"))).toSeq

}, outputSchema)

val result = df.
              select(col("id").as("id"), explode(toMap(to_json(col("pricingByCountry.regionPrices")))).as("temp")).
              select(col("id"), col("temp.country").as("country"), col("temp.currency").as("currency"), col("temp.price").as("price"))

Output will be:
scala> result.show
+----+-------+--------+-----+
|  id|country|currency|price|
+----+-------+--------+-----+
|abcd|     AT|     EUR|100.0|
|abcd|     BT|     NGE|200.0|
|abcd|     CL|     PES|300.0|
+----+-------+--------+-----+


text:
Q: Musician goes into Cryogenic suspension About 15 years ago, I read a book about a classical musician whos wife (possible girlfriend) dies and he turns to writing commercial jingles (which he feels is selling his soul, but is well-paid) to pay for cryogenic suspension until the end of the universe. The premise is that the big bang started expansion, but as the universe contracts, time would go backward and he would be reunited with his wife.
He is woken up in the future and agrees to work for a government or corporation. One of these jobs sees him visit a planet where small conical creatures live, similar size to dogs. The technology allows his thoughts to be placed in to new bodies, and he goes to see the planet, but the small creatures keep attacking and killing him. He keeps going through this cycle, because he told the ships computer not to tell him if anything bad happens to him.
Anybody got any idea of this books title?

A: Possibly Tomorrow and Tomorrow by Charles Sheffield. I also read it back in the late 90s
From Wikipedia:

"Originally, Drake is a professional musician, with minor celebrity.
  When his wife Ana is diagnosed with an unspecified incurable brain
  disorder, Drake exhausts every option attempting to cure her. Only
  then does he decide to have her body cryogenically stored, in the
  hopes future generations will discover effective treatment. However,
  Drake is extremely cautious, and in case the future culture doesn't
  care about her plight, he has himself frozen as well. Furthermore he
  devotes all his energies for a decade prior to his freezing, in
  becoming an expert primary source on the musically notable people of
  his era...
  Drake is continuously laid dormant and revived, exponentially further
  into the future. Human civilization alters radically over the eons,
  but Ana's mangled brain proves an extremely difficult problem. Despite
  the incomprehensible changes surrounding in each successive awakening,
  Drake never loses sight of his mission.


text:
Q: "Have it to say" meaning
... and I should never have it to say that my mother was willing
  when my father was not.

This sentence is from Robinson Crusoe. Does "I should never have it to say" mean "I have never had the possibility to say it" or something else?

A: Context helps here.  Robbie wants to see the world.  His father wants him to stay at home.  Robbie is determined to go to sea, but he doesn't want to cross his father, so he asks his mother to intervene on behalf of his plans.  Robbie reports that his mother refuses, listing the reasons that his father reasonably opposes the plans to travel.  At the end of this litany, his mother says that she's in agreement with his father and that Robbie

should never have it to say that my mother was willing when my father was not.

That is, Robbie will never be able to say that his parents were of differing minds, that his mother supported his wayfaring plans in the face of his father's refusal to do so.


text:
Q: When merging PDF documents using iText, the image fields are missing I had a PDF document and needed to add a couple of image fields. I imported the pdf file into Adobe LiveCycle as artwork. I then added my 2 images and saved as a static file. When I view the file using Adobe Reader, I can see the images. But when I try to merge the file with other static and dynamic pdf files created using LiveCycle, the images are missing.
I looked at the following thread
Images (imageField) are not shown after iText PDF Merging
but after checking the solution shown there against my code, I am already using PdfCopy instead of PdfWriter:
        ByteArrayOutputStream output = new ByteArrayOutputStream();

        PdfReader reader = new PdfReader(baosList.get(0).toByteArray());
        Document document = new Document(reader.getPageSizeWithRotation(1));
        reader.close();

        PdfCopy writer = new PdfCopy(document, output);
        document.open();

        for (ByteArrayOutputStream baos : baosList)
        {
            // copy content
            reader = new PdfReader(baos.toByteArray());

            for (int idx = 1; idx <= reader.getNumberOfPages(); idx++)
                writer.addPage(writer.getImportedPage(reader, idx));

            reader.close();
            baos.close();
        }

I have other dynamic PDF files with images that are fine. I wonder if my problem is because I imported the original file as artwork.


text:
Q: WordPress featured post and sharethis issue im having some trouble with this featured post function that I made. the issue that im having is that when query('showposts=1'); is set the featured post is not picked up. however when I put query(''); the sharethis plugin doesn't work. can any one please help me on what I might be doing wrong.

            <?php
            $featured = new WP_Query();
            $featured->query('showposts=1');
            while($featured->have_posts()) : $featured->the_post();

            //$wp_query->in_the_loop = true; // This line is added so that the_tags('') will work outside the regular loop.
            $featured_ID = $post->ID; // We'll store this here so that we know to skip this post in the main loop
            ?>

                <?php if(get_post_meta($post -> ID, 'feature', true)) { ?>

                    <?php if (get_post_meta($post->ID, 'large_preview', true)) { ?>

                        <img src="<?php echo get_post_meta($post->ID,'large_preview',true);?>" width=150px; height=150px alt="Featured Post"/>

                    <?php } ?>

<a href="<?php the_permalink();?>" title="<?php the_title(); ?>"><?php the_title(); ?>

                        on <?php the_time('M d'); ?> in <?php the_category(',');?> tagged <?php the_tags(''); ?>
                        <?php the_excerpt();?>

                        <a href="<?php the_permalink(); ?>" class="readMore">Read More

                <?php } ?>
            <?php endwhile; ?>

A: showposts is been deprecated since version 2.1, so it might be better to use posts_per_page instead. Not sure if it will make any difference, but you could also replace the first two lines of PHP with $featured = new WP_Query('showposts=1');
As to what is causing the problem I am not sure, your query looks fine to me and you didn't mention in what way Share This failed. I'm not familiar with the Share This plugin, but most such plugins add its content to the post using a filter function attached to the the_content filter. That said, it might just be that you are using the_excerpt() and not the_content().


text:
Q: Does Kotlin has a scope delimiter? In C one can use { and } as a scope delimiter.
For example:
int myfunc()
{
    int i = 4;

    {
        int j = 5;
        i = i + j;
        ...
    }
    ...
}

In this example the { and } create a new scope and so the j can't be seen outside of the { and }.
Does Kotlin supports this?

A: It doesn't, because this syntax creates a lambda expression (which then isn't assigned to anything, and is never called).
So this code does nothing to the initial value of i:
var i = 0
{
    i++
}
println(i) // 0

You can however assign the lambda to a variable and call it:
var i = 0
val f: () -> Int = {
    i++
}
f()
println(i) // 1

Or invoke it immediately in a JavaScript-ish style, which might be frowned upon by some people:
var i = 0
{
    i++
}()
println(i) // 1

A: Adding to @zsmb13's answer, you may look into scoping functions (Standard.kt). The idiomatic way of creating a scope in Kotlin would be:
var i = 0
run {
  i++
}
println(i)


text:
Q: Accessing data outside of a promise I am using fetch and a promise to make 2 calls to api's and return the data. I have no problem getting the data within the promise I just can't access it outside of it. I would have thought return apiData would return it for use? I imagine I'm missing something like a .finalise or .success to return it outside the promise?
Essentially I'm trying to figure out how I can access the JSON object outside the promise which includes all the data, not just the JSON structure.
var api1 = fetch('api.example1.com/search').then(function(response){
         return response.json()
});
var api2 = fetch('api.example2.com/search').then(function(response){
         return response.json()
});

var apiData = {"api1":{},"api2":{}};
Promise.all([api1,api2]).then(function(values){
    apiData.api1 = values[0];
    apiData.api2 = values[1];
    console.log(JSON.stringify(apiData, null, 4));
    //this displays all the data as it's still within the promise
    return apiData;
});
console.log(JSON.stringify(apiData, null, 4));
    //this doesn't get the values of the api1 and api2 data as it's outside of the
    //promise and only displays the object structure

A: You can always access apiData globally. Just make sure you access it after data is assigned. The reason you don't get the data because you call console.log before the promise return.
Try this:
var apiData = {"api1":{},"api2":{}};
Promise.all([api1,api2]).then(function(values){
        apiData.api1 = values[0];
        apiData.api2 = values[1];
        console.log(JSON.stringify(apiData, null, 4));
        //this displays all the data as it's still within the promise
        return apiData;
    })
    .then(function(){
        console.log(JSON.stringify(apiData, null, 4)); // You still reference apiData globally
            //this doesn't get the values of the api1 and api2 data as it's outside of the
            //promise and only displays the object structure
    });

Or even this (only for demonstration, don't use it):
var apiData = {"api1":{},"api2":{}};
Promise.all([api1,api2]).then(function(values){
    apiData.api1 = values[0];
    apiData.api2 = values[1];
    console.log(JSON.stringify(apiData, null, 4));
    //this displays all the data as it's still within the promise
    return apiData;
});
setTimeout(function(){
    console.log(JSON.stringify(apiData, null, 4)); // should be now able to log the data here
        //this doesn't get the values of the api1 and api2 data as it's outside of the
        //promise and only displays the object structure
}, 1000); // assume the fetch calls finish in 1s


text:
Q: Making tree diagram fit multiple per row I have the following code:
\documentclass[10pt]{article}
\usepackage{fullpage,amsmath,amssymb,amsfonts,nicefrac, amsthm,calc}
\usepackage{caption}
\usepackage{listings}
\usepackage{qtree}

\begin{document}
\pagenumbering{gobble}

\newpage
\begin{enumerate}
\item
{\centering
\begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|}
\hline
$8$ & $11$ & $9$ & $6$ & $7$ & $2$ & $4$ & $5$ & $10$ & $1$ & $3$ \\
\hline
\end{tabular}

\Tree[.8 [.11 [.6 [.5 ] [.10 ]] [.7 [.1 ] [.3 ]]]
               [.9   [.2 ] [.4 ]]]
}

\medskip
\medskip
\medskip
\medskip
\medskip

{\centering
\begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|}
\hline
$8$ & $11$ & $9$ & $6$ & $1$ & $2$ & $4$ & $5$ & $10$ & $7$ & $3$ \\
\hline
\end{tabular}

\Tree[.8 [.11 [.6 [.5 ] [.10 ]] [.1 [.7 ] [.3 ]]]
               [.9   [.2 ] [.4 ]]]
}

\medskip
\medskip
\medskip
\medskip
\medskip

{\centering
\begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|}
\hline
$8$ & $11$ & $9$ & $5$ & $1$ & $2$ & $4$ & $6$ & $10$ & $7$ & $3$ \\
\hline
\end{tabular}

\Tree[.8 [.11 [.5 [.6 ] [.10 ]] [.1 [.7 ] [.3 ]]]
               [.9   [.2 ] [.4 ]]]
}

\medskip
\medskip
\medskip
\medskip
\medskip

{\centering
\begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|}
\hline
$8$ & $11$ & $2$ & $5$ & $1$ & $9$ & $4$ & $6$ & $10$ & $7$ & $3$ \\
\hline
\end{tabular}

\Tree[.8 [.11 [.5 [.6 ] [.10 ]] [.1 [.7 ] [.3 ]]]
               [.2   [.9 ] [.4 ]]]
}

\medskip
\medskip
\medskip
\medskip
\medskip

{\centering
\begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|}
\hline
$8$ & $1$ & $2$ & $5$ & $3$ & $9$ & $4$ & $6$ & $10$ & $7$ & $11$ \\
\hline
\end{tabular}

\Tree[.8 [.1 [.5 [.6 ] [.10 ]] [.3 [.7 ] [.11 ]]]
               [.2   [.9 ] [.4 ]]]
}

\medskip
\medskip
\medskip
\medskip
\medskip

{\centering
\begin{tabular}{|c|c|c|c|c|c|c|c|c|c|c|}
\hline
$1$ & $3$ & $2$ & $5$ & $7$ & $9$ & $4$ & $6$ & $10$ & $8$ & $11$ \\
\hline
\end{tabular}

\Tree[.1 [.3 [.5 [.6 ] [.10 ]] [.7 [.8 ] [.11 ]]]
               [.2   [.9 ] [.4 ]]]
}

\end{enumerate}
\end{document}

I feel like the trees are taking up too much space, so I want to have them two columns per row instead of one per row. It would also be good if I could number them somehow, or otherwise be able to indicate the order explicitly. How can I achieve this? Thanks!

A: Do you want something like this?

This uses a new command \ticker{<numbers for ticker tape>}{<code for tree>}. (I only used \ticker because it looks like ticker tape to me.)
\documentclass{article}
\usepackage{geometry}
\usepackage{tikz}
\usepackage{qtree}
\pagestyle{empty}
\begin{document}
\newcounter{tapes}
\newcommand*\ticker[2]{%
  \refstepcounter{tapes}%
  \noindent\thetapes.
  \begin{minipage}[t]{.45\textwidth}
    \centering
    \tikz{%
      \coordinate (n0) at (0,0);
      \foreach \i [count=\j, remember=\j as \k (initially 0)] in {#1} \node (n\j) [anchor=south west, draw, text width=12.5pt, text centered, inner ysep=2.5pt, inner xsep=2.5pt, xshift=-\pgflinewidth] at (n\k.south east)  {\i};
    }\par
    #2\medskip\par
  \end{minipage}%
}
\ticker{8,11,9,6,7,2,4,5,10,1,3}{%
  \Tree[.8 [.11 [.6 [.5 ] [.10 ]] [.7 [.1 ] [.3 ]]]
  [.9   [.2 ] [.4 ]]]}\hfill
\ticker{8,11,9,6,1,2,4,5,10,7,3}{%
  \Tree[.8 [.11 [.6 [.5 ] [.10 ]] [.1 [.7 ] [.3 ]]]
  [.9   [.2 ] [.4 ]]]}

\ticker{8,11,9,5,1,2,4,6,10,7,3}{%
  \Tree[.8 [.11 [.5 [.6 ] [.10 ]] [.1 [.7 ] [.3 ]]]
  [.9   [.2 ] [.4 ]]]}\hfill
\ticker{8,11,2,5,1,9,4,6,10,7,3}{%
  \Tree[.8 [.11 [.5 [.6 ] [.10 ]] [.1 [.7 ] [.3 ]]]
  [.2   [.9 ] [.4 ]]]}

\ticker{8,1,2,5,3,9,4,6,10,7,11}{%
  \Tree[.8 [.1 [.5 [.6 ] [.10 ]] [.3 [.7 ] [.11 ]]]
  [.2   [.9 ] [.4 ]]]}\hfill
\ticker{1,3,2,5,7,9,4,6,10,8,11}{%
  \Tree[.1 [.3 [.5 [.6 ] [.10 ]] [.7 [.8 ] [.11 ]]]
  [.2   [.9 ] [.4 ]]]}
\end{document}

EDIT
This addresses a further question asked in comments, which is how to centre the trees with respect to their roots, as opposed to centring the trees themselves.
I think this would be hard to do with qtree unless, perhaps, you hacked the production of the ticker tape into the \Tree macro. It is a long time since I used qtree, but I remember hacking it not being especially fun. (That is, it was hard to get it to do what it was not intended to be able to do!)
You can stop the trees being centred with qtree, but that is not really what is wanted.
To centre the roots relative to the ticker tapes, I suggest abandoning qtree and moving to one of the more flexible TikZ-based tree-drawing packages. tikz-qtree is one option; forest is another. My preference for the latter will come as no particular surprise on this site.
Here's a Forest solution. tickertree is an environment which takes one mandatory argument. This argument should specify the numbers for the ticker tape. The body of the environment should give the tree specification in Forest's bracket syntax.
Then
\begin{tickertree}{8,11,9,6,7,2,4,5,10,1,3}
  [8
    [11
      [6
        [5]
        [10]
      ]
      [7
      [1]
      [3]
      ]
    ]
    [9
      [2]
      [4]
    ]
  ]
\end{tickertree}\hfill
\begin{tickertree}{8,11,9,6,1,2,4,5,10,7,3}
  [8[11[6[5][10]][1[7][3]]][9[2][4]]]
\end{tickertree}

\begin{tickertree}{8,11,9,5,1,2,4,6,10,7,3}
  [8[11[5[6][10]][1[7][3]]][9[2][4]]]
\end{tickertree}\hfill
\begin{tickertree}{8,11,2,5,1,9,4,6,10,7,3}
  [8[11[5[6][10]][1[7][3]]][2[9][4]]]
\end{tickertree}

\begin{tickertree}{8,1,2,5,3,9,4,6,10,7,11}
  [8[1[5[6][10]][3[7][11]]][2[9][4]]]
\end{tickertree}\hfill
\begin{tickertree}{1,3,2,5,7,9,4,6,10,8,11}
  [1[3[5[6][10]][7[8][11]]][2[9][4]]]
\end{tickertree}

will produce the 6 trees with tickers shown above, with their roots below the midpoint of their respective tapes.

\documentclass{article}
\usepackage{geometry}
\usepackage[linguistics]{forest}
\pagestyle{empty}
\makeatletter
\environbodyname\tickertreebody
\bracketset{action character=@}
\newsavebox\tickertreetape
\newcounter{tapes}
\NewEnviron{tickertree}[1]{%
  \sbox\tickertreetape{%
    \tikz{%
      \coordinate (n0) at (0,0);
      \foreach \i [count=\j, remember=\j as \k (initially 0)] in {#1} \node (n\j) [anchor=south west, draw, text width=12.5pt, text centered, inner ysep=2.5pt, inner xsep=2.5pt, xshift=-\pgflinewidth] at (n\k.south east)  {\i};
    }%
  }%
  \refstepcounter{tapes}%
  \noindent\thetapes.
  \begin{forest}
    before drawing tree={
      !r1.no edge
    },
    before computing xy={
      !r1.l'=\baselineskip,
    }
    [\usebox{\tickertreetape} @\tickertreebody]
  \end{forest}}
\makeatother
\begin{document}

\begin{tickertree}{8,11,9,6,7,2,4,5,10,1,3}
  [8
    [11
      [6
        [5]
        [10]
      ]
      [7
      [1]
      [3]
      ]
    ]
    [9
      [2]
      [4]
    ]
  ]
\end{tickertree}\hfill
\begin{tickertree}{8,11,9,6,1,2,4,5,10,7,3}
  [8[11[6[5][10]][1[7][3]]][9[2][4]]]
\end{tickertree}

\begin{tickertree}{8,11,9,5,1,2,4,6,10,7,3}
  [8[11[5[6][10]][1[7][3]]][9[2][4]]]
\end{tickertree}\hfill
\begin{tickertree}{8,11,2,5,1,9,4,6,10,7,3}
  [8[11[5[6][10]][1[7][3]]][2[9][4]]]
\end{tickertree}

\begin{tickertree}{8,1,2,5,3,9,4,6,10,7,11}
  [8[1[5[6][10]][3[7][11]]][2[9][4]]]
\end{tickertree}\hfill
\begin{tickertree}{1,3,2,5,7,9,4,6,10,8,11}
  [1[3[5[6][10]][7[8][11]]][2[9][4]]]
\end{tickertree}

\end{document}


text:
Q: Error executing EntityManageer delete native query with in clause parameter I get an error executing EntityManageer delete native query with in clause parameter. The parameter is of type List and I want to do something like-
List<UUID> ids = ...
entityManager.createNativeQuery("DELETE FROM FOO WHERE ID IN (:ids)")
        .setParameter("ids", ids)
        .executeUpdate();

The exception that I get is-
javax.persistence.PersistenceException: org.hibernate.exception.SQLGrammarException: ERROR: IN could not convert type bytea to uuid
  Position: 39
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1377)
    at org.hibernate.ejb.AbstractEntityManagerImpl.convert(AbstractEntityManagerImpl.java:1300)
    at org.hibernate.ejb.AbstractEntityManagerImpl.throwPersistenceException(AbstractEntityManagerImpl.java:1387)
    at org.hibernate.ejb.AbstractQueryImpl.executeUpdate(AbstractQueryImpl.java:108)
[snip]

Please let me know how I can run the delete query above.

A: Since its a Native query you should have something like below:       entityManager.createNativeQuery("DELETE FROM FOO WHERE ID IN (?1)")
        .setParameter(1, ids)
        .executeUpdate();
Also, I think you don't need native query in this case, below code should work too:
entityManager.createQuery("DELETE FROM FOO WHERE ID IN (:ids)")
    .setParameter("ids", ids)
    .executeUpdate();


text:
Q: Why does django autocomplete dont work on first page visit before python 2.7 code for autocomplete works fine, but after python3 autocomplete dont work as it is, everytime i visit the page the field is always blank and the select2 is not fount everytime I check in google chrome network
<link href="{% static 'autocomplete_light/vendor/select2/dist/css/select2.css' %}" type="text/css" media="all" rel="stylesheet" />
<link href="{% static 'autocomplete_light/select2.css' %}" type="text/css" media="all" rel="stylesheet" />
<script type="text/javascript" src="{% static 'autocomplete_light/jquery.init.js' %}"></script>
<script type="text/javascript" src="{% static 'autocomplete_light/autocomplete.init.js' %}"></script>
<script type="text/javascript" src="{% static 'autocomplete_light/vendor/select2/dist/js/select2.full.js' %}"></script>
<script type="text/javascript" src="{% static 'autocomplete_light/select2.js' %}"></script>
<script type="text/javascript">

forms.py
        widgets = {
            'tags': autocomplete.ModelSelect2Multiple(url='tags_autocomplete'),

        }

thanks

A: I found an answer in this django-autocomplete-light displays empty dropdown in the form I just added {{ form.media }} on the header an it work


text:
Q: There was an error parsing the query. [ Token line number] sql error while creating table Hi guys im tryin to create tables in sql compact.
Here is the query:
CREATE TABLE [dbo.A]
(
    Id nvarchar(37) NOT NULL CONSTRAINT Info_PK PRIMARY KEY,
    ImportDate datetime NOT NULL
);

CREATE TABLE [dbo.B]
(
    Id uniqueidentifier PRIMARY KEY,
        DeviceId smallint,

);

But it is giving error in the line where it is tryin to create table B.

A: Don't use dbo. Schemas are not supported in SQL CE.
And you may need execute your queries separately.
Here is a similar problem and the solution:
http://social.msdn.microsoft.com/Forums/en-US/sqlce/thread/d6f1db96-8724-4376-990e-3f6da18c2d08/

A: I would remove the comma after DeviceId smallint
CREATE TABLE [dbo.A]
( Id nvarchar(37) NOT NULL CONSTRAINT Info_PK PRIMARY KEY,
ImportDate datetime NOT NULL
);

CREATE TABLE [dbo.B] ( Id uniqueidentifier PRIMARY KEY, DeviceId smallint
);

A: I googled this and it sounds like you are using SQL CE (for future reference it's always good to tell us what implementation of SQL you are using).
Brackets [] are not supported as delimiters in CE.  Try removing those from your table names.

A: Despite the fact a batch with multiple query is working on SQL Server Management Studio, it won't work with SqlCeCommand.
You have to split your batch in multiple query (you can use a transaction to be sur all the query are executed or none). I recommand to use ExecuteNonQuery as it doesn't use cursor (which could make some error in a transaction).
You could use the following sample.
Using connexion As New SqlCeConnection(connexionstring)
            connexion.Open()
            Dim transaction As SqlCeTransaction = connexion.BeginTransaction()
            Try
                Dim batch As String = GetCommandText()
                For Each query In batch.Split(";")
                    If Not String.IsNullOrWhiteSpace(query) Then
                        Dim command As New SqlCeCommand(query, connexion, transaction)
                        command.ExecuteNonQuery()
                    End If
                Next
                transaction.Commit()
            Catch ex As Exception
                transaction.Rollback()
                Throw
            End Try
        End Using


text:
Q: Can I hit with Ahri's Q more than twice? I've seen Draven's Whirling Death will achieve a third hit if you flash over your ult to change its course to hit the enemy a third time. A variant with Blitzcrank can be seen here and the usage of 'teleport' here

(Active): Draven hurls two massive axes in a given direction, dealing physical damage to every unit struck.
   Upon reaching the edge of the map, striking an enemy champion or upon the reactivation of Whirling Death, the axes will slowly come to a stop before changing direction and returning to Draven

Ahri's Q is another out-and-back ability similar to Draven's ult.

(Active) Ahri sends out and pulls back her orb, dealing magic damage on the way out and true damage on the way back.

My question is, if you are able to flash over your enemy with Orb of Deception in flight, causing it to change direction, will it hit a third time? Will it deal magic or true damage on the third hit?

A: It is not possible for an ability to hit more often than it was designed to - if it does, it's a bug.
As you can see in this video, Ezreal's ult can hit the same target only once. Another example would be Veigar's Even Horizon - if the target manages to break the stun quickly enough to walk through the same Event Horizon, he will not be stunned again. Accordingly, it should be impossible to be hit more than twice by returning projectile abilities such as Ahri's Q, Sivir's Q, or Draven's ult.

A: It will do true damage as the orb is on its way back, you just change the position where YOU are, but its still on the way to you.
The number of hits has nothing to do with the kind of damge it deals, only the direction it is heading.


text:
Q: How to add multiple pictures into Tkinter Text-widget? (python) I'm making this app, and I need to display a bunch of images alongside titles. I haven't done the title part yet because I ran into a problem.
I'm using a for loop to add all the images into this Text-box widget, which allows me to scroll through all the images once they've been added with the loop.
When the loop finishes going through all 25 pictures, only the last picture added is shown in the textbox and it's all the way at the bottom. It looks like this:

You can see that the image is all the way at the bottom of the screen and there's only one. It appears that its placing all the images, but all of them except for the last one are invisible.
I've done all I could but I couldn't wrap my head around why. Does anybody know?? Here's the code:
# the textbox was made here
self.display = Text(self.frame, font=('Roboto', 15), bg='#c8cbcc', borderwidth=0, highlightthickness=0)
self.display.grid(row=0, column=0, sticky='nsew', ipadx=200)

for i in range(len(thumbnails)):
    urllib.request.urlretrieve(thumbnails[i], 'thumbnails/img{}.jpg'.format(i))

    # get image
    img = Image.open(('thumbnails/img{}.jpg'.format(i)))
    img = img.crop([0, 60, 480, 300])
    img = img.resize((200, round(200 / 1.3333)))

    global image
    image = ImageTk.PhotoImage(img)

    # self.display.insert(END, '\n\t\t')
    self.display.image_create(END, image=image)

self.display.config(state='disabled')


text:
Q: How to clear database sessions pool after making request I'm trying to use FastAPI with async SQLAlchemy. For db session I want to create FastApi dependency:
async_db_url = f'postgresql+asyncpg://{db_user}:{db_pass}@{db_host}:{db_port}/{db_name}'
async_engine = create_async_engine(async_db_url)
async_session = sessionmaker(async_engine, expire_on_commit=False, class_=AsyncSession)

async def async_db_session() -> AsyncGenerator:
    async with async_session() as session:
        try:
            yield session
        except Exception as exc:
            await session.rollback()
            raise exc

I expect that the session will be closed after use, because of context manager. But it does not happen. Instead of that I can see new connections with each request. And number of connections riches the limit, I can't connect to db anymore.
I tried to use  engine.dispose() from documentation, but it caused very slow requests. I did it like that:
async def async_db_session() -> AsyncGenerator:
    async with async_session() as session:
        try:
            yield session
        except Exception as exc:
            await session.rollback()
            raise exc
        finally:
            await engine.dispose()

How to force connection to drop after making a request?


text:
Q: My EC2 instance has a Public IP but don't have a Public DNS I created a new VPC called testglobal with 2 subnets: opennet, closednet
So I created EC2 instances on those subnets and now I can't ping them.
In EC2 panel it shows the Public IP but don't shows Public DNS.
They are all associated to ElasticIPs and added to a group with All Traffic IN/OUT.
Am I doing something wrong?

A: EC2 instances in your public subnet (what you've called opennet) will have a public DNS and a public IP address. You will only be able to ping them if they are in a security group that allows ICMP echo requests from your client-side IP address.
Instances in your private subnet (closednet) will not have public IP addresses or public DNS names. They will only have private addresses within the range of your subnets. That is the intent of a private subnet - to not allow direct public Internet traffic. Access systems in the private subnets only from the instance in public subnets, or alternatively via VPN.
More specific advice would require further information, like screenshots of the instance, subnet, route table and security group details.


text:
Q: How to create an ISO disk image of an NVMe SSD? I want to create a disk image of my solid-state drive using the dd (disk dump) command. There are multiple partitions on the SSD. Is it possible to make a complete image of the drive including all partitions?
This is an example of how it works with an HDD:
dd if=/dev/sda of=/mnt/sdb/disk.img conv=sync,noerror bs=64K

However, I'm unsure because in /dev/ the paths to my NVMe SSD look different. There are  these variants:
 /dev/nvme0
 /dev/nvme0n1
 /dev/nvme0n1p1
 /dev/nvme0n1p2
 /dev/nvme0n1p3
 /dev/nvme0n1p4
Which path do I have to set as the input file if= ? Why? nvme0n1p1 to nvme0n1p4 are the four partitions. As I said before, I don't want to create an image of a single partition only. What is the difference between nvme0 and nvme0n1?

A: If you want do make image of the entire disk, use /dev/nvme0n1, this is the NVMe drive block device (it's actually a "namespace", you can in theory have multiple namespaces on an NVMe drive, it's like a "partition on a hardware level", but most "consumer" NVMes come with only one namespace).
/dev/nvme0 is controller, a character device  used for control/management of the NVMe device (like adding new namespaces, changing block size etc.).You can use nvme-cli tools for NVMe management, for example to get SMART data or temperature using the nvme0 device:
sudo nvme smart-log /dev/nvme0
Smart Log for NVME device:nvme0 namespace-id:ffffffff
critical_warning                        : 0
temperature                             : 38 C
available_spare                         : 100%
...

(But I generally don't recommend playing with the tool, you can remove everything from the drive by accident very easily.)
ArchWiki has a great article about NVMes if you're interested in more details, but everything you need to know is:

*

*ignore nvme0, you'll probably never use it

*nvme0n1 is the drive (= sda)

*nvme0n1pX are partitions on nvme0n1, the only difference is instead of sda + number you have nvme0n1 + p + number where p means "partition" and is added only because nvme0n1 ends with a digit (that isn't NVMe-specific)


text:
Q: Share connection to postgres db across processes in Python I have a Python script running as a daemon. At startup, it spawns 5 processes, each of which connects to a Postgres database. Now, in order to reduce the number of DB connections (which will eventually become really large), I am trying to find a way of sharing a single connection across multiple processes. And for this purpose I am looking at the multiprocessing.sharedctypes.Value API. However, I am not sure how I can pass a psycopg2.connection object using this API across processes. Can anyone tell me how it might be done?
I'm also open to other ideas in order to solve this issue.
The reason why I did not consider passing the connection as part of the constructor to the 5 processes is mutual exclusion handling. I am not sure how I can prevent more than one process from accessing the connection if I follow this approach. Can someone tell me if this is the right thing to do?

A: You can't sanely share a DB connection across processes like that. You can sort-of share a connection between threads, but only if you make sure the connection is only used by one thread at a time. That won't work between processes because there's client-side state for the connection stored in the client's address space.
If you need large numbers of concurrent workers, but they're not using the DB all the time, you should have a group of database worker processes that handle all database access and exchange data with your other worker processes. Each database worker process has a DB connection. The other processes only talk to the database via your database workers.
Python's multiprocessing queues, fifos, etc offer appropriate messaging features for that.


text:
Q: Querying dates in Realm React Native [EDITED]
I'd like to query and filter by dates in realm. Here's my code:
    let factories = realm.objects('Factory')
    for(factory of factories) {
       let toys = realm.objects('Toy').filtered('factory_id == factory.id')
       let lowerBound = new Date(year + '-1-1T00:00:00Z')
       let uppperBound = new Date(year + '-2-1T00:00:00Z')
       let janToys = toys.filtered('created_at > lowerBound AND created_at < uppperBound')
    }

year is a variable declared before the code snippet above.
This doesn't work and I'm pretty sure it's because the date format is not correct.
Here is the date format when I log toys:
Fri Mar 24 2017 16:01:59 GMT+0800 (Malay Peninsula Standard Time)
I'd like to know how to query realm dates. I can't find it in the documentation and other posts here. I'd appreciate any help. If this is not a date format issue, please tell me.
Thank you!
EDIT: I added the outside loop. This may not be a date format issue. Here is the error message:
    Error: Predicate expressions must compare a keypath and another keypath or a constant value`

A: It seems that Realm does not support dot operators inside its queries. Forcing Realm to be relational is not allowed. As a solution, I transformed my usage to follow NoSQL convention. Passing in objects instead of declaring relationships.


text:
Q: Laravel 4, jQuery .ajax, No post input received I must be missing something, didn't think this would have been a issue.
I have a login form that has no connection to laravel form, although its on the same domain, and a POST route with laravel at "login".
I can change it to GET and everything works, but I would like to use POST.
/online/index.html
$("#login").click(function(e){
    console.log( $("#loginForm").serialize() );
    var request = $.ajax({
      url: "../login/",
      type: "POST",
      data: { test : "someuser" },
      dataType: "json"
    });

    request.done(function( data ) {
      console.log("Complete");
      console.log(data);
    });

    request.fail(function( jqXHR, textStatus ) {
      console.log("Failed");
      console.log(textStatus);
    });
});

Route::post('login', array('as' => 'login', 'uses' => 'AuthController@doLogin'));
( which is below /online/ )
class AuthController extends Controller {

    public function doLogin(){

        $username = Input::get('username');
        $password = Input::get('password');

        return Response::json(Input::all());

    }
}

In the javascript console, when you press login, it shows...
Complete
[]

When it should say something like this...
Complete
[ test => "someuser" ]

Using Laravel 4, jQuery 1.8.3. Any ideas would be great... Thanks!

A: I just removed the trailing slash in the Ajax request URL and everything worked as planned.


text:
Q: Exposing SQL Server database to internet I have a POS application that is used by a business. The application has a SQL Server backend and there's a local machine that acts as a server for the DB. The other computers within the office connect to this server. This happens over TCP/IP. I am wondering if it is possible and/or how difficult it would be to expose this database and allow read access to an offsite application. Essentially I want to be able to pull data from a local database into AWS on a regular automated schedule. If anyone has any ideas that could help point me in the right direction, that would be great. This is not an application I'm a developer of, so I don't have access to the application code or anything like that. I guess what it boils down to would be the equivalent of an off-site backup. Thanks in advance!

A:
what I'm really looking to do is create offsite backups automatically

SQL Server can natively backup to Azure Blob Storage.  See Backup to URL.
But whatever offsite storage you use, the right solution is for SQL Server (or code running on the local network) to push the data out.  Not have code running elsewhere pull it out.
That way you don't need to open anything to the internet, or use a VPN.  You just need to open outbound ports, to connect to the internet.


text:
Q: EXC_BAD_ACCESS NSXMLParser using delegate on ARC I have this code in parser DidendElement.
   [self setImageThumbnailLink:[NSMutableString stringWithString:imageLink]];
    if([_delegate respondsToSelector:@selector(receiveImageLink:withParser:withParameter:)]){

        [_delegate receiveImageLink:[self imageThumbnailLink] withParser:nil withParameter:parameterPassed];
    }
    else{
        [NSException raise:NSInternalInconsistencyException
                    format:@"Delegate doesn't respond to receiveItems:"];
    }

When the code reach   [_delegate receiveImageLink:[self imageThumbnailLink] withParser:nil withParameter:parameterPassed];
EXC_BAD_ACCESS occur. I've tried what is wrong with it by trying to make each parameter nil. And EXC_BAD_ACCESS occur when the [self imageThumbnailLink] is passed to delegate.
How can i solve that?
I use [nonatomic,strong] for imageThumbnailLink. it is NSMutableString.
If i use this code (not using variable):It is working fine.
 [_delegate receiveImageLink:@"http://www.....flower.jpg" withParser:nil withParameter:parameterPassed];

Thank you
Error Message in console:
Only
Current language: auto; currently objective-c (gdb).
This is the stack trace:

A: Lacking the complete error message here is best guess:
Probably [self imageThumbnailLink] is bad or parameterPassed. Try separating the statement into two for debugging:
Ex:
NSLog(@"parameterPassed: %@", parameterPassed);
NSString *imageLink = [self imageThumbnailLink];
NSLog(@"imageLink: %@", imageLink);
[_delegate receiveImageLink:imageLink withParser:nil withParameter:parameterPassed];

In general when  trying to debug an error separating the components of a compound statement is a good first step.


text:
Q: SQL Server Express 2014, Windows Authentication problems I am using SQL Server Express 2014, and I currenly have a (probably) very stupid problem with Windows Authentication.
I have a AD server, a MS-SQL server and a Client, where everything was installed from scratch to test in VMs.
I want access to be through Active Directory.

*

*I go in the SQL Server Management studio

*In Security/Connections, I add the new User

*While adding him in connection, I map him towards my database as db_datareader and db_datawriter

*In my database properties, I check that the user really have the Explicit rights for at least CONNECT, SELECT, INSERT, UPDATE, DELETE, and he does

I test my setup with a very small VBA macro (in Microsoft Office), which's the following :
Sub OpenConn()
    Dim ConnString As String
    Dim DB_Address As String
    Dim DB_Name As String

    DB_Address = "Computer1\SQLEXPRESS"
    DB_Name = "MyDB"

    ConnString = "Provider=SQLOLEDB;Data Source=" & DB_Address & ";" & _
                 "Initial Catalog=" & DB_Name & ";" & _
                 "Integrated Security=SSPI;"

    Set DB = New ADODB.Connection
    DB.Open ConnString
End Sub

With the user that installed SQL Express, it works perfectly.(I'm doing a small SELECT as test, and works as intended)
With the user I previously added, It tells me that my server can't be joined.
Weird thing is that, when I check my connections logs in SQL Server, it tells me that the connection succedeed.
Log of my connection success with the account that INSTALLED the Server (Sorry, the log's in french)
08/12/2015 23:52:11,Microsoft-Windows-Security-Auditing,Réussite de l'audit,L'ouverture de session d'un compte s'est correctement déroulée.<nl/><nl/>Sujet :<nl/>   ID de sécurité :        S-1-0-0<nl/>    Nom du compte :     -<nl/>  Domaine du compte :     -<nl/>  ID d'ouverture de session :     0x0<nl/><nl/>Type d'ouverture de session :          3<nl/><nl/>Nouvelle ouverture de session :<nl/> ID de sécurité :        S-1-5-21-2814706995-1848420457-3208371447-1105<nl/> Nom du compte :     cgl<nl/>    Domaine du compte :     TEST<nl/>   ID d'ouverture de session :     0x53172f<nl/>   GUID d'ouverture de session :       {00000000-0000-0000-0000-000000000000}<nl/><nl/>Informations sur le processus :<nl/>    ID du processus :       0x0<nl/>    Nom du processus :      -<nl/><nl/>Informations sur le réseau :<nl/>    Nom de la station de travail :  COMP2<nl/>  Adresse du réseau source :  -<nl/>  Port source :       -<nl/><nl/>Informations détaillées sur l'authentification :<nl/>    Processus d'ouverture de session :      NtLmSsp <nl/>   Package d'authentification :    NTLM<nl/>   Services en transit :   -<nl/>  Nom du package (NTLM uniquement) :  NTLM V2<nl/>    Longueur de la clé :        128<nl/><nl/>Cet événement est généré lors de la création d'une ouverture de session. Il est généré sur l'ordinateur sur lequel l'ouverture de session a été effectuée.<nl/><nl/>Le champ Objet indique le compte sur le système local qui a demandé l'ouverture de session. Il s'agit le plus souvent d'un service<c/> comme le service Serveur<c/> ou un processus local tel que Winlogon.exe ou Services.exe.<nl/><nl/>Le champ Type d'ouverture de session indique le type d'ouverture de session qui s'est produit. Les types les plus courants sont 2 (interactif) et 3 (réseau).<nl/><nl/>Le champ Nouvelle ouverture de session indique le compte pour lequel la nouvelle ouverture de session a été créée<c/> par exemple<c/> le compte qui s'est connecté.<nl/><nl/>Les champs relatifs au réseau indiquent la provenance d'une demande d'ouverture de session à distance. Le nom de la station de travail n'étant pas toujours disponible<c/> peut être laissé vide dans certains cas.<nl/><nl/>Les champs relatifs aux informations d'authentification fournissent des détails sur cette demande d'ouverture de session spécifique.<nl/>    - Le GUID d'ouverture de session est un identificateur unique pouvant servir à associer cet événement à un événement KDC .<nl/> - Les services en transit indiquent les services intermédiaires qui ont participé à cette demande d'ouverture de session.<nl/>  - Nom du package indique quel est le sous-protocole qui a été utilisé parmi les protocoles NTLM.<nl/>   - La longueur de la clé indique la longueur de la clé de session générée. Elle a la valeur 0 si aucune clé de session n'a été demandée.,(12544),4624,,Comp1
08/12/2015 23:52:11,Microsoft-Windows-Security-Auditing,Réussite de l'audit,Privilèges spéciaux attribués à la nouvelle ouverture de session.<nl/><nl/>Sujet :<nl/> ID de sécurité :        S-1-5-21-2814706995-1848420457-3208371447-1105<nl/> Nom du compte :     cgl<nl/>    Domaine du compte :     TEST<nl/>   ID d'ouverture de session :     0x53172f<nl/><nl/>Privilèges :      SeSecurityPrivilege<nl/>            SeBackupPrivilege<nl/>          SeRestorePrivilege<nl/>         SeTakeOwnershipPrivilege<nl/>           SeDebugPrivilege<nl/>           SeSystemEnvironmentPrivilege<nl/>           SeLoadDriverPrivilege<nl/>          SeImpersonatePrivilege,(12548),4672,,Comp1
08/12/2015 23:52:11,Logon,Inconnu,Login succeeded for user 'TEST\cgl'. Connection made using Windows authentication. [CLIENT : 192.168.152.170],,,,

It tells me that it gives special privileges to the new session (2nd line)
Now the login with the account that doesn't work
08/12/2015 23:51:36,Microsoft-Windows-Security-Auditing,Réussite de l'audit,L'ouverture de session d'un compte s'est correctement déroulée.<nl/><nl/>Sujet :<nl/>   ID de sécurité :        S-1-0-0<nl/>    Nom du compte :     -<nl/>  Domaine du compte :     -<nl/>  ID d'ouverture de session :     0x0<nl/><nl/>Type d'ouverture de session :          3<nl/><nl/>Nouvelle ouverture de session :<nl/> ID de sécurité :        S-1-5-21-2814706995-1848420457-3208371447-1111<nl/> Nom du compte :     cgl3<nl/>   Domaine du compte :     TEST<nl/>   ID d'ouverture de session :     0x52c0e4<nl/>   GUID d'ouverture de session :       {5F718665-B8B7-28B2-9D08-5DB2898F3FA2}<nl/><nl/>Informations sur le processus :<nl/>    ID du processus :       0x0<nl/>    Nom du processus :      -<nl/><nl/>Informations sur le réseau :<nl/>    Nom de la station de travail :  <nl/>   Adresse du réseau source :  192.168.152.170<nl/>    Port source :       49232<nl/><nl/>Informations détaillées sur l'authentification :<nl/>    Processus d'ouverture de session :      Kerberos<nl/>   Package d'authentification :    Kerberos<nl/>   Services en transit :   -<nl/>  Nom du package (NTLM uniquement) :  -<nl/>  Longueur de la clé :        0<nl/><nl/>Cet événement est généré lors de la création d'une ouverture de session. Il est généré sur l'ordinateur sur lequel l'ouverture de session a été effectuée.<nl/><nl/>Le champ Objet indique le compte sur le système local qui a demandé l'ouverture de session. Il s'agit le plus souvent d'un service<c/> comme le service Serveur<c/> ou un processus local tel que Winlogon.exe ou Services.exe.<nl/><nl/>Le champ Type d'ouverture de session indique le type d'ouverture de session qui s'est produit. Les types les plus courants sont 2 (interactif) et 3 (réseau).<nl/><nl/>Le champ Nouvelle ouverture de session indique le compte pour lequel la nouvelle ouverture de session a été créée<c/> par exemple<c/> le compte qui s'est connecté.<nl/><nl/>Les champs relatifs au réseau indiquent la provenance d'une demande d'ouverture de session à distance. Le nom de la station de travail n'étant pas toujours disponible<c/> peut être laissé vide dans certains cas.<nl/><nl/>Les champs relatifs aux informations d'authentification fournissent des détails sur cette demande d'ouverture de session spécifique.<nl/>  - Le GUID d'ouverture de session est un identificateur unique pouvant servir à associer cet événement à un événement KDC .<nl/> - Les services en transit indiquent les services intermédiaires qui ont participé à cette demande d'ouverture de session.<nl/>  - Nom du package indique quel est le sous-protocole qui a été utilisé parmi les protocoles NTLM.<nl/>   - La longueur de la clé indique la longueur de la clé de session générée. Elle a la valeur 0 si aucune clé de session n'a été demandée.,(12544),4624,,Comp1

I really don't understand this problem, or even what I'm doing wrong...
And I can't even seem to find answers on the net, meaning I'm probably searching for the wrong thing...
Can Anyone help me?
Thanks in advance


text:
Q: What is fastest way to insert rows in sqlite database I have around 7000 rows which want to insert into device's(Android galaxy tab2) sqlite database. Currently I am parsing the JSON file and inserting the row into the database using "for" loop. But its taking more than 120 seconds to parse and inset data into sqlite database. Is there any other faster way to do this?
Thanks...

A: I have ran into the exact same situation. First I was using DatabaseUtil.insertHelper, and it was taking me +30 seconds for 600 entries.
I did a bit more digging and found out that every row i'm inserting is being committed, which is extremely expensive.
To solve this, I switched to ORMLite, with the insertAll method:
/**
* Inserts multiple objects into the database quickly by committing them all at once
*
* @param objects The objects to insert
*/
public void insertAll(final T[] objects) {
    try {
        dao.callBatchTasks(new Callable<Void>() {

        @Override
        public Void call() throws Exception {
            for (T object : objects) {
                dao.create(object);
            }
            return null;
        }
        });
    } catch (Exception e) {
    AdbLogger.error("Error inserting new " + className + "s in the database");
}
}

The idea here is that they do the insert of the array of object, then at the end only do one big commit. After this switch the insert became almost instantanious.

A: You should use statements
database.beginTransaction();
SQLiteStatement stmt = database.compileStatement(sql);

for (int i = 0; i < NUMBER_OF_ROWS; i++) {
    //generate some values

    stmt.bindString(1, randomName);
    stmt.bindString(2, randomDescription);
    stmt.bindDouble(3, randomPrice);
    stmt.bindLong(4, randomNumber);

    long entryID = stmt.executeInsert();
    stmt.clearBindings();
}

database.setTransactionSuccessful();
database.endTransaction();

Reference
Here is one more link where a comparison between these two insertion methods is given. (for 100 records, normal insertion took 1657ms, while statements with endTransaction() took 92ms)


text:
Q: baudrate mismatch between AXI-Uartlite and Teraterm I have built a simple Microblaze system on a Kintex 7 on Avnet's MMP2 board. I am using Uartlite (v2.0) IP in this system and communicate to a PC using Teraterm (v4.85). The baudrate for the Uartlite component must be fixed at a particular value at the design stage. I have chosen 19200 bps for my design. I have written a very simple application that is sending 6 consecutive "At"s to the PC through Teraterm, then get an ascii character from the Teraterm console and print the same. The problem is that, for every "At" the Teraterm displays only one 'Ç' on the console. The transmission parameters are as follows:

19200 bps; 8 data bits; 1 stop bit; No parity; No Flow-control

However, after a lot of head scratching and trial and errors, I discovered that if I change the baudrate in Teraterm to 38400 bps, I get the desired behaviour, i.e., I get the "At"s on the console, get a char from console and print it back.
As far as I know the code (which is really very simple), I have not changed the baudrate. But somehow, I am sending data at a rate faster than the specified rate. The clock used is 100MHz. Since the baudrate MUST be specified in the design phase, how is it even possible to attain a higher baud rate? What have I done wrong?
The code goes like this:
#include <stdio.h>
#include "platform.h"
#include "xgpio_l.h"
#include "xintc_l.h"
#include "xparameters.h"
#include "xuartlite_l.h"

#define MAX_UART_BUFFER_LENGTH 16

u8 uart_rx_data = 0;

int main()
{
    init_platform();
    //Init GPIOs
    //dip switch port as input
    XGpio_WriteReg(XPAR_AXI_GPIO_0_BASEADDR, XGPIO_TRI_OFFSET, 0xFFFFFFFF);

    char count_data = 0x0F;
    while(1)
    {
        unsigned int dip_gpio_data = XGpio_ReadReg(XPAR_AXI_GPIO_0_BASEADDR, XGPIO_DATA_OFFSET) & 0x000000FF;
        if(dip_gpio_data == 0)
        {
            u8 send_data[MAX_UART_BUFFER_LENGTH] = "AtAtAtAtAtAt";
            u8 i = 0 ;
            for (i = 0; i < MAX_UART_BUFFER_LENGTH; i++)
            {
                if(send_data[i] != '\0')
                    XUartLite_SendByte(XPAR_AXI_UARTLITE_0_BASEADDR, send_data[i]);
                else
                    break;
            }
            //Rx something from Teraterm
            uart_rx_data = XUartLite_RecvByte(XPAR_AXI_UARTLITE_0_BASEADDR);
            //Send same thing back
            XUartLite_SendByte(XPAR_AXI_UARTLITE_0_BASEADDR, uart_rx_data);
            XUartLite_SendByte(XPAR_AXI_UARTLITE_0_BASEADDR, '\n');
            XUartLite_SendByte(XPAR_AXI_UARTLITE_0_BASEADDR, '\r');
        }
    }

    return 0;
}

EDIT:
Today, I tried to reduce the baudrate to 9600 at the UARTlite IP core, regenerated bitstream and ran again. The same result. If I set baudrate of Teraterm to 9600, it doesn't work. Teraterm gives an option of 14400 baudrate. I used this. I get 12 chars, but gibberish. If I exactly double it to 19200, it works perfectly. I will try with other baud rates as well and update. Please help.!! This is still the basic part of my design. Image below for reference:

EDIT2:
I tried the following:

*

*Uninstalled Teraterm and re-installed

*Installed Realterm

*Installed hyperterminal
Tried with all 3. No change in the behaviour. :(

A: found the reason for the strange behaviour.
It was a mistake from my side during design phase. According to my previous design, the Clocking wizard expects 100MHz as input and is designed to produce 100MHz at the output (no division is done). My UARTLite core also expects a 100MHz clock and applies the relevant divider values to generate a baudrate of 19200. But the board is supplying 200MHz. The clk_wizard assumes it is 100MHz and passes the clock without any division, and the chain continues till UARTLite. Here the UARTLite divides the 200MHz clk with the number it generated for a 100MHz clk. And thus I am transferring at double the speed.
Anyways, thank you for the time.


text:
Q: Como tornar um ion-radio requerido, ou tornar o botão inativo enquanto não escolher uma opção? Como posso tornar um ion-radio como requerido, ou desativar o botão se nada for selecionado?
  <ion-radio ng-model="escolhido.categoria_comida_cod_categoria_com" ng-value="'{{item.categoria_comida_cod_categoria_com}}'" ng-required="true">{{item.categoria_comida_nome}}</ion-radio>

Segue com o botão:
 <ion-list ng-repeat="item in categoriass | filter:q as results" ng-init="$last ? fireEvent() : null">

            <ion-radio ng-model="escolhido.categoria_comida_cod_categoria_com" ng-value="'{{item.categoria_comida_cod_categoria_com}}'" ng-required="true">{{item.categoria_comida_nome}}</ion-radio>
        </ion-list>

        <button class="button button-full button-assertive" ng-click="SelecionaCategoria(escolhido)">
            Continuar (Passo 1 de 2)
        </button>

A: Utilizei POG (Programação orientada a gambiarra)!
ng-required não aceita. Onde este if encontra nada, mas também não deixa passar se não tiver nada selecionado. Nem o Alert ele dá... POG total.
$scope.SelecionaCategoria = function () {

            if (($scope.escolhido.categoria_comida_cod_categoria_com).length === null) {
                slert('É PRECISO UMA CATEGORIA');
            } else {

                $ionicLoading.show();

                var url = "?cod_categoria=" + $scope.escolhido.categoria_comida_cod_categoria_com + "&categoria=" + $scope.escolhido.categoria_comida_nome + ""
                console.log(url);

                var encodedurl = encodeURI(url);
                $ionicLoading.hide();
                window.localStorage.setItem("cod_categoria", $scope.escolhido.categoria_comida_cod_categoria_com);

                $state.go('nhaac.formDelicias');

            }


text:
Q: The fastest way for relinking a directory I use a Gentoo Linux, and I'm currently moving my /usr/portage (portage's database, containing thousands of small ebuild files), /var/tmp/portage (portage's compiling directory), and /var/tmp/ccache (compiler cache directory) to reiserfs. These directories are performance sensitive and thousands of small files are accessed and written when portage is calculating package dependencies and compiling packages.
What is the fastest way of redirecting the directories into the new filesystem? Is there a huge performance loss from using a symlink since the system parse a symlink as a text? Is mount bind going to be better?

A: Mount --bind should be faster then symbolic link.
If you mount -B /mnt/portage /usr/portage reading /usr/portage will give you i-node of /mnt/portage and it should work as fast as normal directory.
Resolving symbolic link speed will depend on number of components in the linked path, so for /usr/portage linked to /mnt/portage it will be three additional i-node reads and two directory searches.
I doubt you will notice any difference between these methods, unless you are really using these file systems a lot.


text:
Q: Is this sound software engineering practice for class construction? Is this a plausible and sound way to write a class where there is a  syntactic sugar @staticmethod that is used for the outside to interact with? Thanks.
###scrip1.py###
import SampleClass.method1 as method1

output = method1(input_var)

###script2.py###
class SampleClass(object):

    def __init__(self):
        self.var1 = 'var1'
        self.var2 = 'var2'

    @staticmethod
    def method1(input_var):
        # Syntactic Sugar method that outside uses
        sample_class = SampleClass()
        result = sample_class._method2(input_var)
        return result

    def _method2(self, input_var):
        # Main method executes the various steps.
        self.var4 = self._method3(input_var)
        return self._method4(self.var4)

    def _method3(self):
        pass

    def _method4(self):
        pass

A: Answering to both your question and your comment, yes it is possible to write such a code but I see no point in doing it:
class A:
    def __new__(cls, value):
        return cls.meth1(value)

    def meth1(value):
        return value + 1

result = A(100)
print(result)

# output:
101

You can't store a reference to a class A instance because you get your method result instead of an A instance. And because of this, an existing __init__will not be called.
So if the instance just calculates something and gets discarded right away, what you want is to write a simple function, not a class. You are not storing state anywhere.
And if you look at it:
result = some_func(value)

looks exactly to what people expect when reading it, a function call.
So no, it is not a good practice unless you come up with a good use case for it (I can't remember one right now)
Also relevant for this question is the documentation here to understand __new__ and __init__ behaviour.
Regarding your other comment below my answer:
defining __init__ in a class to set the initial state (attribute values) of the (already) created instance happens all the time. But __new__ has the different goal of customizing the object creation. The instance object does not exist yet when __new__is run (it is a constructor function).  __new__ is rarely needed in Python unless you need things like a singleton, say a class A that always returns the very same object instance (of A) when called with A(). Normal user-defined classes usually return a new object on instantiation. You can check this with the id() builtin function. Another use case is when you create your own version (by subclassing) of an immutable type. Because it's immutable the value was already set and there is no way of changing the value inside __init__ or later. Hence the need to act before that, adding code inside __new__. Using __new__ without returning an object of the same class type (this is the uncommon case) has the addtional problem of not running __init__.
If you are just grouping lots of methods inside a class but there is still no state to store/manage in each instance (you notice this also by the absence of self use in the methods body), consider not using a class at all and organize these methods now turned into selfless functions in a module or package for import. Because it looks you are grouping just to organize related code.
If you stick to classes because there is state involved, consider breaking the class into smaller classes with no more than five to 7 methods. Think also of giving them some more structure by grouping some of the small classes in various modules/submodules and using subclasses, because a long plain list of small classes (or functions anyway) can be mentally difficult to follow.
This has nothing to do with __new__ usage.
In summary, use the syntax of a call for a function call that returns a result (or None) or for an object instantiation by calling the class name. In this case the usual is to return an object of the intended type (the class called). Returning the result of a method usually involves returning a different type and that can look unexpected to the class user. There is a close use case to this where some coders return self from their methods to allow for train-like syntax:
 my_font = SomeFont().italic().bold()

Finally if you don't like result = A().method(value), consider an alias:
func = A().method
...
result = func(value)

Note how you are left with no reference to the A() instance in your code.
If you need the reference split further the assignment:
a = A()
func = a.method
...
result = func(value)

If the reference to A() is not needed then you probably don't need the instance too, and the class is just grouping the methods. You can just write
func = A.method
result = func(value)

where selfless methods should be decorated with @staticmethod because there is no instance involved. Note also how static methods could be turned into simple functions outside classes.
Edit:
I have setup an example similar to what you are trying to acomplish. It is also difficult to judge if having methods injecting results into the next method is the best choice for a multistep procedure. Because they share some state, they are coupled to each other and so can also inject errors to each other more easily. I assume you want to share some data between them that way (and that's why you are setting them up in a class):
So this an example class where a public method     builds the result by calling a chain of internal methods. All methods depend on object state, self.offset in this case, despite    getting an input value for calculations.
Because of this it makes sense that every method uses self to access the state. It also makes sense that you are able to instantiate different objects holding different configurations, so I see no use here for @staticmethod or @classmethod.
Initial instance configuration is done in __init__ as usual.
# file: multistepinc.py

    def __init__(self, offset):
        self.offset = offset

    def result(self, value):
        return self._step1(value)

    def _step1(self, x):
        x = self._step2(x)
        return self.offset + 1 + x

    def _step2(self, x):
        x = self._step3(x)
        return self.offset + 2 + x

    def _step3(self, x):
        return self.offset + 3 + x

def get_multi_step_inc(offset):
    return MultiStepInc(offset).result

--------
# file: multistepinc_example.py

from multistepinc import get_multi_step_inc

# get the result method of a configured
# MultiStepInc instance
# with offset = 10.

# Much like an object factory, but you
# mentioned to prefer to have the result
# method of the instance
# instead of the instance itself.
inc10 = get_multi_step_inc(10)

# invoke the inc10 method
result = inc10(1)
print(result)

# creating another instance with offset=2
inc2 = get_multi_step_inc(2)

result = inc2(1)
print(result)

# if you need to manipulate the object
# instance
# you have to (on file top)

from multistepinc import MultiStepInc

# and then
inc_obj = MultiStepInc(5)

# ...
# ... do something with your obj, then
result = inc_obj.result(1)
print(result)

Outputs:
37
13
22


text:
Q: How to index when all columns are searchable? I have a large table of persons that have info about their appearance and skills like age, eye color, hair style, plays piano, etc
All these fields are searchable so a user can search for someone that plays guitar and have blue eyes.
How to deal with indexes in this particular case? I know that I cant create index for all columns because it will affect the write time. So whats the best approach for this scenario?

A: Creating indexes  is always a trade-off. You made a part of that trade-off yourself: you can't create an index for each column, because of the write-speed. How many indexes you can create depends on your trade-off between read-speedup and write-slowdown. That's for you to decide: if you update the table nightly outside office hours and only read during day-time, the trade-off is different that when you continuously update.
If your trade-off says you can create only 2 indexes, you might want to create them where they have the most impact. Which columns are those? We obviously don't know, but you may get some hints:

*

*do you use views with merges? They could be faster with indexes.

*do you have any statistics on the use? If a column is in 99% of all queries, that column is definitely a candidate for an index.

*do you have a number of fixed queries? You could speed those up with well chosen indexes.

*how many different values are there in a column? For example: has a driver-license is yes/no. An index on those colums is less effective that an index on age (ranging from 0-122 years and 164 days).

*do you have any policies, f.e. using queries on age is discouraged? In that case, you would not put an index on the age.

These are a few points to consider. As your question was quite generic, my answer is necessarily too.

A: You can't index every possible combination optimally. For example, if you want to search for plays_guitar=true and eye_color='blue' you'd need a compound index on the pair of columns (plays_guitar, eye_color). The order of columns in the index doesn't make much difference if both conditions are equality, but having the compound index does help a lot.
The trouble is, this means you'd need not only an index for every column, you'd need all possible combinations. So 2n indexes for n columns.
But there's also inequality conditions to account for. For example, if you want to search for plays_guitar=true and eye_color <> 'blue', the latter condition is an inequality. Then the order of columns in the index does matter. You can have multiple columns used for equality conditions, first in the index. Then you can have one column used for an inequality condition follow the other columns.
So you don't merely need 2n indexes, you need indexes for all permutations of columns (that is, combinations but with significant ordering), which is on the order of n! indexes. Clearly this is not possible given the practical limits of a database.
The only options are to index some of the columns that are searchable, and hope that narrows down the search sufficiently. Conditions on additional columns that aren't in the index will be evaluated row by row. This is where you get a high number of "rows examined" in your query execution.
This is not as good as finding the rows solely by index lookups, but maybe not a deal-breaker.
So it's up to you to design a limited set of indexes that are going to be "good enough" to narrow down the most likely searches.
Welcome to being a professional software engineer — you need to use your judgment and experience, and you can't optimize all possible outcomes.
If you are told the searches are totally unpredictable and all possible searches should be treated as equally likely, then that's not a scenario that can be solved, at least not with B-Tree indexes.
Then you can try adapting the data to a fulltext search architecture, where you can index the whole dataset and search for values in arbitrary combinations of columns.
Currently the most popular example of such a database is Elasticsearch, which is based on the open-source Apache Lucene search engine.
Apache Solr is another good choice, if you want to stick to open-source offerings (the latest version of Elasticsearch is no longer open-source).


text:
Q: Adding a WindowListener to JFrame (Window Opened) This is my view class. The main class actually launches the program. The below code was used in the view lass since it contains the GUI and event handlers (action listeners).
public class TheaterView extends JFrame implements WindowListener{
    public void windowOpened(WindowEvent e) {
            displayMessage("WindowListener method called: windowOpened.");
    }
}

This is what I'm doing but it gives the error message: TheaterView is not abstract and does not override abstract method windowDeactivated(WindowEvent) in WindowListener.
Anyway, I implement the methods and get this (I get others too, but this is the only one I need):
@Override
    public void windowOpened(WindowEvent e) {
        throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
    }

However, it doesn't seem to work when I do anything like use the println command. I want it to do something once the program runs for the first time i.e. when the windows is opened.
I searched a lot but I couldn't figure it out yet. Any help would be appreciated :)
Code in main:
TheaterView theater = new TheaterView("Movie Theater");
theater.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
theater.setLocation(200, 200);
theater.pack();
theater.setVisible(true);

A: Did you overide all abstract methods from your listener ?
something like that  :
public void windowClosing(WindowEvent e) {
     aboutFrame.dispose();
}

public void windowClosed(WindowEvent e) {
}

public void windowIconified(WindowEvent e) {
}

public void windowDeiconified(WindowEvent e) {
}

public void windowActivated(WindowEvent e) {
}

public void windowDeactivated(WindowEvent e) {
}

A: Write a class which extends WindowsAdapter and add it to your JFrame via addWindowsListener.
See https://docs.oracle.com/javase/7/docs/api/java/awt/event/WindowAdapter.html for more information.
When working with listeners in Swing/AWT it is allways worth try to search for an according adapter to the listener you want to use.