text:
Q: How to determine lead ranking score with changeable variables An auctioneer holds an open reverse auction between two bidding parties. Prior to the auction starting, each party fills out a survey which is scored by the auctioneer, who scores it out of a possible 10 percentage points. Price bidding then commences and the bid price makes up the remaining 90 percentage points. Auction rank is determined by highest auction score using this calculation:

*

*let x = the current bidders lowest bid amount (lower is better)

*let y = the overall lowest current bid amount

*let z = the current bidders survey score

score = $(90 * (100 * (1 - (x - y) / y)) / 100) + z$
Party A scores 5 on the survey and bids £85, giving a rounded score of 95.00 and a ranking of 1(st). Party A score = $(90 * (100 * (1 - (85 - 85) / 85)) / 100) + 5 = 95$
Party B scores 8 on the survey and bids £90, giving a rounded score of 92.71 and a ranking of 2(nd). Party B score = $(90 * (100 * (1 - (90 - 85) / 85)) / 100) + 8 = 92.70588235294118$
Question: For valid values of x, y and z, what is the calculation that I can use to calculate the highest possible money amount that the 2nd place supplier can bid to move them into first ranking position?
Edit: what happens when Party B bids a new leading low amount of £80?
Party B still scores 8 on the survey and now bids £80 (which becomes the new value of $y$), giving a rounded event score of 98 and moves into 1st ranked position. Party B score = $(90 * (100 * (1 - (80 - 80) / 80)) / 100) + 8 = 98$
Party A still scores 5 on the survey and bid remains £85, giving a rounded event score of 89.38 and a new ranking of 2nd. Party A score = $(90 * (100 * (1 - (85 - 80) / 80)) / 100) + 5 = 89.375$
In the example above, I used a target bid price of £80. I would like to understand how to calculate the target bid price so that the difference in score between A and B is only 0.01.
(I can't figure this out because by changing the lead score you change the other score as well. I have made a number of attempts, none satisfactory, I either overshoot or undershoot the target price. Apologies for poor terminology or lack of formatting, mathematics is not my forte.)

A: Let $x_1$ and $x_2$ be the bids, $s_1$ and $s_2$ the corresponding survey scores and $m=\min(x_1,x_2)$. The bidders score respectively (I simplified a little your expression):
$$
s_1+90\left(2-{x_1\over m}\right)
\quad\hbox{and}\quad
s_2+90\left(2-{x_2\over m}\right)
$$
and these have the same value if
$$
s_1+90\left(2-{x_1\over m}\right)
=
s_2+90\left(2-{x_2\over m}\right)
$$
that is if:
$$
90{x_2-x_1\over m}=s_2-s_1.
$$
Suppose, without loss of generality, that $s_2\ge s_1$: the above equation then tells us that $x_2\ge x_1$ at the equilibrium point. We can thus substitute $m=x_1$ into that equation, to get the equilibrium equation:

$$ {x_2\over x_1}=1+{s_2-s_1\over 90}. $$

In your first example, $x_1=85$, $s_1=5$, $x_2=90$, $s_2=8$. Equilibrium is reached when
$$
{x_2\over x_1}=1+{3\over90}={31\over30}.
$$
With $x_1=85$ the second bidder can thus make a winning offer at $x_2<85\cdot{31\over30}=87.83$.
In your second example, $x_1=85$, $s_1=5$, $x_2=80$, $s_2=8$. Equilibrium equation is the same as above, thus with $x_2=80$ the first bidder should bid less then $80\cdot{30\over31}=77.42$ to get a better score.


text:
Q: For loop not returning all values DB Values:
a_id  a_user_id  a_date     a_intime    a_outtime
1       1       28/10/2014  12.30        1.30
2       1       29/10/2014  12.30        1.30
3       1       30/10/2014  12.30        1.30

The for loop returns only last  value. I want to return all a_date values.
   foreach ($query->result() as $row) {
     $users= array(
       'a_user_id' => $row->a_user_id,
       'a_date'=> $row->a_date,
       'a_intime'=>$row->a_intime,
       'a_outtime'=> $row->a_outtime
     );
   }

   $b=date('g:i a',$bd);
   $ttime=($a-$b/3600);
   $total_time=date(' g:i ',$ttime);

   $user['total_hour']= $total_time;
   return $user;

A: Your $users in the loop have to be an array
foreach ($query->result() as $row)
{
    $users[] = array(
        'a_user_id' => $row->a_user_id,
        'a_date'=> $row->a_date,
        'a_intime'=>$row->a_intime,
        'a_outtime'=> $row->a_outtime
     );
}

Since it is variable it only hold the last occurrence of the loop.

redpajama_set_name: RedPajamaStackExchange


text:
Q: eclipse go to actual implementation I have the following class structure. I would like to know how can I jump in eclipse to the actual implementation of th gethod printVar().
If I hover (hold down STRG) over the 2 method calls in main and click open implementation I get both Classes displayed. Is there a way to directly jump to the implementation in class B for this method call w.getWrapperVar().printVar()
public class A {

    private String var;

    public A(String a){
        this.var=a;
    }

    public void printVar(){
        System.out.println("class A print: " + this.var);
    }

}

public class B extends A{

    private String var;

    public B(String a){
        super(a);
        this.var=a;
    }

    @Override
    public void printVar(){
        System.out.println("class B print: " + this.var);
    }

}

public class Wrapper {

    private B wrapperVar;
    private A wrapperVar2;

    public Wrapper(String var){
        this.wrapperVar = new B(var);
        this.wrapperVar2 = new A(var);
    }

    // explicit Return Class A
    public A getWrapperVar(){
        return this.wrapperVar;
    }

    public A getWrapperVar2(){
        return this.wrapperVar2;
    }

}

public class main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub

        Wrapper w = new Wrapper("value");

        w.getWrapperVar().printVar();

        w.getWrapperVar2().printVar();

    }

}

A: Eclipse doesn't know that the implementation class is B, so it can't take you directly to B.
However, you can click on printVar and press Ctrl-G to search for all methods that might be the actual implementation.

A: After selecting a method call you can hit the F3 function key. This action will take you to the definition of the method. This definition may be in an interface.
When you are in that file you may want to hit Ctrl+T. This will bring up a type hierarchy showing the classes that implement the method you were looking for.
Hope this helps.


text:
Q: Tabbed fragment don't show listviews i try to combine tabbed fragment with listview. I fetch data by JSON and put it in listview in fragment but when i start app fragment don't show list view.
Actors.java
`
        public class Actors {
    private String name;
    private String description;
    private String dob;
    private String country;
    private String height;
    private String spouse;
    private String children;
    private String image;

    public Actors() {
        // TODO Auto-generated constructor stub
    }

    public Actors(String name, String description, String dob, String country,
            String height, String spouse, String children, String image) {
        super();
        this.name = name;
        this.description = description;
        this.dob = dob;
        this.country = country;
        this.height = height;
        this.spouse = spouse;
        this.children = children;
        //this.image = image;
    }

    public String getName() {
        return name;
    }

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

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public String getDob() {
        return dob;
    }

    public void setDob(String dob) {
        this.dob = dob;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }

    public String getHeight() {
        return height;
    }

    public void setHeight(String height) {
        this.height = height;
    }

}

`
ActorAdapter.java
`
    import java.io.InputStream;
    import java.util.ArrayList;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class ActorAdapter extends ArrayAdapter<Actors> {
    ArrayList<Actors> actorList;
    LayoutInflater vi;
    int Resource;
    ViewHolder holder;

    public ActorAdapter(Context context, int resource, ArrayList<Actors> objects) {
        super(context, resource, objects);
        vi = (LayoutInflater) context
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       // this.vi = LayoutInflater.from(context);
        this.Resource = resource;
        this.actorList = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // convert view = design
        View v = convertView;
        if (v == null) {
            holder = new ViewHolder();
            v = vi.inflate(Resource, null);
        //  holder.imageview = (ImageView) v.findViewById(R.id.ivImage);
            holder.tvName = (TextView) v.findViewById(R.id.tvName);
            holder.tvDescription = (TextView) v.findViewById(R.id.tvDescriptionn);
            holder.tvDOB = (TextView) v.findViewById(R.id.tvDateOfBirth);
            holder.tvCountry = (TextView) v.findViewById(R.id.tvCountry);
            holder.tvHeight = (TextView) v.findViewById(R.id.tvHeight);
            v.setTag(holder);
        } else {
            holder = (ViewHolder) v.getTag();
        }
        //holder.imageview.setImageResource(R.drawable.ic_launcher);
        //new DownloadImageTask(holder.imageview).execute(actorList.get(position).getImage());
        holder.tvName.setText(actorList.get(position).getName());
        holder.tvDescription.setText(actorList.get(position).getDescription());
        holder.tvDOB.setText("Pubblicato il: " + actorList.get(position).getDob());
        holder.tvCountry.setText(actorList.get(position).getCountry());
        holder.tvHeight.setText("Categoria: " + actorList.get(position).getHeight());
        return v;

    }

    static class ViewHolder {
        //public ImageView imageview;
        public TextView tvName;
        public TextView tvDescription;
        public TextView tvDOB;
        public TextView tvCountry;
        public TextView tvHeight;

    }

    /*private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
        ImageView bmImage;

        public DownloadImageTask(ImageView bmImage) {
            this.bmImage = bmImage;
        }

        protected Bitmap doInBackground(String... urls) {
            String urldisplay = urls[0];
            Bitmap mIcon11 = null;
            try {
                InputStream in = new java.net.URL(urldisplay).openStream();
            mIcon11 = BitmapFactory.decodeStream(in);
            } catch (Exception e) {
                Log.e("Error", e.getMessage());
                e.printStackTrace();
            }
            return mIcon11;
        }

        protected void onPostExecute(Bitmap result) {
            bmImage.setImageBitmap(result);
        }

    }*/
}

Main.java

    import info.androidhive.tabsswipe.adapter.TabsPagerAdapter;
    import android.app.ActionBar;
    import android.app.ActionBar.Tab;
    import android.app.FragmentTransaction;
    import android.os.Bundle;
    import android.support.v4.app.FragmentActivity;
    import android.support.v4.view.ViewPager;
public class MainActivity extends FragmentActivity implements
        ActionBar.TabListener {

    private ViewPager viewPager;
    private TabsPagerAdapter mAdapter;
    private ActionBar actionBar;
    // Tab titles
    private String[] tabs = { "Top Rated", "Games", "Movies" };

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

        // Initilization
        viewPager = (ViewPager) findViewById(R.id.pager);
        actionBar = getActionBar();
        mAdapter = new TabsPagerAdapter(getSupportFragmentManager());

        viewPager.setAdapter(mAdapter);
        actionBar.setHomeButtonEnabled(false);
        actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

        // Adding Tabs
        for (String tab_name : tabs) {
            actionBar.addTab(actionBar.newTab().setText(tab_name)
                    .setTabListener(this));
        }

        /**
         * on swiping the viewpager make respective tab selected
         * */
        viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                // on changing the page
                // make respected tab selected
                actionBar.setSelectedNavigationItem(position);
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {
            }

            @Override
            public void onPageScrollStateChanged(int arg0) {
            }
        });
    }

    @Override
    public void onTabReselected(Tab tab, FragmentTransaction ft) {
    }

    @Override
    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        // on tab selected
        // show respected fragment view
        viewPager.setCurrentItem(tab.getPosition());
    }

    @Override
    public void onTabUnselected(Tab tab, FragmentTransaction ft) {
    }

}

TopRatedFragment.java

    import android.app.ProgressDialog;
    import android.content.Context;
    import android.content.Intent;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.support.v4.app.Fragment;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.AdapterView;
    import android.widget.ListView;
    import android.widget.Toast;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.ParseException;
import java.util.ArrayList;

public class TopRatedFragment extends Fragment {
    ArrayList<Actors> actorsList;
    Context context=getActivity();
    ActorAdapter adapter;
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_top_rated, container, false);
        actorsList = new ArrayList<Actors>();
        new JSONAsyncTask().execute("http://www.technologici.it/api/get_recent_posts/");

        ListView listview = (ListView)rootView.findViewById(R.id.list);
        context = getActivity();
        listview.setAdapter(new ActorAdapter(getActivity(), R.layout.row, actorsList));
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long id) {
                // TODO Auto-generated method stub
                // Starting single contact activity
                Intent in = new Intent(getActivity(),
                        SingleContactActivity.class);
                in.putExtra("title", actorsList.get(position).getName());
                in.putExtra("author", actorsList.get(position).getCountry());
                in.putExtra("data", actorsList.get(position).getDob());
                in.putExtra("content", actorsList.get(position).getDescription());
                in.putExtra("category", actorsList.get(position).getHeight());
                //in.putExtra("image", actorsList.get(position).getImage());
                startActivity(in);
            }
        });
        setRetainInstance(true);
        return rootView;
    }

    class JSONAsyncTask extends AsyncTask<String, Void, Boolean> {

        ProgressDialog dialog;

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            dialog = new ProgressDialog(getActivity());
            dialog.setMessage("Caricamento...");
            dialog.setTitle("Contattando il server...");
            dialog.show();
            dialog.setCancelable(false);
        }

        @Override
        protected Boolean doInBackground(String... urls) {
            try {

                //------------------>>
                HttpGet httppost = new HttpGet(urls[0]);
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(httppost);

                // StatusLine stat = response.getStatusLine();
                int status = response.getStatusLine().getStatusCode();

                if (status == 200) {
                    HttpEntity entity = response.getEntity();
                    String data = EntityUtils.toString(entity);

                    JSONObject jsono = new JSONObject(data);
                    JSONArray jarray = jsono.getJSONArray("posts");

                    for (int i = 0; i < jarray.length(); i++) {
                        JSONObject object = jarray.getJSONObject(i);

                        Actors actor = new Actors();

                        actor.setName(object.getString("title"));
                        actor.setDescription(object.getString("content"));
                        actor.setDob(object.getString("date"));
                        JSONObject author = object.getJSONObject("author");
                        actor.setCountry(author.getString("name"));

                        JSONArray catarray = object.getJSONArray("categories");
                        JSONObject catobject = catarray.getJSONObject(0);
                        actor.setHeight(catobject.getString("title"));

                       // JSONArray imgarray = object.getJSONArray("attachments");
                       // JSONObject imgobject = imgarray.getJSONObject(0);
                        //actor.setImage(imgobject.getString("url"));

                        actorsList.add(actor);
                    }
                    return true;
                }

                //------------------>>

            } catch (IOException e) {
                e.printStackTrace();
            } catch (JSONException e) {
                e.printStackTrace();
            }
            return false;
        }

        protected void onPostExecute(Boolean result) {
            dialog.cancel();
           // adapter.notifyDataSetChanged();
            if (result == false) {
               Toast.makeText(getActivity(), "Unable to fetch data from server", Toast.LENGTH_LONG).show();
            }
        }

    }
}

Layout:
fragment_top_rated.xml

    <ListView
        android:id="@+id/list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        tools:listitem="@layout/row" >

    </ListView>

</LinearLayout>

row.xml

            <TextView
                android:id="@+id/tvName"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Tom Cruise"
                android:textColor="#166CED"
                android:textAppearance="?android:attr/textAppearanceLarge" />

            <TextView
                android:id="@+id/tvDateOfBirth"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#D64530"
                android:text="Date of Birth: July 3, 1962" />

            <TextView
                android:id="@+id/tvHeight"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="Height: 1.80 m"
                android:textColor="#D64530"
                android:textAppearance="?android:attr/textAppearanceSmall" />

            <TextView
                android:id="@+id/tvCountry"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:textColor="#D64530"
                android:text="United States" />
    <TextView
        android:id="@+id/tvDescriptionn"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="#009A57"
        android:text="Description"
        android:visibility="gone"/>
        </LinearLayout>

`
Can someone help me?


text:
Q: replace a string, but ignore the ones that are between quotes (command line) I am trying to replace a string in a text in a file, with a hexvalue with gsar, but I am in doubt if gsar can fix this :)
Original text:
print "this is a print" "print" "*:;PRINT'" PRINT " PRINT" " print " PrInT
After "gsar" did its thing it should be:
XXXX "this is a print" "print" "*:;PRINT'" XXXX " PRINT" " print " XXXX
(XXXX represents the hex value a5)
I only want the word 'print' (case insensitive) replaced with the hex value a5, but only if it is not between quotes.
Also, please note that the quotes are the same hexidecimal value in the source file! (0x22)
The code: gsar -s"print" -r:x22 -o file.txt replaces of course also the words that are between quotes and it doesnt replace the words that are not the same case.
Is this even possible? :)
I would be very happy if someone could help me with this.

A: For such replacement, it's better to match what we want to keep (i.e. the values between quotes) and assert that the failled then match the rest.
This can be done with the verbs (*SKIP) and (*FAIL).

*

*Ctrl+H

*Find what: "[^"]+"(*SKIP)(*FAIL)|\w+

*Replace with: XXXX

*CHECK Wrap around

*CHECK Regular expression

*Replace all
Explanation:
"           # double quote
[^"]+       # 1 or more non double quote
"           # double quote
(*SKIP)     # skip what was matched
(*FAIL)     # and consider the match failled
  |           # OR
\w+         # 1 or more word character

Screenshot (before):

Screenshot (after):


text:
Q: Have values of keys of dictionary mapped to their own key I have this python dictionary
dct = {'A': ['B', 'C'], 'B': ['D'], 'D': ['E'], 'C': ['F'], 'E': ['G']}
and i need a function to return it as
(A(B(D(E(G)))))(C(F))
I am unable to map the elements of each values to their own values. Any help would be appreciated.
Thank you

A: I'm not good at Python. I developed the function you want in Java. Hope you can convert it easily to Python.
import java.util.HashMap;
import java.util.Map;

public class MapTheMap {
    // Count of open parentheses
    static int parentheses = 0;

    public static void main(String[] args) {
        // Creating the map (i.e. dictionary in python)
        Map<Character, Character[]> map = new HashMap<>();
        map.put('A', new Character[]{'B', 'C'});
        map.put('B', new Character[]{'D'});
        map.put('D', new Character[]{'E'});
        map.put('C', new Character[]{'F'});
        map.put('E', new Character[]{'G'});

        // The start key is A, you can develop a logic to get the first key if you want to
        Character key = 'A';
        System.out.print("(" + key);

        recursion(map, key);
    }

    public static void recursion(Map<Character, Character[]> map, Character key) {
        // If the map contains the key, add 1 parenthesis, print the value of that key, and call the function again with value as a key (Call 1: Key A -> Value B -- Call 2: Key B --> ...)
        if (map.containsKey(key)) {
            for (Character valueKey : map.get(key)) {
                parentheses++;
                System.out.print("(" + valueKey);
                recursion(map, valueKey);
            }
        }
        // If the map doesn't contain the key, print close parentheses
        else {
            while (parentheses >= 0) {
                System.out.print(")");
                parentheses--;
            }
        }
    }
}

If there is something you don't understand, tell me and I'll try to edit the answer.


text:
Q: What is the meaning of "May I also take this opportunity of..."? What is the meaning of the following sentence in simple terms?

May I also take this opportunity of welcoming you on board at our company.

I searched the web but couldn't find something similar.


text:
Q: What sorts of problems cause Core Text crashes in calls to `sizeThatFits`? I've seen a handful of different crash reports coming in that all seem to be triggered when Core Text is calculating the size of some text in response to a call to [UIView sizeThatFits].  I suspect the crashes share some common cause, but I've only got a few stack traces and I don't know how to reproduce any of the problems myself, so I'm left guessing what sorts of problems could be triggering the crash.
In one case the crash is happening in an ABPeoplePickerNavigationController and the code on the stack is entirely Apple code. I've audited my code to make sure that UIKit/Core Text are only being used from the main thread.
I saw this tantalizing stack trace posted on the buzztouch forum, which looks very similar and also shares the "contacts" trigger.
frame #0: 0x007fe283 CoreText`TComponentFont::GetMinSideBearing(CGAffineTransform const&, bool) const + 43
frame #1: 0x0076b244 CoreText`TRun::GetLeftHangersGlyphCountAndWidth(long, unsigned long, TCharStream const&) const + 524
frame #2: 0x0077e7da CoreText`TLine::GetLeftHangersGlyphCountAndWidth(unsigned long const*) const + 234
frame #3: 0x0077e4b9 CoreText`TLine::GetBounds(unsigned long) const + 811
frame #4: 0x0077ace6 CoreText`CTLineGetBoundsWithOptions + 44
frame #5: 0x02059497 UIKit`-[UITableViewIndex _cacheAndMeasureTitles] + 984
frame #6: 0x02059ace UIKit`-[UITableViewIndex sizeThatFits:] + 131

On the forum, someone named Ofer left a post saying the crash had been fixed.  I'm hoping Ofer might be kind enough to share some details about what they discovered they were doing to trigger the crash!

A: In my case the problem appears to have stemmed from the way I was loading icons using the FontAwesomeKit library, as described in his "Known Issues". I had the good luck of getting my app into a state where I could pretty regularly reproduce the problem, and applying the suggested workaround made the problem go away (of course, for all I know it could just be hiding).


text:
Q: Combination of variational methods and empirical Bayes Suppose I have a posterior $p(z, \theta | y, \eta)$ with $y$ observed data, $z$ are hidden variables and $\theta$ are parameters, and $\eta$ is a vector of hyperparameters. I construct a mean field approximation to the posterior using coordinate ascent, i.e.
$$
q(z) \gets  \exp\left\{E_q(\log p(z, \theta | y, \eta) | z) + \mbox{const}\right\} \\
q(\theta) \gets \exp\left\{E_q(\log p(z, \theta | y, \eta) | \theta) + \mbox{const}\right\} $$
where $\mbox{const}$ makes each integrate to $1$. Iterate until convergence. My question is, if I want to do empirical Bayes, and (approximately) profile out $\eta$, is it valid to just augment this with an EM step
$$
\eta \gets \arg \max_\eta E_q \log(p(z, \theta | y, \eta))?
$$
Based on the evidence lower bound
$$
\log p(y | \eta) \ge E_q \log(p(z, \theta | y, \eta)) - E_q \log(q(z, \theta))
$$
it seems like I should be able to get away with this; optimizing the lower bound over $\eta$ is exactly the proposed EM step, so I'm still doing coordinate ascent on the lower bound.
I suspect that, if this works, it is the obvious thing to do for people who do variational inference regularly. Since variational methods are fast, my thought is that maybe I could do this to set hyperparameters before launching into a Gibbs sampler for exact (up to MCMC error) inference.
Update: I've toyed around with this a bit and found that adding the EM step can work okay, but in some situations it seems to increase sensitivity to bad local optima in the variational algorithm. Initializations of variational parameters that normally seem to work okay don't. If I instead only throw in the EM step every few iterations it works better, but then of course I slow down convergence. One approach that works okay is to "burn in" the variational algorithm using a method that I trust, and then add the EM step every iteration thereafter. I'm adding a bounty because I'm still looking for some good general advice.

A: Generally, in empirical Bayes, you maximise the marginal likelihood (also called model evidence, or the normalising constant of the posterior) with respect to the hyperparameters and plug this estimate of the hyperparameters into the posterior.
In Casella (2001) there is a derivation of an EM for empirical Bayes. Casella first writes the marginal likelihood $m(\eta ; y)$ as:
\begin{align}
m(\eta ; y) = \frac{p(y, \theta, z | \eta) }{p(\theta, z| y, \eta)}.
\end{align}
So the marginal likelihood is the joint distribution of model parameters $\theta$, latent parameters $z$ and data $y$ ($p(y,\theta,z| \eta)$) divided by the joint posterior distribution of the model and latent parameters given the data ($p(\theta,z| y, \eta$).
Take the logarithm and expectation with respect to the posterior $p(\theta, z| y, \eta^{(0)})$, for some starting value $\eta^{(0)}$:
$$
E [\log m(\eta ; y)| \eta^{(0)}] = E [\log p(y, \theta, z | \eta)|\eta^{(0)}] - E [\log p(\theta, z| y, \eta) | \eta^{(0)}].
$$
By Gibbs' inequality, $E [\log p(\theta, z| y, \eta) | \eta^{(0)}] \leq E [\log p(\theta, z| y, \eta^{(0)}) | \eta^{(0)}]$. So, maximising $E [\log p(\theta, z| y, \eta) | \eta^{(0)}]$ with respect to $\eta$ beyond $\eta^{(0)}$ increases the marginal likelihood such that the sequence
$$
\eta^{(k+1)} = \underset{\eta}{\arg \max} \, E [\log p(\theta, z| y, \eta) | \eta^{(k)}]
$$
converges to a local maximum of the marginal likelihood. In general, this expectation is not available in closed form. In Casella (2001), the expectation is approximated using $M$ Monte Carlo samples from the posterior $p(\theta, z| y, \eta^{(k)})$:
\begin{align}
E [\log p(\theta, z| y, \eta) | \eta^{(k)}] & \approx M^{-1} \sum_{m=1}^M \log p(y, \theta^{(m)}, z^{(m)} | \eta), \\
\theta^{(m)}, z^{(m)} & \sim p(\theta, z| y, \eta^{(k)}).
\end{align}
However, you could of course use other approximating methods, such as variational Bayes. The expectation then becomes:
$$
E [\log p(\theta, z| y, \eta) | \eta^{(k)}] \approx E_Q [\log p(\theta, z| y, \eta) | \eta^{(k)}],
$$
where the right-hand side expectation is now with respect to the variational posterior.
So, in the EM algorithm to find the hyperparameters that maximise the marginal likelihood, the E step is now a variational Bayes EM itself, so we have an EM within an EM. Which is basically what you describe.
That also explains why it doesn't work so well when you update the hyperparameters at every iteration: the expectation with respect to the variational Bayes posterior is not very accurate after one iteration. Updating the hyperparameters after the variational Bayes algorithm has converged gives better performance, since the expectation is more accurate.

A: One way of deciding how to run variational MLE is to look at how the experts do it.
In Blei's LDA code (http://www.cs.princeton.edu/~blei/lda-c/lda-c-dist.tgz), within the "run_em" function, the "lda_inference" function (inside "doc_e_step") repeatedly maximizes with respect to each $q$ distribution until convergence. After the $q$'s converge, the algorithm maximizes with respect to the parameters in "lda_mle".
The justification for this order is that by maximizing with respect to the $q$'s until convergence you get a better estimate of the expectations of hidden variables (or marginalized parameters) needed to maximize with respect to the parameters.
In standard EM, of course, the expectations you are computing are exact - which is the main difference between standard and variational EM - so this is not a concern.
From the perspective of EM as a maximization algorithm over the function $F(q,\theta)$ (www.cs.toronto.edu/~radford/ftp/emk.pdf) or from the perspective of maximizing the evidence lower bound, it is not clear that maximizing over the q's until convergence is best in terms of computationally efficiency because the algorithm will reach a local maximum no matter the order of maximization steps.


text:
Q: Yii - Saving Data between 3 tables I am working with Yii and jQuery Mobile. I currently have 3 tables: Users, Projects and ShareProjects. I have been able to create a function to display shared projects with that user, but I am struggling to assign users to projects. I have tried this code but have been unsuccessful so far.
public function actionShareProjects() {
   $model=new SharedProjects;
   if(isset($_POST['SharedProjects'])) {
      $model->attributes=$_POST['SharedProjects'];
      $model->project_id = "project_id";
      $model->user_id = "user_id";
      $model->sharedProject_id = "";
      $model->sharedCreateDate= date('Y-m-d G:i:s');
      if($model->save()) {
         echo json_encode(array('action'=>'success', 'message'=>''));
      } else {
          echo json_encode(array('action'=>'error', 'message'=>'Incorrect'));
      }
   }
}

In the project, there is a share button which takes the project id but I am trying to be able to allow the user to type an email in for the user you would like to share with.
I tried inputting it manually on postman but it failed, no errors came up but no data was saved. I used the correct input:
SharedProjects [user_id]
SharedProjects [project_id]
SharedProjects [sharedProject_id]
SharedProjects [sharedCreateDate]

A: change your code to this
public function actionShareProjects() {
   $model=new SharedProjects;
   if (isset($_POST['SharedProjects'])) {
      $model->attributes=$_POST['SharedProjects'];
      $model->sharedCreateDate= date('Y-m-d H:i:s');
      if($model->save()) {
         $this->sendResponse(array('action'=>'success', 'message'=>''));
      } else {
         $this->sendResponse(array('action'=>'error', 'message'=>'Incorrect'));
      }
   }
}

and make sure project_id,user_id are set and are of int type. To play around sending JSON response better way would be adding this function
public function sendResponse($data)
{
    header('Content-Type: application/json; charset=utf-8');
    echo CJSON::encode($data);
    exit;
}

in your controller and calling it for sending response.

A: If no error is comes up then  your data is right for your model's rule validation but may be this is creating error while saving in database,
Have you applied any constraint(like unique , not null) on your table's column. They are also restrict to save wrong data in table.


text:
Q: Building a bulk mail sender I want to build an application that will allow my customers to send marketing information by e-mail. This will be a carefully monitored tool used for legitimate bulk mailing only. It's going to have all of the necessary 'unsubscribe' functionality etc.
The solution will be built using VB.NET.
My question relates to the best way to actually send the e-mails. We have an SMTP server in our data centre which we can use. I'm thinking we could write some kind of multi-threaded windows service to monitor a database of e-mails to send, then make calls to the System.Net.Mail API to send through this server.
Is this going to give me the level of performance I need to send mail to thousands of users in a sensible time frame?
If not, should I be looking at doing things at a 'lower level', performing DNS lookups in one thread, sending direct to the relevant server on port 25 in another thread, etc?
Any pointers would be appreciated!

Not really an answer - but an update for anyone interested...  I'm currently looking at a product called ActiveMail from ActiveUp.
This seems to be an MTA (performing its own MX lookups and sending the mail directly), and it comes with a multi-threaded queuing application.

A: I think it's not that difficult to roll something like that on your own. It would take a day or so to build. But you should be much better off using something existing.
Still, some things I found important when doing Bulk-Email:
Don't use your own SMTP to send those.
Lookup the MX entries for your recipients and connect the SMTPClient to their SMTP, this gives you the benefit that you get an instant error msg back when the mailbox is not found or something else is wrong, and you don't stress your own server.
There was also a little bug in SmtpClient that gave me trouble because the hostname isn't a fully qualified domain name (as requested by the SMTP spec) but the machine name (and that's an internal field inside SmtpClient). Some SMTP servers take that seriously and want a domainname instead, so I ended up setting that field with reflection to a FQDN. (Hopefully this was changed since)

A: First off get a component to do the heavy lifting.
I would recommend: aspnetmail
Then setting up bulkmailing is as easy as downloading some example code.
WebMailer: Sending 1000s of emails from a web page without timing out.
The same vendor also supplies mx record checker / bounce mail checkers etc.
This solution isn't free but the time you save not chasing bugs / inconsistencies in the standard mail component will make this worth your while.
Oh and if you want a bulk mailer which sits on the desktop that is also supplied:
http://www.aspnetemail.com/rapidmailer/

A: The question is not precise enough but I will attempt to answer it anyway.  There are a few factors limiting you're options.  The best "way" is really up to your circumstances. What deadline are you working against?
Implementing a large, low-level, multi-threaded mail-sending system will take a lot of time compared to the other option you mentioned. Sure, writing the whole thing from scratch is far more elegant than using the SMTP server and the .NET library for sending the mails.
There is also the matter of the bandwidth between the different data. Will the .NET app and the database be running on the same server as the SMTP? If not, how will the pipeline of bandwidth limit the maximum of mails sent per second?
Personally I am a big fan of keeping it simple. Reusing available software is a smart move if the clock is ticking. How often will you be sending thousands of mails? That interval will define if the time frame is sensible or not. Is it so small that you could end up with the system still working on the first "batch" when another version is ready to be sent out?


text:
Q: JavaScript - Append to an element that cannot contain children using jQuery I have several
 elements for example, each one has the same class and contains 2 sibling. I want to append an element to the last sibling but that element cannot contain a children...
E.g

      <input type="checkbox"/> Checkbox 1

      <input type="checkbox "/> Checkbox 2

      <input type="checkbox "/> Checkbox 3

So my jQuery code is the following but it didn't work...
$(function() {
  var div = $("div"),
      $element = '';
  div.each(function(i, el) {
    if (el.hasClass("class-name")) {
      $(el).nextAll().eq(1).append($element);
    }
  });
});

I've included an IF statement for veryfication and only append the
  element to the target (here I'm pointing to the <input> element as
  the target) within the
 only so the other elements will not be
  included.

Any idea how to achieve that in this case?
Thanks.

A: Not knowing your exact intent regarding the "children" comment I present three
This appends TO the last element:
$(function() {
  var div = $("div.class-name"),
    $element = '';
  div.last().append($element);
});

This appends a new span AFTER the last one:
$(function() {
  var div = $("div.class-name"),
    $element = '';
  div.last().after($element);
});

This replaces the last elements content with the span:
$(function() {
  var div = $("div.class-name"),
    $element = '';
  div.last().html($element);
});

NOTE After your edit, I made the assumption you want to append a span after the last checkbox elements label so this does that:
$(function() {
  var div = $("div.checkbox");
  var lastelementwithnochildren = div.find('*:not(:has("*"))').last();
  $element = 'howdy';
  lastelementwithnochildren.parent().append($element);
});

IF you want the span before the label text just after the input, change the last line to:
lastelementwithnochildren.after($element);


text:
Q: Google Earth API for Android I want to ask if Google Earth API is avaialble for developing android application.
If google earth api is not available for android, are there any map api which can be used off network on android?

A: If you just want to open a location you can use the intents for searching on Google Earth. See How to fly to a location in Google Earth from your android app for examples

A: No, there's no offline API on Android or Google Earth API. You can use the regular Android Google Maps package api, eventually in combination with the Google Maps web api, in case you need routing and directions as well.
Until SDK 0.9, Google had a navigation package/api included, but that has been dropped; I guess due to licensing issues. Note that real-time turn-by-turn navigation on Android is not allowed and against the ToS, while route navigation in general can be done, but only in combination with the maps web api.

A: You can use the open source AndNav library for offline mapping.  The API is very similar to the Android Google Maps one.  The code can be found here: http://code.google.com/p/andnav/
Their wiki has a lot of good information and downloads for map tile packs.


text:
Q: How to remove leafs from a binary tree represented with list of lists? I have a binary tree represented with nested lists:
[[[[], []], [[], []]], [[], [], []]]
And I want to write a function which removes the leafs (the empty lists) from it with recursion.
I tried with this but it doesn't even run. Could someone help me how to start?
def removeLeaf(tree):
    for i in tree:
        if type(tree[i]) is list:
            return removeLeaf(tree[i])
        elif tree[i] == []:
            tree.pop(i)
            return removeLeaf(tree)

input:
[[[[], []], [[], []]], [[], [], []]]
output:
[[[], []], []]

A: You shouldn't call resursion in the first part of if, because you are removing the empty list that is a leaf. Also the for sentence must be changed.
Here's the code:
def removeLeafs(tree):
    for i in range(0,len(tree)-1):
        if len(tree[i]) == 0:
            tree.pop(i)
        else
            removeLeafs(tree[i])


text:
Q: Поиск максимумов в скользящем окне Pandas DataFrame Недавно начал изучать Python3.
Суть проблемы. Есть таблица из нескольких столбцов и несколько десятков тысяч строк. Пусть столбец называется "А".
Нужно найти максимум в столбце "А" за 100 предыдущих строк и записать этот максимум в новый столбец "B". Записи в столбце "B" начинаются со 101 строчки. На 102 строчке столбца "B" должен быть максимум из диапазона 2-101 столбца "А". И так до самого конца таблицы.
Также нужно определять позицию найденного в столбце А максимума, например 24 место в диапазоне 1-100. (Если несколько одинаковых значений, то брать самое верхнее). И находить сумму в диапазоне 24-100 по столбцу "X". Эту сумму записывать в новый столбец "C". Записи в столбце "C" начинать также со 101 строки. Если для следующей строки в диапазоне 2-101 максимум в столбце остался на 24 месте, то сумма по столбцу "Х" рассчитывается по строкам 24-101 и записывается в ячейку С-102. И так до самого конца таблицы, как со столбцом "B".
В Excel такие вещи делаются элементарно, а в Python не могу найти как это сделать.

A: Для того чтобы найти максимум в скользящем окне в Pandas существует метод Series.rolling().
Исходный DataFrame:
In [134]: df = pd.DataFrame({'A':np.random.randint(100, size=30)})

In [135]: df
Out[135]:
     A
0   49
1   93
2   62
3   40
4   59
5   52
6   97
..  ..
23  30
24  36
25  46
26  38
27  76
28  39
29  63

[30 rows x 1 columns]

пример использования метода .rolling(window=3):
In [136]: df['B'] = df['A'].rolling(3).max()

In [137]: df
Out[137]:
     A     B
0   49   NaN
1   93   NaN
2   62  93.0
3   40  93.0
4   59  62.0
5   52  59.0
6   97  97.0
..  ..   ...
23  30  66.0
24  36  53.0
25  46  46.0
26  38  46.0
27  76  76.0
28  39  76.0
29  63  76.0

[30 rows x 2 columns]


text:
Q: How do I integrate an MVC rest service with Spring Integration? My goal is to use Spring Integration to control the flow between multiple systems and add some logging and monitoring.
One of the systems is a RESTful MVC service.  I read the Spring Integration document here: http://static.springsource.org/spring-integration/reference/htmlsingle/#http-inbound.  There is a line here that I don't understand:

If you are running within a Spring MVC application, then the aforementioned explicit servlet definition is not necessary. In that case, the bean name for your gateway can be matched against the URL path just like a Spring MVC Controller bean.

Can someone provide an example of integrating a Spring MVC restful endpoint with Spring Integration?  Ideally it would be nice to reuse the mapping definitions in my Controller that I've already defined, but perhaps that isn't the intended use case?

A: The discussion there is to route HTTP requests to an http inbound gateway.
If you already have a Controller, simply inject a MessagingGateway to invoke your Spring Integration flow...
http://static.springsource.org/spring-integration/reference/html/messaging-endpoints-chapter.html#gateway


text:
Q: MS Excel- extract special character from a cell I have an excel with one column (say column A) having different data in no specific format. Some of the cells in the column contains some special characters too. I need to find which cell contains "*", "@", "_" and "!". and publish those characters in column B.
For example
Column A contains-
A1- ABVC_KL.....
A2- !1223.....
A3- UIL%%$00.....
A4- JOHN@456.....
A5- 9_90*YY!P.....

Then, the formula in column B should give this result in column B:
B1- _.....
B2- !.....
B3- null.....
B4- @.....
B5- _*!.....

Can someone help me with ths?

A: For each character you want to find, create a new column (you can hide/group them afterwards), and create a formula like =IFERROR( IF(SEARCH("!",A2)>0,TRUE),"").
If you have a lot of character to check for, reference the string you want to search for from row 1 (example) like this =IFERROR( IF(SEARCH(B$1,$A2)>0,TRUE),""). This way you can copy the formula and it will always reference column A text values and row 1 string values to find.
This will search for the string "!" in cell A2 and give its location. You dont need to know the exact location, just if there is a character like this, so IF >0 provides a TRUE value if there is a "!" anywhere. If there is none, an error is displayed and turned into an empty string "" with the IFERROR().


text:
Q: Convert base 64 file to text or pdf file in r I am using R, version 3.3.2.. I have downloaded base64 file from API. Here is output (base64) file (all file have 27 pages so I put just liitle part of it):
list(structure(list("584959666b2e5f32bc43fad1", "584959666b2e5f32bc43fad1.pdf",
    91572L, "[encoded data, 4487 characters] ",
    "application/pdf"), .Dim = c(1L, 5L), .Dimnames = list(NULL,
    c("dokumentId", "filename", "lenght", "content", "contentType"
    ))))

I would like to convert this file to text or pdf file, and then parse it. I have tried to use two packages but without success: base64enc and base64.
For example I have tried:
text <- document[[1]][[4]]
plain_text <- base64enc::base64decode(text)
plain_text <- rawToChar(plain_text)

and
text <- document[[1]][[4]]
test_file <- write.csv2(text, "E:/somepath/test_file.csv")
tmp <- tempfile()
base64::decode(input = test_file, output = tmp)

, but without success. Could you please help me with this issue?


text:
Q: Custom List Row in Android leanback browser fragment in last 4 days i search through internet and android leanback library code to find my problem's solution, but i can not figure it out. in browser fragment of android leanback library it's explained how to have ListRowPresenter with two rows or more. but i want a row in browser fragment that look like something like this sketch:

any idea can helps a lot. thanks


text:
Q: Send array of JSON objects with TNetHTTPRequest.Post() I need to send a post request containing JSON like this:
[ { "sku": "AS12AS11S", "estoque": 3}, { "sku": "ASKD123F4", "estoque": 10} ]

I have found examples inserting a single JSON object.  How can I set the params to send more than one JSON object?
This is the actual code that I have.
var
  NetHTTPClient : TNetHTTPClient;
  parametres : Tstringlist;
begin
  parametres := tstringlist.Create;
  NetHTTPClient := TNetHTTPClient.Create(nil);

  parametres .Add('nom_logiciel='+UTF8Encode('éè'));
  parametres .Add('emplacement='+EncodeURIComponent('éè') );
  parametres .Add('version='+ 'éè');

  NetHTTPClient.ContentType := 'application/json';
  NetHTTPClient.AcceptEncoding := 'UTF-8';

  NetHTTPClient.post('http://metaclients.xxx.fr/xxx',parametres,nil,TEncoding.UTF8).ContentAsString(tencoding.UTF8);

  parametres .Free;
  NetHTTPClient.Free;
end;

A: Use the overloaded version of TNetHTTPClient.Post() that takes a TStream as input rather than a TStrings.  Then you can store your JSON into a suitable TStream as needed, such as TStringStream.
var
  NetHTTPClient : TNetHTTPClient;
  parametres : TStringStream;
begin
  NetHTTPClient := TNetHTTPClient.Create(nil);
  try
    NetHTTPClient.ContentType := 'application/json';
    NetHTTPClient.AcceptEncoding := 'UTF-8';

    parametres := TStringStream.Create('[{"sku": "AS12AS11S", "estoque": 3}, {"sku": "ASKD123F4", "estoque": 10}]', TEncoding.UTF8);
    try
      Result := NetHTTPClient.Post('http://metaclients.xxx.fr/xxx', parametres).ContentAsString(TEncoding.UTF8);
    finally
      parametres.Free;
    end;
  finally
    NetHTTPClient.Free;
  end;
end;


text:
Q: Python IDE and gathering runtime statistics (variable types and other) It occured to me after reading this blog post and watching related video: http://steve-yegge.blogspot.com/2008/05/dynamic-languages-strike-back.html
Is there any Python IDE that gathers Python program runtime statistics and uses it to provide better code completion, variable type determining etc.?
Or, if not IDE, is there any working tool that gathers such information and can be used by programmer to do something useful?

A: AFAIK there is no tool that is able to do all this magic at once, but...

*

*eclipse can do some inference about basic types, e.g. classes and instance members, functions, can do some autocompletion

*semantic & emacs also does it

*pywin, IDLE and pycrust introspect imported modules, also providing autocompletion

*pylint does extensive static checks, apart from other functionality


text:
Q: How to check Date with Joda-time to Save and sort data day by day? I'm setting up an app to save my moods.
My code look like that
DateTime dt = new DateTime();
        DateTimeFormatter fmt = DateTimeFormat.forPattern("EEEE, dd").withLocale(Locale.FRANCE);
        day = fmt.print(dt);

It's perfect to get the date, but now I would like to check when the date change, to not overwrite my last mood.
I would like to save my moods, day by day.
I'm using SharedPreferences to save my moods and my code look like that:
private void saveDateTime(){
        SharedPreferences sharedPreferences = getContext().getSharedPreferences(MY_PREFS, Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        DateTime dt = new DateTime();
        DateTimeFormatter fmt = DateTimeFormat.forPattern("EEEE, dd").withLocale(Locale.FRANCE);
        day = fmt.print(dt);
        editor.putString(DATE, day);
        editor.apply();
        editor.commit();
    }

If SomeOne have an idea to help me, do not hesitate ;)


text:
Q: Customize legend and color scale in interactive charts `altair` I want an interactive chart, so I first define
click = selection_multi(fields=['species'])

Inside the encode() method the following works well:
color = condition(click,
                  'species',
                  value('gray'))

But I'd rather use my own color palette and I do not want a legend. I can achieve this with the following.
color = Color('species',
              scale=Scale(range=palette),
              legend=None)

But now I have no selection! Can I have them both?

A: To get a multi-selection, your own palette and no legend, simply specify all of these inside color().
Working Code
import altair as alt
from vega_datasets import data
iris = data.iris()

click = alt.selection_multi(fields=['species'])
palette = alt.Scale(domain=['setosa', 'versicolor', 'virginica'],
                  range=['lightgreen', 'darkgreen', 'olive'])

alt.Chart(iris).mark_point().encode(
    x='petalWidth',
    y='petalLength',
    color=alt.condition(click,
                        'species:N', alt.value('lightgray'),
                        scale=palette,
                        legend=None)
).properties(
    selection=click
)

produces:

And if you click on any point, that whole species will get selected and colored according to the color condition. (Selected points assume color from the palette and the unselected ones are shown in grey.)


text:
Q: Renumbering and prefixing equations, figures, and tables in the last section I'm writing a manuscript that will eventually be submitted for publication in an American Chemical Society (ACS) journal. For this, I'm using the achemso document class.
Manuscript submissions to the ACS typically consist of two parts: a main paper and a file of Supporting Information (SI). Typically the main paper and the SI would be in separate .tex files, and output to separate .pdf files. However, I would like to draft the main paper and SI in the same file.
This may seem like an odd request -- what's wrong with two separate files? -- but having only one file for the manuscript drafting/preparation process would be helpful to me and my supervisor.
So, my questions are:

*

*Is it possible to reset to 1 the number counters for equations,
figures, and tables in the final section of my .tex file?

*In addition, is it possible to prefix, with a letter "S", the number
counters for equations, figures, and tables in the final section of
my .tex file?
In other words, I'd like the equations in the Supporting Information (i.e., the last section of the file) to be numbered (S1), (S2), (S3), etc. Similarily, I'd like the figures in the Supporting information to be numbered Figure S1, Figure S2, Figure S3, etc. And similarily for tables: Table S1, Table S2, etc.
Here is my MWE, which makes use of the achemso document class, along with a condensed version of its output:
\documentclass[journal=jacsat,manuscript=article]{achemso}

\usepackage{amsmath,siunitx,booktabs,graphicx}
\usepackage[capitalize]{cleveref}
\sisetup{%
  detect-family, detect-shape, detect-weight, detect-mode,
  product-units = power,
  list-final-separator = {, and },
  retain-explicit-plus,
  input-comparators = {<=>\approx\ge\geq\gg\le\leq\ll\sim\lesssim\gtrsim}
}

\author{First A. Author}
\affiliation[University A]{Department, University A, Address A}
\author{Second B. Author}
\affiliation[University B]{Department, University B, Address B}
\author{Third C. Author}\email{thirdauthor@univc.edu}
\affiliation[University C]{Department, University C, Address C}

\title{Article Title}

\SectionNumbersOn

\begin{document}

\begin{abstract}
Abstract goes here.
\end{abstract}

\section{Introduction}

\section{Methods}

\section{Results and Discussion}
% Equations in the main paper
\begin{equation}\label{eq:result1}
  \begin{aligned}
    A &= A_1 + A_2 + A_3 \\
    A_{\alpha} &= A_{\alpha 1} + A_{\alpha 2} + A_{\alpha 3}
  \end{aligned}
\end{equation}

\begin{subequations}\label{eq:result2}
  \begin{align}
    B &= B_1 + B_2 + B_3\label{eq:result2:a} \\
    B_{\beta} &= B_{\beta 1} + B_{\beta 2} + B_{\beta 3}\label{eq:result2:b}
  \end{align}
\end{subequations}

% Figure in the main paper
\begin{figure}[!h]
  \centering
  \includegraphics[width=0.25\textwidth]{example-image}%
  \caption{A figure in the main paper.}\label{fig:result1}
\end{figure}

% Table in the main paper
\begin{table}
  \centering
  \begin{tabular}{lS[table-format=1.2,table-number-alignment=left]}
    \toprule
    & {Quantity} \\
    \midrule
    Trial A & 1.11 \\
    Trial B & 2.22 \\
    \bottomrule
  \end{tabular}
  \caption{A table in the main paper.}
  \label{tbl:result1}
\end{table}

\begin{itemize}
  \item REFER TO EQUATIONS: Refer to \cref{eq:result1}. Refer to \cref{eq:result2}.
Let's look more closely and refer to subequations: \cref{eq:result2:a,eq:result2:b}.
  \item REFER TO FIGURES: Refer to \cref{fig:result1}.
  \item REFER TO TABLES: Refer to \cref{tbl:result1}.
\end{itemize}

\section{Conclusion}

\begin{suppinfo}
  Advertisement for, and description of, Supporting Information goes here.
\end{suppinfo}

\begin{acknowledgement}
  The authors thank funding sources.
\end{acknowledgement}

\begin{tocentry}
  \includegraphics[width=\textwidth]{example-image}
  Graphical TOC goes here.
\end{tocentry}

\clearpage
\section*{Supporting Information}
% Equations in the Supporting Information

% Figure in the Supporting Information
\begin{figure}[!h]
  \centering
  \includegraphics[width=0.25\textwidth]{example-image}%
  \caption{A figure in the Supporting Information.}\label{fig:si:result1}
\end{figure}

% Table in the Supporting Information
\begin{table}
  \centering
  \begin{tabular}{lS[table-format=1.2,table-number-alignment=left]}
    \toprule
    & {Quantity} \\
    \midrule
    Trial A & 1.11 \\
    Trial B & 2.22 \\
    \bottomrule
  \end{tabular}
  \caption{A table in the Supporting Information.}\label{tbl:si:result1}
\end{table}

\end{document}

A: Change the format of the counter representations and reset them to 0.
\clearpage
\renewcommand{\theequation}{S\arabic{equation}}
\renewcommand{\thetable}{S\arabic{table}}
\renewcommand{\thefigure}{S\arabic{figure}}
\setcounter{equation}{0}
\setcounter{table}{0}
\setcounter{figure}{0}

\section*{Supporting Information}

Here's a full example. I changed [!h] into [!htp] not only to avoid warnings.
\documentclass[journal=jacsat,manuscript=article]{achemso}

\usepackage{amsmath,siunitx,booktabs,graphicx}
\usepackage[capitalize]{cleveref}
\sisetup{%
  detect-family, detect-shape, detect-weight, detect-mode,
  product-units = power,
  list-final-separator = {, and },
  retain-explicit-plus,
  input-comparators = {<=>\approx\ge\geq\gg\le\leq\ll\sim\lesssim\gtrsim}
}

\author{First A. Author}
\affiliation[University A]{Department, University A, Address A}
\author{Second B. Author}
\affiliation[University B]{Department, University B, Address B}
\author{Third C. Author}\email{thirdauthor@univc.edu}
\affiliation[University C]{Department, University C, Address C}

\title{Article Title}

\SectionNumbersOn

\begin{document}

\begin{abstract}
Abstract goes here.
\end{abstract}

\section{Introduction}

\section{Methods}

\section{Results and Discussion}
% Equations in the main paper
\begin{equation}\label{eq:result1}
  \begin{aligned}
    A &= A_1 + A_2 + A_3 \\
    A_{\alpha} &= A_{\alpha 1} + A_{\alpha 2} + A_{\alpha 3}
  \end{aligned}
\end{equation}

\begin{subequations}\label{eq:result2}
  \begin{align}
    B &= B_1 + B_2 + B_3\label{eq:result2:a} \\
    B_{\beta} &= B_{\beta 1} + B_{\beta 2} + B_{\beta 3}\label{eq:result2:b}
  \end{align}
\end{subequations}

% Figure in the main paper
\begin{figure}[!htp]
  \centering
  \includegraphics[width=0.25\textwidth]{example-image}%
  \caption{A figure in the main paper.}\label{fig:result1}
\end{figure}

% Table in the main paper
\begin{table}[!htp]
  \centering
  \begin{tabular}{lS[table-format=1.2,table-number-alignment=left]}
    \toprule
    & {Quantity} \\
    \midrule
    Trial A & 1.11 \\
    Trial B & 2.22 \\
    \bottomrule
  \end{tabular}
  \caption{A table in the main paper.}
  \label{tbl:result1}
\end{table}

\begin{itemize}
  \item REFER TO EQUATIONS: Refer to \cref{eq:result1}. Refer to \cref{eq:result2}.
Let's look more closely and refer to subequations: \cref{eq:result2:a,eq:result2:b}.
  \item REFER TO FIGURES: Refer to \cref{fig:result1}.
  \item REFER TO TABLES: Refer to \cref{tbl:result1}.
\end{itemize}

\section{Conclusion}

\begin{suppinfo}
  Advertisement for, and description of, Supporting Information goes here.
\end{suppinfo}

\begin{acknowledgement}
  The authors thank funding sources.
\end{acknowledgement}

\begin{tocentry}
  \includegraphics[width=\textwidth]{example-image}
  Graphical TOC goes here.
\end{tocentry}

\clearpage
\renewcommand{\theequation}{S\arabic{equation}}
\renewcommand{\thetable}{S\arabic{table}}
\renewcommand{\thefigure}{S\arabic{figure}}
\setcounter{equation}{0}
\setcounter{table}{0}
\setcounter{figure}{0}

\section*{Supporting Information}
% Equations in the Supporting Information
\begin{equation}
x=y
\end{equation}

% Figure in the Supporting Information
\begin{figure}[!htp]
  \centering
  \includegraphics[width=0.25\textwidth]{example-image}%
  \caption{A figure in the Supporting Information.}\label{fig:si:result1}
\end{figure}

% Table in the Supporting Information
\begin{table}
  \centering
  \begin{tabular}{lS[table-format=1.2,table-number-alignment=left]}
    \toprule
    & {Quantity} \\
    \midrule
    Trial A & 1.11 \\
    Trial B & 2.22 \\
    \bottomrule
  \end{tabular}
  \caption{A table in the Supporting Information.}\label{tbl:si:result1}
\end{table}

\end{document}


text:
Q: Calling the event when it is connected to Internet I want to handle the event, which will check if an internet connection and if it is I will call this piece of code:
/** Called when the user clicks the ImageView */
    public void mapOfWasteActivity() {
        mapOfWaste = (ImageView)findViewById(R.id.imageViewMap);
        mapOfWaste.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Main_Activity.this, MapOfWasteActivity.class);
                startActivity(intent);
            }
        });
    }

and if you do not have a connection to this cause me:
Intent intent = new Intent(Main_Activity.this, Test.class);
startActivity(intent);

A: Use this function. It will return true if connected or connecting.
public  boolean isNetworkConnected() {
            boolean isConnected=false;
            try{
                ConnectivityManager cm =
                    (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);

                NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
                isConnected = activeNetwork != null &&
                                  activeNetwork.isConnectedOrConnecting();
                return isConnected;
            }
            catch(Exception e)
            {
                e.printStackTrace();
            }
            return isConnected;
        }

A: Try this code
/** Called when the user clicks the ImageView */
public void mapOfWasteActivity() {
    mapOfWaste = (ImageView)findViewById(R.id.imageViewMap);
    mapOfWaste.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

             if(isNetworkConnected()){
              Intent intent = new Intent(Main_Activity.this, MapOfWasteActivity.class);
            startActivity(intent);

             }else{

            Intent intent = new Intent(Main_Activity.this, Test.class);
             startActivity(intent);

             }

        }
    });
}

public  boolean isNetworkConnected() {
        boolean isConnected=false;
        try{
            ConnectivityManager cm =
                (ConnectivityManager)this.getSystemService(Context.CONNECTIVITY_SERVICE);

            NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
            isConnected = activeNetwork != null &&
                              activeNetwork.isConnectedOrConnecting();
            return isConnected;
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
        return isConnected;
    }


text:
Q: Is it better to use multiple databases when you are managing independent sets of things in MongoDB? If, as an example, you have a blogging website done with MongoDB to store data
Is it better to have a database per blogger? given that their blogs and comments are completely independent from other bloggers.   Or just lump everything together? or it doesn't make too much difference?
I'm imagining the same web app (not independent webs/urls per blogger) is used by all bloggers.  So when someone logs in / accesses the blog the code would find the right database to use and haul data out it.
Does this have any downsides?  is this normal for handling these kinds of things?

A: I am making plenty of assumptions about your needs.  But, generally, there are 3 paths to multi-tenant apps in MongoDB:
Single collection per customer; never, ever do this.
Single database per customer.  Good.  You will trade off free space if your product is on the freemium model.  Either way, you will want to run with "smallfiles" option.  As stated, you will build the routing system for your environment.  Thus, you will want to connect to the proper database for the proper customer.
customer_id key per document + path slug.  Good.  The trade off here is recovery of free space.  Traditionally, MongoDB does not recover space used by deleted documents.  Thus customers creating and deleting blog posts would create unused space.  By using 'usePowerOf2Sizes' collections, you will recover disk space of deleted documents.  However, 'usePowerOf2Sizes' creates bloated padding space.
To get over the disk space padding, take a look at the compression used here: http://blog.appsignal.com/blog/2013/07/30/taming-mongodb-disk-usage.html
Recap, I would recommend using customer_id plus the compression.  It gives you the best of both worlds.

A: As stated in the comments under the original question, there's really no performance benefit to splitting up your MongoDB store into separate databases per blogger, due to the overhead of having each database and minimum storage.
On the flipside: You are going to make some cross-user analysis more difficult for yourself. As a very simple example, based on your blogging example: Imagine you want to look at average post count per user. This is pretty simple if your users (and posts) are in the same database (typically in the same collections), and you can likely use the aggregation framework for this task. This task will not be so straightforward with an unbounded number of databases, where you'll need to first enumerate all databases, then perform your aggregations/averaging once per database. This could end up being a slower operation than within a single-database architecture.
Having said all that: You still might have some reason to split data across databases. Maybe you have to separate data due to legal reasons, or to ensure customers that their sensitive data won't be commingled with other companies' data. Maybe your customer needs full read/write access to their database, and so you use per-database configuration as a security boundary. I'm sure there are other reasons as well...

A: It is perfectly normal to allocate 100's of databases if that is all you will see.
Database separation can have many benefits. They can be sharded independantly, since sharding occurs on database level. Databases also have the upside of being completely isolated instances (including locks) of the data within them (good example: space allocation occurs on database level).
This means they can be moved around the network as users data is accessed more and since a single users data might not be that big it would be easier than moving all of your users data to a more powerful node.
However, you must consider the problematic sides in the application of managing the connections to each database. There will be over head on it and you will need to have far more complex coding than what is considered standard.
Considering space, you will not see a drastic usage of space. The most problematic part of using separate databases is the journal allocation. Every collection you use in separate databases will also, of course, pre-allocate itself but this is actually considered one of the upsides to using database separation (movement of databases between nodes, isolation).
So the space problem is really only a problem if your scenario makes it one.

is this normal for handling these kinds of things?

For a normal blogger site, no, and I do not know enough about the complexities of your scenario to say any different. Normal operation would be to lump everything together, since you could see into the region of 1,000's maybe 1,000,000's of users and database separation just won't scale over that very well.


text:
Q: C++ Treiber Stack and atomic next pointers The "Treiber Stack" is generally one of the simplest lock-free data structures, and so it is often used when teaching introductions to lock-free algorithms.
I've seen many implementations of Treiber Stacks using C++ atomics.  The algorithm itself is trivial, so the real challenge is handling all the other incidental details of lock-free data-structures, such as providing some way of performing safe memory reclamation, avoiding the ABA problem, and allocating nodes in a lock-free manner.  This can be solved in various ways, such as using atomic reference counting, hazard pointers, counted/tagged pointers to avoid ABA, and using a lock-free memory pool.
But ignoring all those details and focusing on the simple algorithm itself, one question that occurred to me is the fact that every implementation of Treiber Stacks that I can recall implements the node class using atomic next pointers.  For example:
struct Node
{
  T value;
  std::atomic<Node*> next;
};

But after thinking about the algorithm, I'm not sure why the next pointer needs to be atomic.
The general PUSH algorithm (ignoring lock-free allocation, safe memory reclamation, backoff, ABA avoidance, etc.) is:
Node* n = new Node();
Node* front = m_front.load();
n->next.store(front);
while (!m_front.compare_exchange_weak(front, n))
{
  n->next.store(front);
}

The general POP algorithm (again, ignoring all details except the actual algorithmic logic) is:
Node* front = m_front.load();
Node* next = front->next.load();
while (!m_front.compare_exchange_weak(front, next))
{
  next = front->next.load();
}

And here is an real-world example implementation of the PUSH algorithm:
https://github.com/khizmax/libcds/blob/master/cds/intrusive/treiber_stack.h#L736
So I don't understand why the next pointer even needs to be atomic.  Most C++ implementations use relaxed loads/stores with the next pointer, so we don't need any memory fences when reading/writing to the next pointer, but my thinking is that it doesn't need to be atomic at all.
From what I can see, at no time is the next pointer of any node concurrently written to.  Rather, the next pointer may be concurrently loaded, but I never see any opportunity for the algorithm to concurrently load+store or concurrently store+store.  In fact, in the PUSH algorithm, the next pointer is never accessed concurrently at all.
So it seems to me that next pointers are effectively "read-only" when accessed concurrently, so I'm not sure why it would even be necessary to make them atomic at all.
Yet, every C++ implementation of a Treiber Stack I've seen makes the next pointers to be atomic.  So am I correct, or is there some reason the next pointer must be made atomic?

A: If it was as simple as the code you showed, you'd be right.  A Node is never modified after a pointer to it is published.  But you left out the part where Nodes are cleaned up so they can be garbage-collected.  (You can't just delete after popping; another thread could still have a pointer to it and not yet have read it.  This is a tricky problem for RCU as well.)
This is the function you left out, called after a CAS in pop succeeds:
protected:
    void clear_links( node_type * pNode ) CDS_NOEXCEPT
    {
        pNode->m_pNext.store( nullptr, memory_model::memory_order_relaxed );
    }

Here's an ordering where a reader reads a next while it's being written:
A: Node* front = m_front.load();
                                 B: Node* front = m_front.load();  // same value
A: Node* next = front->next.load();
A: m_front.compare_exchange_weak(front, next) // succeeds, no loop
A: clear_links(front);  // i.e. front->next.store(nullptr);

                                 B: front->next.load();

Thus, C++ Undefined Behaviour, end of story as far as standards compliance is concerned.
In practice, a non-atomic load will happen to be atomic anyway on most CPU architectures, or at worst experience tearing.  (IDK of any ISA where it results in anything unpredictable other than the value, but C++ leaves this option open).
I'm not sure there's any scenario where a torn value could actually get used (put into m_front), because clear_links() can't run until after a successful CAS.  And if CAS succeeded in one thread, it will fail in the other thread because it will only try a torn next value with the old front as the expected arg to CAS.
In practice, pretty much every implementation anyone cares about has no extra cost for relaxed-atomic loads/stores vs. regular for pointer-sized objects.  In fact, this stack pretty much sucks if atomicity isn't "free" for a pointer.
e.g. on AVR (8-bit RISC microcontrollers which use 16-bit pointers), it would be cheaper to just take a lock on the data structure, instead of letting std::atomic use locks for every load/store in this algo.  (Especially since there aren't multi-core AVR CPUs, so locks are probably very cheap to implement.)

atomic<> also gets the compiler to assume that a value could be asynchronously modified by another thread.  So it stops it from ever optimizing away a load or store, somewhat like volatile.  (But see also Why don't compilers merge redundant std::atomic writes?.)  I don't think there's anything here where that's needed, and wouldn't already happen.
Non-atomic ops are ordered by atomic acquire and release operations, similar to relaxed atomic operations, and CAS modifies front, so front->nexthas a newfront` so a non-atomic load couldn't optimize away.
It might be an interesting experiment to see if you get identical asm output from a compiler after replacing atomic <Node*> next with Node *next.  (Or with a non_atomic wrapper class that still has load/store member functions so you don't have to modify much code).

Using relaxed atomic stores looks good to me.  You definitely don't want to implement it the way you showed, with seq_cst stores as part of initializing a new object that hasn't had any pointers to it published yet.  At that point atomicity is not needed, but it's free (on normal CPUs) so there's no benefit to avoiding it.  None of the stores or loads could be optimized away.


text:
Q: MJS - Array to ArrayList How do I convert an Array to an ArrayList in MJS?
So, let's say that I have an Array:
MJS-Array;createnew. myArray
When I do
MJS-ArrayList;createnew. myArrayList -> through;myArray.
this returns an empty ArrayList.
What am I doing wrong?
Thank you.

A: OK, I figured out the answer.
We need to do
MJS-ArrayList;createnew + { myArrayList ->  \[{ through;myArray. }] }
Ew. Long and ugly. I can't believe that there is no better way to do this.


text:
Q: Playframework 1.x Pointing to a staticFile: route in a template Given
GET /termsofservice   staticFile:/public/tos.txt
GET /public/          staticDir:public

How do I point to this first route in a template?
@{'public/tos.txt'} ends up with a .../public/tos.txt url instead of .../termsofservice
I'm now using
${play.Play.configuration.getProperty("application.baseUrl")}/termsofservice

but there should be a cleaner way?

A: This isn't ideal, but what we have is a "Docs" controller:
public class Docs extends Controller {
    public static void termsOfUse() { render(); }

Most likely you don't want TOS to be txt file anyway, so this way you create template for it where you include your header/footer and add TOS inside it, getting /docs/termsofservice URL or similar.


text:
Q: JToken.ToString() removing curly braces I have the following JToken:
{
    "ID": "9dbefe3f5424d972e040007f010038f2"
}

But whenever I run ToString() on the JToken object to get the underlying JSON in string form, it returns:
\"ID\": \"9dbefe3f5424d972e040007f010038f2\"

Escaping the quotes is expected, but why is it removing the curly braces? It's valid JSON. And this only seems to happen in certain cases, as I'm able to successfully run ToString() and have the curly braces intact on other (more complex) JTokens.

A: ToString() returns the JSON representation of the contents of the JToken.  JToken is an abstract class, so what JSON is returned depends on what kind of JToken it is (as well as what it contains).
Here is a short example that should illustrate the point:
class Program
{
    static void Main(string[] args)
    {
        JObject jo = new JObject();
        jo.Add("ID", "9dbefe3f5424d972e040007f010038f2");

        // token is a JObject
        DumpToken(jo);

        // token is a JProperty (the first property of the JObject)
        DumpToken(jo.Properties().First());

        // token is a JValue (the value of the "ID" property in the JObject)
        DumpToken(jo["ID"]);
    }

    private static void DumpToken(JToken token)
    {
        Console.WriteLine(token.GetType().Name);
        Console.WriteLine(token.ToString());
        Console.WriteLine();
    }
}

Output:
JObject
{
  "ID": "9dbefe3f5424d972e040007f010038f2"
}

JProperty
"ID": "9dbefe3f5424d972e040007f010038f2"

JValue
9dbefe3f5424d972e040007f010038f2

So, I suspect that when you are getting a bare name-value pair from ToString() you have a reference to a JProperty in your code, not a JObject.  You should only expect to get complete (valid) JSON when you call ToString() on a JObject or a JArray.


text:
Q: Running .NET framework console-app service on Docker I'm trying to get a service on-boarded to Docker containers.
Target Framework - .NET Framework 4.6.1
Output type - Console Application
When I initially tried to right click -> Add -> Docker Support on the project in the Visual Studio 2017 sln I got a prompt "You cannot add Docker support to this project type"
I went ahead and created a Dockerfile by hand and placed it in the root. This is what it looks like:
FROM microsoft/windowsservercore

SHELL ["powershell", "-command"]

RUN Add-WindowsFeature NET-Framework-45-ASPNET, Web-Asp-Net45

EXPOSE 80
EXPOSE 5000
EXPOSE 13134

ADD ./bin/Debug/net461/win7-x64 .
COPY ./bin/cert-that-needs-to-be-installed.pfx /cert-that-needs-to-be-installed.pfx

RUN $Secure_String_Pwd = ConvertTo-SecureString "thePasswordToTheCert!" -AsPlainText -Force; \
    Import-PfxCertificate -FilePath .\cert-that-needs-to-be-installed.pfx  -CertStoreLocation Cert:\LocalMachine\My -Exportable -Password $Secure_String_Pwd;

ENV ASPNETCORE_ENVIRONMENT="Development"
ENTRYPOINT ["./ServiceName.exe"]

Upon doing the following, I was able to successfully create an image and also a container with the service running on it: (the prod version listens on port 5000 while the test one listens on 13134 and those ports are also open in my localhost Firewall)
docker build -t ServiceName .; docker run -p 5000:5000 -p 13134:13134 -it ServiceName

I am able to get the ip of the container by doing this:
docker inspect <containerId>

Now when I try to test the service by doing a HttpGet call to an API using Postman I don't get a response. I have the docker container open in my cmd prompt and I don't see my request coming in either.
My service works fine on a Windows VM.
Since my GET calls don't even seem to reach the container I fear I am doing the port mapping wrong/or is it something else?

A: From what I know you don't need the ip of the container, the ports have been projected on your localhost, you should get a response when you make REST calls to localhost:5000/localhost:13134


text:
Q: Changing color of the drawing figure with Jbutton I wrote a program for drawing figures. I am having problem with communication between components. After few hours of different ways I give up.
My program is divided between 2 packages:
First package called panels: App.java, ButtonPanel.java, ColorPanel.java, DrawingPanel.java, MainFrame.java
Second package called shapes: Circle.java, Line.java, Square.java and other figures. There is also abstract class called Shape.java
I want basically press button called btnRed and to be available to draw figure with Red color. In this case I want to draw circle.

Circle.class
package shapes;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

import panels.ButtonPanel;

public class Circle extends Shape   {

    private int x1, y1, x2, y2;
    private Color updatedColor;
    private ButtonPanel buttonPanel;

    public Circle(int x1, int y1, int x2, int y2) {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
    }

    @Override
    public void draw(Graphics2D g2) {

        int r = (int)Math.sqrt(Math.pow((x2-x1),2) + Math.pow((y2-y1),2));
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        updatedColor = buttonPanel.getNewColor();

        g2.setColor(updatedColor);
        g2.drawOval(x1 - r, y1 - r, r*2, r*2);
    }

    @Override
    public void update(int x, int y) {
        x2 = x;
        y2 = y;
    }
}

I have all buttons and button listeners in ButtonPanel.java class.
package panels;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.border.Border;

import shapes.Circle;

public class ButtonPanel extends JPanel implements ActionListener{

    private JButton btnLine;
    private JButton btnCircle;
    private JButton btnTriangle;
    private JButton btnSquare;
    private JButton btnHexagon;
    private JButton btnUndo;
    private JButton btnReset;
    private JButton btnSave;
    private JButton btnLoad;
    private JButton btnPentagon;
    private JButton btnWhite;
    private JButton btnYellow;
    private JButton btnOrange;
    private JButton btnPink;
    private JButton btnRed;
    private JButton btnGreen;
    private JButton btnBlue;
    private JButton btnMagenta;
    private JButton btnCyan;
    private JButton btnLightGrey;
    private JButton btnDarkGrey;
    private JButton btnBlack;
    private Color cl;

    //i want to hook up this with my drawing panel
    private DrawingPanel drawingPanel;
    private Circle circle;

    public ArrayList<JButton> shapeArrayList = new ArrayList<JButton>();

    public ButtonPanel() {

        //instanitiate buttons
        Dimension dim = getPreferredSize();
        btnLine = new JButton("LINE");
        btnCircle = new JButton("CIRCLE");
        btnTriangle = new JButton("TRIANGLE");
        btnSquare = new JButton("SQUARE");

        btnWhite = new JButton("WHITE");
        btnWhite.setBackground(Color.WHITE);

        btnYellow = new JButton("YELLOW");
        btnYellow.setBackground(Color.YELLOW);

        btnOrange = new JButton("ORANGE");
        btnOrange.setBackground(Color.ORANGE);

        btnPink = new JButton("PINK");
        btnPink.setBackground(Color.PINK);

        btnRed = new JButton("RED");
        btnRed.setBackground(Color.RED);

        btnGreen = new JButton("GREEN");
        btnGreen.setBackground(Color.GREEN);

        btnBlue = new JButton("BLUE");
        btnBlue.setBackground(Color.BLUE);

        btnMagenta = new JButton("MAGENTA");
        btnMagenta.setBackground(Color.MAGENTA);

        btnCyan = new JButton("CYAN");
        btnCyan.setBackground(Color.CYAN);

        btnLightGrey = new JButton("LIGHT GREY");
        btnLightGrey.setBackground(Color.LIGHT_GRAY);

        btnDarkGrey = new JButton("GREY");
        btnDarkGrey.setBackground(Color.DARK_GRAY);

        btnBlack = new JButton("BLACK");
        btnBlack.setBackground(Color.BLACK);

        btnPentagon = new JButton("PENTAGON");
        btnUndo = new JButton("UNDO");
        btnReset = new JButton("RESET");
        btnSave = new JButton("SAVE");
        btnLoad = new JButton("LOAD");

        //set width fot the panel button
        dim.width = 200;
        setPreferredSize(dim);

        Border innerBorder = BorderFactory.createTitledBorder("Draw buttons");
        Border outerBorder = BorderFactory.createEmptyBorder(5, 5, 5, 5);
        setBorder(BorderFactory.createCompoundBorder(outerBorder, innerBorder));

        //set new Lyaout for ButtonPanel
        setLayout(new GridBagLayout());

        GridBagConstraints gc = new GridBagConstraints();

        gc.gridx = 0; //set position from left to right
        gc.gridy = 0; //set position from up to down
        gc.weightx = 1; //weight controls how irmuch space take relative to the other space
        gc.weighty = 1;

        // tell will it take all the space in the components or not
        gc.fill = GridBagConstraints.BOTH;

        add(btnLine, gc); //add buttons to the layout

        gc.gridx = 0;
        gc.gridy = 1;
        add(btnCircle, gc);

        gc.gridx = 0;
        gc.gridy = 2;
        add(btnSquare, gc);

        gc.gridx = 0;
        gc.gridy = 3;
        add(btnTriangle, gc);

        gc.gridx = 0;
        gc.gridy = 4;
        add(btnSquare, gc);

        gc.gridx = 0;
        gc.gridy = 5;
        add(btnPentagon, gc);

        //colors///////////////////////////////////////////////////////
        gc.gridx = 0;
        gc.gridy = 6;
        add(btnWhite, gc);

        gc.gridx = 0;
        gc.gridy = 7;
        add(btnYellow, gc);

        gc.gridx = 0;
        gc.gridy = 8;
        add(btnOrange, gc);

        gc.gridx = 0;
        gc.gridy = 9;
        add(btnPink, gc);

        gc.gridx = 0;
        gc.gridy = 10;
        add(btnRed, gc);

        gc.gridx = 0;
        gc.gridy = 11;
        add(btnGreen, gc);

        gc.gridx = 0;
        gc.gridy = 12;
        add(btnBlue, gc);

        gc.gridx = 0;
        gc.gridy = 13;
        add(btnMagenta, gc);

        gc.gridx = 0;
        gc.gridy = 14;
        add(btnCyan, gc);

        gc.gridx = 0;
        gc.gridy = 15;
        add(btnLightGrey, gc);

        gc.gridx = 0;
        gc.gridy = 16;
        add(btnDarkGrey, gc);

        gc.gridx = 0;
        gc.gridy = 17;
        add(btnBlack, gc);

        //operations buttons
        gc.gridx = 0;
        gc.gridy = 18;
        add(btnUndo, gc);

        gc.gridx = 0;
        gc.gridy = 19;
        add(btnReset, gc);

        gc.gridx = 0;
        gc.gridy = 20;
        add(btnSave, gc);

        gc.gridx = 0;
        gc.gridy = 21;
        add(btnLoad, gc);

        /*
         *
         * add action listener to the buttons
         */
        btnLine.addActionListener(this);
        btnCircle.addActionListener(this);
        btnTriangle.addActionListener(this);
        btnSquare.addActionListener(this);
        btnPentagon.addActionListener(this);

        btnWhite.addActionListener(this);
        btnYellow.addActionListener(this);
        btnOrange.addActionListener(this);
        btnPink.addActionListener(this);
        btnRed.addActionListener(this);
        btnGreen.addActionListener(this);
        btnBlue.addActionListener(this);
        btnMagenta.addActionListener(this);
        btnCyan.addActionListener(this);
        btnLightGrey.addActionListener(this);
        btnDarkGrey.addActionListener(this);
        btnBlack.addActionListener(this);

        btnUndo.addActionListener(this);
        btnReset.addActionListener(this);
        btnSave.addActionListener(this);
        btnLoad.addActionListener(this);

    }   //end of constructor

    //overridden method from actionlistener interface
    @Override
    public void actionPerformed(ActionEvent e) {

        JButton btnFire = (JButton) e.getSource();

        if(btnFire == btnLine) {
            drawingPanel.setCurrentShape(0);
        }
        else if(btnFire == btnCircle) {
            drawingPanel.setCurrentShape(1);
        }
        else if(btnFire == btnTriangle) {
            drawingPanel.setCurrentShape(2);
        }
        else if(btnFire == btnSquare) {
            drawingPanel.setCurrentShape(3);
        }
        else if(btnFire == btnPentagon) {
            drawingPanel.setCurrentShape(4);
        }

        else if(btnFire == btnUndo) {
            drawingPanel.setCurrentShape(5);
        }
        else if(btnFire == btnReset) {
            drawingPanel.setCurrentShape(6);
        }
        else if(btnFire == btnSave) {
            drawingPanel.setCurrentShape(7);
        }
        else if(btnFire == btnLoad) {
            drawingPanel.setCurrentShape(8);
        }
        else if(btnFire == btnRed) {
            cl = Color.red;
            System.out.println("cl is: " + cl);

        }
    }   //end of actionperformed method

    public void setDrawingPanel(DrawingPanel drawingPanel) {
        this.drawingPanel = drawingPanel;
    }

    public void setButtonPanel(ButtonPanel buttonPanel) {
        this.drawingPanel = drawingPanel;
    }

    public void setNewColor(Color color) {
        this.cl = color;
    }

    public Color getNewColor() {
        return cl;
    }

}

When I press red and debugg with System.out.print it says I have that red button storred in cl variable.
cl is: java.awt.Color[r=255,g=0,b=0]

However when I pressed Circle button and red button it gives me NullPointerException. It looks like that cl is not passed to the updatedColor variable in the Circle.java class
 updatedColor = buttonPanel.getNewColor();

It give me null when I sysout that statement. Can anybody help me with that,please ?

A: Painting is destructive, each time a paint cycle is triggered, you will need to re-paint the whole state, this means, you will need to store the color of the shape with the shape some how.
Instead of using...
updatedColor = buttonPanel.getNewColor();

The Shape should have it's own color property, which is used every time it is painted.  The problem with your current approach is that EVERY instance of Circle will get the same color.
Add a color property to the shape and change the color of the shape when you need to.  Don't forget to call repaint on the shape container to update it
public class Circle extends Shape   {

    private int x1, y1, x2, y2;
    private Color updatedColor;
    private ButtonPanel buttonPanel;

    public Circle(int x1, int y1, int x2, int y2) {
        this.x1 = x1;
        this.y1 = y1;
        this.x2 = x2;
        this.y2 = y2;
    }

    public void setColor(Color color) {
        updateColor = color;
    }

    public Color getColor() {
        return updateColor;
    }

    @Override
    public void draw(Graphics2D g2) {

        int r = (int)Math.sqrt(Math.pow((x2-x1),2) + Math.pow((y2-y1),2));
        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

        g2.setColor(getColor());
        g2.drawOval(x1 - r, y1 - r, r*2, r*2);
    }

    @Override
    public void update(int x, int y) {
        x2 = x;
        y2 = y;
    }
}

A: You are calling
updatedColor = buttonPanel.getNewColor();

However, the variable buttonPanel is a private variable in your Circle class, which you are not initializing.
That's why you have a NullPointerException. When you create the circle, you should also pass it a reference to the button panel with which to initialize buttonPanel.


text:
Q: hp envy 4 - dual win 8 with ubuntu I have win8 on my envy 4 ullttrabook and i want to dual win8 with ubuntU.
I download the instulation and run it throw usb.
But, the installision does not recognize my hard disc ,while im in it, throw the usb.
Whay should i do?

A: Let me tell you that I don't trust HP and I think of Windows 8 is difficult and unnecessary. Do you need anything from Microsoft? So we are slaves of these companies: the latter & Apple.
I cannot supply any solution with W8 but a good idea could be to burn an image on a dvd. So did I on my computer Dell W7. Therefore both two operating systems run well.


text:
Q: How to put background on the top for internal pages of installer How can I put the background image to the top of internal installer page, so it takes all header area.
In solution below background takes only left side of the header
!define MUI_HEADERIMAGE
!define MUI_HEADERIMAGE_BITMAP "top.bmp"
!include "MUI2.nsh"

A: You can't do this without modifying a UI executable. See the MUI 2 docs, specifically the MUI_UI definition. You'd need to take the default executable and with a resource hacker change the size of that header image.
You may also be able to swing this with resource hacking and the value of MUI_UI_HEADERIMAGE (see those docs). I'm not sure, though, as I've never tried it.

A: I have found the answer
!define MUI_HEADERIMAGE_BITMAP_NOSTRETCH


text:
Q: Trigger :visited state (make links purple) when browsing in Electron In my Electron app I have a webview. If I click a link (e.g. on Google) and then move back, the link turns not purple, like in normal browsers.
Can I activate this behaviour in Electron too? Or do it programmatically, if I would store the browsing history by myself?
I guess it is somehow connected that the history support in Electron is not yet the best?
Would this maybe possible with Muon fork of Electron?

A: As you can see from the comments at about line 16 of this file, the Electron guys/girls have created their own navigation solution. It would seem this doesn't handle a:visited properly.
Instead, we can easily create our own solution. Add the following function to all of your renderer scripts and ensure you put simuHistory(); at the start of every page:
function simuHistory() {
    var localstorageSimuHistory = localStorage.getItem('simuHistory');
    var simuHistory = localstorageSimuHistory ? JSON.parse(localstorageSimuHistory) : [];
    var found = false;
    var windowHref = window.location.href;
    for(let i=0;i<simuHistory.length;i++) {
        if(simuHistory[i] == windowHref) {
            found = true;
            break;
        }
    }
    if(found === false) {
        simuHistory[simuHistory.length] = windowHref;
        localStorage.setItem('simuHistory', JSON.stringify(simuHistory));
    }
    var elements = document.getElementsByTagName('a');
    for(let i=0;i<elements.length;i++) {
        for(let h=0;h<simuHistory.length;h++) {
            if(elements[i].href == simuHistory[h]) {
                elements[i].className += ' visited';
            }
        }
    }
}

And add the following CSS to your stylesheet:
.visited {
    color: purple;
}

Alternatively, if you don't want to include the CSS (or want it all self-contained), you could replace this line:
elements[i].className += ' visited';

...with this line:
elements[i].style.color = 'purple';

Scalability
The TL;DR is that unless you have more than around 25,000 fairly long unique URLs in your app, you don't need to worry about scalability.
The visited URLs are stored in localStorage. This is limited in size, and therefore limited in the number of URLs we can store. I believe in Electron this is limited to around 5MB. I tested performance by adding 25,000 additional URLs to the simuHistory array using the following code:
for(var i = 0; i < 25000; i++) {
    simuHistory[simuHistory.length] = 'https://stackoverflow.com/questions/417142/what-is-the-maximum-length-of-a-url-in-different-browsers' + Math.floor((Math.random() * 1000000) + 1);
}

The URL was chosen because it was fairly long. The random number on the end actually affects nothing at all; I just included it to add some extra length. Then I timed running simuHistory() on my crappy slow laptop (with no SSD):
25,000 URLs == ~210ms
 1,000 URLs == ~13ms

In my opinion that's plenty fast for nearly any Electron app, but it depends on your use case as to how many URLs you might end up with.


text:
Q: SOCKET.IO IN express whit EC2 AWS throws "WebSocket is closed before the connection is established." I'm creating a http Socket.io server inside of an express server with something like this:
const port = parseInt(process.env.PORT, 10) || 3001;
const server = express();
const server2 = http.createServer(server);
const io = socketIo(server2, {
 pingTimeout: 3600000
 });
server.listen(port);

I was able to get a 101 status code in my localhost connection.
But at the time I deploy my code to a AWS EC2 instance, it throws the following error:

WebSocket connection to 'ws:/socket.io/EIO=3&transport=websocket' failed: WebSocket is closed before the connection is established.

Client side
this.socket = io("/", {
      transports: ["websocket"]
    });


text:
Q: how to get the 32bit secret encryption key from laravel env file I am trying to fetch the secret encryption key from laravel so that I can use it on the mobile app end for decrypting the data. When I run the command in the laravel
php artisan key:generate

It created the below key in the .env file in laravel. Laravel documentation says that the above command should create a 32 character string key but i get the blow string
APP_KEY=base64:H2gjrkZZAx3U6Rc7hhZG59xzNY2bSsaW1dKpo1Q1NRk=
Larvel uses the above key to encrypt the data. I need the 32 character key string to decrypt the data in other places. Above Key after removing base64: is 44 character string so I get this is not the actual string. I have tried to decode the string by using base64_decode but then it gives a binary string. I need the actual 32 character secret key
Can someone please guide how do I fetch the actual secret key string so that I can use it in other places for decrypting the data?
Regards
Syed

A: If you base64 decode H2gjrkZZAx3U6Rc7hhZG59xzNY2bSsaW1dKpo1Q1NRk= it returns a 32 character long string (binary).
But generally I would think you could use native Laravel methods for decryption and thus avoid fetching the key manually.

A: If I understand you very well, go to your "config/app.php"
Change 'cipher' => 'AES-256-CBC',to AES-128-CBC and then re-generate the key.