text:
Q: Gridview onclick listener its not working I am using gridview of layout,its not working after the grid view items in the list,it shows "throwIndexOutOfBoundsException" in logcat error.without onclick function if i use toast its working,if i give an onlcick function for next activity its not working
Gridviewadapter.java
public class GridviewAdapter extends BaseAdapter
{
    private ArrayList<String> listginfy;
    private ArrayList<Integer> listimage;
    private Activity activity;

    public GridviewAdapter(GinfyActivity ginfyActivity,ArrayList<String> listginfy, ArrayList<Integer> listimage) {
        super();
        this.listginfy = listginfy;
        this.listimage = listimage;
        this.activity = (Activity) ginfyActivity;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return listginfy.size();
    }

    @Override
    public String getItem(int position) {
        // TODO Auto-generated method stub
        return listginfy.get(position);
    }

    public int getItemId() {
        // TODO Auto-generated method stub
        return 0;
    }

    public static class ViewHolder
    {
        public ImageView imgViewGinfy;
        public TextView txtViewTitle;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        ViewHolder view;
        LayoutInflater inflator = activity.getLayoutInflater();

        if(convertView==null)
        {
            view = new ViewHolder();
            convertView = inflator.inflate(R.layout.gridview_row, null);

            view.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
            view.imgViewGinfy = (ImageView) convertView.findViewById(R.id.imageView1);

            convertView.setTag(view);
        }
        else
        {
            view = (ViewHolder) convertView.getTag();
        }

        view.txtViewTitle.setText(listginfy.get(position));
        view.imgViewGinfy.setImageResource(listimage.get(position));

        return convertView;
    }

    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return 0;
    }

}

Mainactivity.java
 @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home_ginfy);

        prepareList();

        // prepared arraylist and passed it to the Adapter class
   mAdapter = new GridviewAdapter(this,listginfy, listimage);

        // Set custom adapter to gridview
        gridView = (GridView) findViewById(R.id.gridView1);
        gridView.setAdapter(mAdapter);

        // Implement On Item click listener
        gridView.setOnItemClickListener(new OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> a, View v, int position, long id) {

                mAdapter = results.get(position);

                switch(mAdapter.getItemId())
                {
                case 1:
                Intent newActivity = new Intent(GinfyActivity.this,MainActivity.class);
                startActivity(newActivity);
                break;

                case 2:
                Intent new1Activity = new Intent(GinfyActivity.this,AndroidTabLayoutActivity.class);
                startActivity(new1Activity);
                break;
                default:
                    Toast.makeText(GinfyActivity.this, "Wrong Input", Toast.LENGTH_LONG).show();
                    }
            }
        });

    }

    public void prepareList()
    {
        listginfy = new ArrayList<String>();

        listginfy.add("Prayers");
        listginfy.add("Poojaroom");

        listimage = new ArrayList<Integer>();
        listimage.add(R.drawable.ginfyprayer);
        listimage.add(R.drawable.poojaroom1);

    }

}

Onclick function of gridview is not working
here i post my xml layout also.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    android:id="@+id/relativeLayout1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:background="@drawable/border"
    android:padding="5dp">

    <ImageView
        android:layout_height="64dp"
        android:id="@+id/imageView1"
        android:layout_width="64dp"
        android:src="@drawable/icon"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:clickable="True">
    </ImageView>

    <TextView
        android:text="TextView"
        android:layout_height="wrap_content"
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_below="@+id/imageView1"
        android:layout_marginTop="2dp"
        android:layout_centerHorizontal="true"
        android:textSize="18sp"
        android:ellipsize="marquee"></TextView>

</RelativeLayout>

home_ginfy.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">

    <GridView
        android:layout_height="wrap_content"
        android:id="@+id/gridView1"
        android:layout_width="match_parent"
        android:numColumns="auto_fit"
        android:horizontalSpacing="10dp"
        android:verticalSpacing="10dp"
        android:clickable="True">
    </GridView>
</LinearLayout>

A: you have a lot of error in your code.. (like android:clickable="True" in your layout >> remove that)
just for test, replace your code with:
// Implement On Item click listener
        gridView.setOnItemClickListener(new OnItemClickListener()
        {
            @Override
            public void onItemClick(AdapterView<?> a, View v, int position, long id) {

            switch(position)
            {
            case 1:
            Intent newActivity = new Intent(GinfyActivity.this,MainActivity.class);
            startActivity(newActivity);
            break;

            case 2:
            Intent new1Activity = new Intent(GinfyActivity.this,AndroidTabLayoutActivity.class);
            startActivity(new1Activity);
            break;
            default:
                Toast.makeText(GinfyActivity.this, "Wrong Input", Toast.LENGTH_LONG).show();
                }
        }
    });

The getItemId for your adapter always return 0..

A: replace
mAdapter = results.get(position);

                switch(mAdapter.getItemId())

by
switch(position)

A: I have been using something like this. In your case this should work.
public class GridviewAdapter extends BaseAdapter
{
    private ArrayList<String> listginfy;
    private ArrayList<Integer> listimage;
    private Activity activity;

    public GridviewAdapter(GinfyActivity ginfyActivity,ArrayList<String> listginfy, ArrayList<Integer> listimage) {
        super();
        this.listginfy = listginfy;
        this.listimage = listimage;
        this.activity = (Activity) ginfyActivity;
    }

    @Override
    public int getCount() {
        // TODO Auto-generated method stub
        return listginfy.size();
    }

    @Override
    public String getItem(int position) {
        // TODO Auto-generated method stub
        return listginfy.get(position);
    }

    public int getItemId() {
        // TODO Auto-generated method stub
        return 0;
    }

    public static class ViewHolder
    {
        public ImageView imgViewGinfy;
        public TextView txtViewTitle;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        // TODO Auto-generated method stub
        ViewHolder view;
        LayoutInflater inflator = activity.getLayoutInflater();

        if(convertView==null)
        {
            view = new ViewHolder();
            convertView = inflator.inflate(R.layout.gridview_row, null);

            view.txtViewTitle = (TextView) convertView.findViewById(R.id.textView1);
            view.imgViewGinfy = (ImageView) convertView.findViewById(R.id.imageView1);

            convertView.setTag(view);
            convertView.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    switch (position){
                         case 1:
                              Intent newActivity = new Intent(GinfyActivity.this,MainActivity.class);
                              startActivity(newActivity);
                              break;
                         case 2:
                              Intent new1Activity = new Intent(GinfyActivity.this,AndroidTabLayoutActivity.class);
                              startActivity(new1Activity);
                              break;
                         default:
                              Toast.makeText(GinfyActivity.this, "Wrong Input", Toast.LENGTH_LONG).show();
                    }
                }
             }
        }
        else
        {
            view = (ViewHolder) convertView.getTag();
        }

        view.txtViewTitle.setText(listginfy.get(position));
        view.imgViewGinfy.setImageResource(listimage.get(position));

        return convertView;
    }

    @Override
    public long getItemId(int arg0) {
        // TODO Auto-generated method stub
        return 0;
    }

}


text:
Q: Why I receive error 2042 in MATCH formula in my VBA? If checkRECORD1 > 0 Then If checkRECORDvalue > 0 Then matchRECORD1 =
Evaluate("INDEX(TEMPDB!E" & lrCHIIMPORT2 + 1 & ":E" & lr3CHIMPORT2 & _
",MATCH(STATIONS!B" & RARTSTAT3 &"& STATIONS!" & Cells(1, cARTIST).Address & _
" , TEMPDB!C" & lrCHIIMPORT2 + 1 & ":C" & lr3CHIMPORT2 & _
" & TEMPDB!A" & lrCHIIMPORT2 + 1 & ":A" & lr3CHIMPORT2 & "))")

Ok, I had some troubles with code above. To ease things up here is some clarification:
checkRECORD counts is there such entry in SEARCH table
checkRECORDvalue is checking does that entry have any value in specific column (can be text or number or empty)
What index/match should be return to is number in this case: 25 (in some other case can be text). Range is pretty much clear and criteria in this case is STATIONNAME and ARTISTNAME. Both exist when I check it manually (KJLU and HW-BREEZIN`) and also there is value to be returned - 25!
I read other articles about this issues, but didnt quite understood why and where would I need CLNG (solution from other thread)?
I constantly receive either 0 either error 2042 for matchRECORD1!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can two ATX SMPS be connected in series to get +10 and +24V DC Can two ATX SMPS be connected in series to get +10 and +24V DC (from 5V and 12DC output of each SMPS)
Needing lots of current at 24V with atleast 5A so cannot use -5V or -12V inside SMPS as negative voltage have less than 1A rating
I know transformer based PSU can be uses this way, but professor telling that SMPS cannot be connected in series the same way.
He not tell me reason as he says I will understand better next year when SMPS in course offering.
If he correct, then why not SMPS work like transformer based PSU?

A: No, you can't connect two ATX supplies in series and get double the voltage.  There are many issues to consider, and most of them require detailed knowledge about the insides of each power supply.
One issue to consider is what happens when one supply is turned on, while the other is off?  This can happen for many reasons, but #1 reason is that both power supplies will never come up at exactly the same time even if you use the same power switch for both.  When one is on, and the other is off, the off supply will be subjected to -5 & -12v on it's outputs.  This is a case that the supply was never designed to handle.  Odds are that you'll blow up the caps on the output, and maybe a diode or MOSFET as well.
There are ways to protect against this sort of fault, but why bother?  You will be much better off getting a supply that does what you want-- and the risk of burning down your house is much less.

A: Under certain conditions you can stack power supply outputs to get higher voltage, but there are caveats.
If the power supply rails have their output return tied to earth, you obviously cannot connect the return of one supply to the positive of the other supply without creating a short-circuit. The ATX spec v2.2 says:
3.4.6. Output Bypass
The output return may be connected to the power supply chassis. The return will be
connected to the system chassis by the system components.

This is ambiguous - the power supply return may or may not be earthed inside the power supply depending on the whim of the manufacturer.
David's earlier point is valid. Since you cannot guarantee that the output of each power supply stage was intended for paralleling, you most likely would have to add ORing diodes to provide some measure of protection and deal with the power dissipation.
The other issues that were touched on in earlier posts are valid. The outputs will not come up together, so your rail will go from 0-12V, then 12-24V in discrete steps. Also, overcurrent protection will not happen at the same threshold for both supplies.
You are definitely better off just purchasing (or designing) a 24V supply.

A: You CAN connect 2 SMPS in series, better if they are the same brand & model... because they are designed to behave as theoric batteries. This way of connection has some problems anyways, a price to pay for : Poor load regulation, partial or total lost of overcurrent protection and similar stuff.
Starting-conditions get worse but they are not bad at all because the baddest starting situation behaves as only-one supply starting by itself (the cheapest one).
Paralel operation is not suggested as current sharing is 100% unpredictable.

A: Needing a very specialized supply that wasn't available in the voltage or wattage I wanted, I was considering to setup 2 of those PSU in series but found it very complex to manage. You have all the points that were already made with regards to grounding and timing of power-ons but there's also the issue that one of the PSUs will have double the voltage that it's 12v rail was designed for running through it. To make sure that it's not going to blow up, you'll have to go through every component of the rail, lookup it's model number on google and check what's the maximum voltage it's been designed to operate on.

A: The outputs of Switching Power Supplies can NOT be connected in either series nor parallel unless they are specifically designed to allow for multi-unit syncronization. Very few SMPS devices are designed for this.
The reason is that each SMPS is switching 20,000 - 80,000+ times per second. If you connect their outputs together without them being perfectly syncronized, they will not share the load properly and there can be very large voltage transients created which will destroy the SMPS components and possibly even the load you have connected to them.


text:
Q: Are there any integer solutions for $a$, $b$, $c$, $d$ such that $ad^2+{b^2}c=0$ Are there any integer solutions  $a$, $b$, $c$, $d$ such that $ad^2+{b^2}c=0$, where $b\neq 0$ and $d\neq 0$? If so, can you please list some examples of them?

A: Yes there are integer solutions, for example all $(a,b,c,d)\in\mathbb{Z}^4$ with $a=-c, d=\pm b$.

A: $$ad^2+{b^2}c=0 \Rightarrow \frac{a}{c}=-\left(\frac{b}{d}\right)^2$$
if we take
$a=\pm kb^2$ and $c= \mp kd^2$ we have solutions.

A: well, obviously $a = -c$ and $b^2 = d^2$.
But less trivially (maybe) for any $a = a'*n^2; n\ne 1$ and $c = -a'$ and $|b| =|dn|$ will do.  ($ad^2 + b^2c = a'n^2d^2 + (dn)^2(-a')$.)
So... I dunno $a = 75; b=35; c=-3;d= 7$... $75*7^2 + 35^2*(-3) = 0$.
More thouroughly:
Let $a = \prod p_{a,i}^{n_{a,i}}$ and $d = \prod p_{d,i}^{n_{d,i}}$ be the prime factors of $a$ and $b$ then we $-cb^2=ad^2 =\prod p_{a,i}^{n_{a,i}}\prod p_{d,i}^{2n_{d,i}}$.  We can divy up the prime factors between $c$ and $d$ however we like (provided the even/odd parity adds up).
Example: If $a =35=5*7$ and $d = 80=2^4*5$ then $ad^2 =-cb^2 = 2^8*5^3*7$ so I can choose $c= -2^2*5^3*7=3500; d = 2^3=8$ .  So $35*80^2 - 3500*8 = 0$. Or $c=-2^8*5*7; d=5$ so $35*80^2 -8960*25 = 0$   (Note: $c$ had to be an odd multiple of 5 and a multiple of 7 and could only have even or 0 powers of 2.)


text:
Q: Run GUI Applications from Terminal with root privilege So it has been well documented that GUI applications (like gedit or textedit) should NOT be run with sudo. Ubuntu et al get gksu and gksudo (and the like) so question: what do WE (Mac users) get? Given that the Darwin kernel is built on some *BSD code, I assume the same issues apply, but how do we go around this?

A: To edit /etc/hosts with Sublime Text:
sudo /Applications/Sublime\ Text.app/Contents/MacOS/Sublime\ Text /etc/hosts
If you have to do this on the regular basis, you can add this snippet to your ~/.bash_profile
#   sudoapp: Runs .app with root privileges
#   Usage: sudoapp /Applications/Name.app /etc/hosts
#   --------------------------------------------------------------------
    sudoapp () {
        sudo "$1/Contents/MacOS/$(defaults read "$1/Contents/Info.plist" CFBundleExecutable)" $2
    }

Apps running with root privileges will use /private/var/root as home folder, thus all config and temporary files owned by root that will be created in the process will stay where they should be - in the root home directory.
This is the same as logging in as root and running the app, but without the hassle of user switching.
This method works on 10.6 — 10.11
Update: Apple's own TextEdit refuses to start if run as root in 10.11 and newer, so I changed my example to use Sublime Text instead

A: While is it possible to launch a graphical application as the root user, it is not recommended. It may work, most of the time, but avoid relying on this behaviour.
Avoid root
Running an application as root is not recommended because it dramatically increases the risk of causing problems with your Mac. The use of root should be limited to the smallest possible piece of code with strict controls in-place.
Applications are increasingly moving towards a fragmented design to avoid exposing too much power to code that does not require it.

*

*A mistake in code running with root permissions is a security risk.

*A mistake in code without root permissions is much less capable of causing serious problems.

There are edge cases but these are increasingly rare. The introduction of sandboxing and XPC are part of Apple's efforts to reduce the need to provide excessive authority to processes running on OS X.
Command Line Tools
If you need to work with files as root user, use command line tools such as vim, emacs, or nano. These tools do not rely on the WindowServer and can happily be launched as root within another user session:
sudo nano <path to edit>

Graphical Tools
If you prefer graphical editors, use an editor that works with the design of Mac OS X.  BBEdit is an excellent editor that will correctly handle editing root owned files.
When you edit a root owned file with BBEdit, a second process is used to bridge the permissions gap between you and the owner of the file. This process passes through Apple's sanctioned paths and thus ensures a predictable experience - hopefully across multiple major versions of Mac OS X.
Why? WindowServer Limits and Design Scope
There are subtle technical problems with launching a graphical application within another user session.
The underlying technical problems stem from one user wanting to launch a graphical process within another user's session. Mac OS X's WindowServer was never designed with this as a goal. User sessions are extremely difficult to break out of even as root user – all for desirable security reasons.
Apple has dramatically improved the WindowServer design in the last few major versions of Mac OS X. It is now possible to have multiple users logged into different graphical sessions on one Mac through Screen Sharing. This seemingly simple improvement relied on a huge amount of behind the scenes effort from Apple's engineers.
However, Apple is unlikely to provide an easy way to cross launch applications as different users from within a single graphical user session. How would this benefit their customers?
If you want to explore this topic further, look for questions involving launchctl and running applications in other active user sessions.

A: There are good reasons NOT to edit files as root. Why not just copy them to a temporary file, edit this and copy back.
You could use visudo although this requires some knowledge of vi, but is OK for making simple changes to /etc/fstab or similar.
You could try setting the EDITOR environment variable and running visudo although I have never tried this with a graphic editor.

A: Sergei's answer didn't work for me on OS X 10.8.5
$ sudo /Applications/TextEdit.app/Contents/MacOS/TextEdit /etc/hosts
I got a permissions error message

Since sudoing the binary first, then double-clicking the file in Finder worked, I came up with the following less simple command
$ sudo -b /Applications/TextEdit.app/Contents/MacOS/TextEdit && sleep .5 && open -a /Applications/TextEdit.app /etc/hosts
You can make a function of it like Sergei's, if need be.


text:
Q: Glassfish: Error processing EjbDescriptor java.lang.NullPointerException I have a JEE6 application with several ejbs that each reference client jars.  For most of these I am having no issue whatsoever getting them deployed to my Glassfish 3.1.2 instance.  I have one however, that works fine until I reference it from my business layer application.  There I instantiate an object from the client just like I do in the all the other where it works perfectly.  Only when I reference this particular client jar in the application and then attempt to deploy I get the following from Glassfish:
[#|2012-11-08T08:38:22.773-0500|SEVERE|glassfish3.1.2|javax.enterprise.system.core.com.sun.enterprise.v3.server|_ThreadID=46;_ThreadName=Thread-2;|Exception while deploying the app [rpavis-app-im-1.0-SNAPSHOT]|#]

[#|2012-11-08T08:38:22.773-0500|SEVERE|glassfish3.1.2|javax.enterprise.system.core.com.sun.enterprise.v3.server|_ThreadID=46;_ThreadName=Thread-2;|Error processing EjbDescriptor
java.lang.RuntimeException: Error processing EjbDescriptor
    at com.sun.enterprise.deployment.util.EjbBundleValidator.accept(EjbBundleValidator.java:294)
    at com.sun.enterprise.deployment.EjbDescriptor.visit(EjbDescriptor.java:2578)
    at com.sun.enterprise.deployment.EjbBundleDescriptor.visit(EjbBundleDescriptor.java:734)
    at com.sun.enterprise.deployment.Application.visit(Application.java:1765)
    at com.sun.enterprise.deployment.archivist.ApplicationArchivist.validate(ApplicationArchivist.java:830)
    at com.sun.enterprise.deployment.archivist.ApplicationArchivist.openWith(ApplicationArchivist.java:277)
    at com.sun.enterprise.deployment.archivist.ApplicationFactory.openWith(ApplicationFactory.java:240)
    at org.glassfish.javaee.core.deployment.DolProvider.load(DolProvider.java:175)
    at org.glassfish.javaee.core.deployment.DolProvider.load(DolProvider.java:94)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.loadDeployer(ApplicationLifecycle.java:827)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.setupContainerInfos(ApplicationLifecycle.java:769)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:368)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:389)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:348)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:363)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1085)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:95)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1291)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1259)
    at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:461)
    at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:212)
    at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:179)
    at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$Hk2DispatcherCallable.call(ContainerMapper.java:354)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.NullPointerException
    at java.util.concurrent.ConcurrentHashMap.putIfAbsent(ConcurrentHashMap.java:1079)
    at java.lang.ClassLoader.getClassLoadingLock(ClassLoader.java:462)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:403)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:410)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:410)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:410)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:410)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    at com.sun.enterprise.deployment.util.EjbBundleValidator.accept(EjbBundleValidator.java:235)
... 39 more
|#]

[#|2012-11-08T08:38:22.782-0500|SEVERE|glassfish3.1.2|javax.enterprise.system.tools.admin.org.glassfish.deployment.admin|_ThreadID=46;_ThreadName=Thread-2;|Exception while deploying the app [rpavis-app-im-1.0-SNAPSHOT] : Error processing EjbDescriptor
java.lang.NullPointerException
    at java.util.concurrent.ConcurrentHashMap.putIfAbsent(ConcurrentHashMap.java:1079)
    at java.lang.ClassLoader.getClassLoadingLock(ClassLoader.java:462)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:403)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:410)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:410)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:410)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:410)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:356)
    at com.sun.enterprise.deployment.util.EjbBundleValidator.accept(EjbBundleValidator.java:235)
    at com.sun.enterprise.deployment.EjbDescriptor.visit(EjbDescriptor.java:2578)
    at com.sun.enterprise.deployment.EjbBundleDescriptor.visit(EjbBundleDescriptor.java:734)
    at com.sun.enterprise.deployment.Application.visit(Application.java:1765)
    at com.sun.enterprise.deployment.archivist.ApplicationArchivist.validate(ApplicationArchivist.java:830)
    at com.sun.enterprise.deployment.archivist.ApplicationArchivist.openWith(ApplicationArchivist.java:277)
    at com.sun.enterprise.deployment.archivist.ApplicationFactory.openWith(ApplicationFactory.java:240)
    at org.glassfish.javaee.core.deployment.DolProvider.load(DolProvider.java:175)
    at org.glassfish.javaee.core.deployment.DolProvider.load(DolProvider.java:94)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.loadDeployer(ApplicationLifecycle.java:827)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.setupContainerInfos(ApplicationLifecycle.java:769)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:368)
    at com.sun.enterprise.v3.server.ApplicationLifecycle.deploy(ApplicationLifecycle.java:240)
    at org.glassfish.deployment.admin.DeployCommand.execute(DeployCommand.java:389)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$1.execute(CommandRunnerImpl.java:348)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:363)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.doCommand(CommandRunnerImpl.java:1085)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl.access$1200(CommandRunnerImpl.java:95)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1291)
    at com.sun.enterprise.v3.admin.CommandRunnerImpl$ExecutionContext.execute(CommandRunnerImpl.java:1259)
    at com.sun.enterprise.v3.admin.AdminAdapter.doCommand(AdminAdapter.java:461)
    at com.sun.enterprise.v3.admin.AdminAdapter.service(AdminAdapter.java:212)
    at com.sun.grizzly.tcp.http11.GrizzlyAdapter.service(GrizzlyAdapter.java:179)
    at com.sun.enterprise.v3.server.HK2Dispatcher.dispath(HK2Dispatcher.java:117)
    at com.sun.enterprise.v3.services.impl.ContainerMapper$Hk2DispatcherCallable.call(ContainerMapper.java:354)
    at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
    at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
    at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
    at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
    at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
    at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
    at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
    at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
    at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
    at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
    at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
    at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
    at java.lang.Thread.run(Thread.java:722)
|#]

I have checked everywhere I know to check and am a total loss.  I feel like I am missing a configuration somewhere but after 2 days I just don't know where.  Can anyone see anything in this error that would help me determine where to even look?
Thank you!!!!

A: I found the answer.  It turns out I had a reference to a piece I had deleted in the ejb-jar.xml of the EJB.  The particular reference was only consumed by the business layer application and so was not processed until I made that change.  Bottom line, if you have deployment errors, look in the ejb-jar.xml configuration files of the root of the issue and you will likely find your answer there.


text:
Q: Smooch - message delivery failed I have successfully integrated Smooch (Sunshine Conversations) iOS SDK with version 9.0.0 but it randomly not working for some of the users.
Few users reported that their message not sent and provides the following error message and tapping on the following message also does nothing.
Message not delivered. Tap to retry.

Does anyone face this issue? I read the complete SDK document but there is no way to get an idea to resolve this issue.

A: This error is usually displayed when users are having connectivity issues - tapping on the prompt once the connection has stabilised will retry sending the message to the platform.
Use the widget in your dashboard or email support for further assistance.


text:
Q: расположение за пределами сетки
Весь основной контент находится в сетке, а вот линии с кругом находятся за пределами сетки. Подскажите, как лучше это реализовать?

A:

    section{
      position:relativ;
   }
   .line {
        position:absolute;
        top: -40:
        left:0;
    }

Как вариант)


text:
Q: Laravel routes not displaying error when required params missing I have some weirdness with Laravel at the moment and can't figure out what's wrong
If i don't include a parameter in the url, my controller should redirect but it doesn't.  I've tried dumping out some text but all I get it is a plain white screen unless I include the param in the url.  The param is set to optional.  Even if I remove the ? to make the param madatory, I still get a white screen where I would expect some sort of error.
The rest of the routes work fine apart from the route group in question.
Here is a cut down version of my controller
class CustomerRequirementsController extends Controller
{
    public function index($id = '')
    {
        debug('sdfgsdfgdsg');
        exit;
        //if the id has been removed from the url, redirect back to quotes summary table
        if(empty($id)) {
            return redirect()->route('quote.index');
        }
        ...
    }

Here is my routes in question
Route::prefix('quotes')->group(function () {
    Route::get('/{id?}', 'QuoteController@show')->name('quote.show');

    Route::post('/customer-requirements/add-group', 'CustomerRequirementsController@ajax')->name('customer-requirements.add-group');
    Route::get('/customer-requirements/{id?}', 'CustomerRequirementsController@index')->name('quote.customer-requirements.index');
    Route::resource('/customer-requirements', 'CustomerRequirementsController', ['except' => ['show', 'destroy']]);

A: I've had the same problem before.
Your first route Route::get('/{id?}', 'QuoteController@show')->name('quote.show'); is getting called before any other route.
Does your show function return a view....or anything? If it does, try moving to the bottom of the route group

A: Instead of making {id?} optional you make it compulsory by {id} may solve your problem.

A: You have a logical error, your if is never true because your $id param is never empty, it has assigned value always, in this case if it's not present in the url, it's assigned value is '' which fails empty check. So you would be better off if you $id = null and then if(is_null($id))

A: Laravel & Nginx :
If you are using virtual host add this line on vhost conf.
location / {
      try_files $uri $uri/ /index.php?$query_string;
}

Know More : https://laravel.com/docs/5.4#web-server-configuration


text:
Q: Bash - Easiest way to evaluate each line of a file and compare to desired range I'm looking for the most efficient way to do this. I have 7 seperate file that need to be filtered through.
Here's is how I started the first but keep in mind I need to do this 6 more times.
While read line do;

Onenum="$(awk '{print $12}' file.txt)"

Onenumssum="$(oneadd="$(tail + n 1 num2.txt)" && echo $onenum + $onenumadd | bc

Onenumdiff="$(onesub="$(tail - n 1 num2.txt)" && echo $onenum - $1sub | bc

if [ "$line" -ge "$onenumdiff" -a -le "$onenumsum" ]; then

Then $line if qualified need to be pushed to save file
File to filer looks like:
655.5
600
654
650
656
655
672
657
655
671
Ect.

I want to look through this file and find on the number that falls with in + or - 1 of 655 so the out put file should look like
654
655.5
655
655
656

A: Given:
$ cat file
655.5
600
654
650
656
655
672
657
655
671

You can use a tolerance and absolute value difference from a target to filter:
$ awk -v tgt=655 -v tol=1 'function abs(v) {return v < 0 ? -v : v}
                         abs($1-tgt)<=tol {print $1}' file
655.5
654
656
655
655

And then redirect that output to the desired file:
$ awk -v tgt=655 -v tol=1 'function abs(v) {return v < 0 ? -v : v}
                         abs($1-tgt)<=tol {print $1}' file > filtered


text:
Q: Cell-adjacency Graph of a Square Mesh Consider the list of points
pts = {{1, 1}, {1, 2}, {2, 1}, {2, 2}}

I want to use them to define a 2x2 square mesh using VoronoiMesh, where each cell has two neighbours. Following the discussion in this question, consider the following code
mesh = VoronoiMesh[pts, ImageSize -> Medium];
conn = mesh["ConnectivityMatrix"[2, 1]];
adj = conn.Transpose[conn];
centers = PropertyValue[{mesh, 2}, MeshCellCentroid];
g = AdjacencyGraph[adj, PlotTheme -> "Scientific",
   VertexCoordinates -> centers];
Show[mesh, g]

As one can see, unlike other meshes, this one does not seem to work exactly as I want, since the diagonal edge should not appear. Why is this happening? Any way of avoiding that edge and get

as one would expect from a square lattice?
Edit: As noticed in the comment section, some of the polygons seem to have sharing edges that are single points, which is enough for them to be considered neighbouring cells. This effect is unchanged with the size of the lattice. If I consider, for example, the points
pts = Flatten[Table[{i, j}, {i, 7}, {j, 5}], 1];

I get

Any ideas on how to solve this? Maybe omit the extra edge in a way that doesn't this or other non-square meshes. For example, considering a random VoronoiMesh, nothing seems to wrong, though it could, theoretically, go

A: We can delete the rows in our incidence matrix that correspond to these edges of length 0.
pts = Flatten[Table[{i, j}, {i, 7}, {j, 5}], 1];

mesh = VoronoiMesh[pts, ImageSize -> Medium];
conn = mesh["ConnectivityMatrix"[1, 2]];

lens = PropertyValue[{mesh, 1}, MeshCellMeasure];
$threshold = 0.;
keep = Pick[Range[MeshCellCount[mesh, 1]], UnitStep[Subtract[$threshold, lens]], 0];
conn = conn[[keep]];

adj = Transpose[conn].conn;
centers = PropertyValue[{mesh, 2}, MeshCellCentroid];
g = AdjacencyGraph[adj, PlotTheme -> "Scientific", VertexCoordinates -> centers];

Show[mesh, g]

A: L1 = 2; L2 = 2;
mesh = VoronoiMesh @ Tuples[Range /@ {L1, L2}];
centers = Rationalize @ PropertyValue[{mesh, 2}, MeshCellCentroid];

g1 = VertexReplace[GridGraph[{L2, L1}, PlotTheme -> "Scientific",
      VertexCoordinates -> centers[[Ordering @ centers]],
    {v_ :> Ordering[centers][[v]]}];

Show[mesh, g1]

For L1 = 7; L2 = 5; the same approach gives

A: You can delete the unwanted edges using EdgeDelete:
Show[mesh, EdgeDelete[g, UndirectedEdge[a_, b_] /;
   (FreeQ[0][Chop[Differences[PropertyValue[{g, #}, VertexCoordinates] & /@ {a, b}]]])]]

For g generated using pts = Flatten[Table[{i, j}, {i, 7}, {j, 5}], 1]; we get


text:
Q: Android: Theme.Holo is not black I am developing my new Android App and after I made the first layouts, I was wondering why everything is white (background) and not black like always before. So I figured out it is because of Theme.Holo.Light.DarkActionBar. I immediately changed it to Theme.Holo but nothing changed in the Emulator.
I googled the problem and they said that your minSDK has to be 11+, so I changed it to 11,12,13,14 but nothing changed again!
What can I do to see the old and nice black theme?

A: The values-v11 and values-v14 folders have styles.xml files in them that need to be updated in addition to the main one.

A: Use Theme.Holo. Since you elected not to post any source code, it is impossible to indicate where you are going wrong. However, if you run an app using a theme based upon Theme.Holo -- such as this sample app -- you get a dark background.
The easiest way to get Theme.Holo is to not specify a theme at all, as Theme.Holo is the default for apps with android:targetSdkVersion of 11 or higher and running on an API Level 11+ device.
The sample app I linked to takes a more elaborate approach, courtesy of Eclipse's code generators:

*

*It has res/values/styles.xml defining AppTheme as inheriting from the old dark Theme:

*It has res/values/styles.xml defining AppTheme as inheriting from Theme.Holo:

*It uses AppTheme in its manifest (which for some reason is not displaying in this answer, so you will have to settle for clicking the link)
Hence, it will use Theme.Holo on API Level 11+ devices and Theme on older devices. Both supply a dark background.


text:
Q: Interact with buttons inside of an aria list-item In our current frontend we want to add accessibility improvements. The current challenge is to make the list of items including additional actions more accessible. Our document structure is based on the following idea:

Product A

First

Second

At the moment it's possible to select the list-items, however the a11y border highlights the entire list item (div.product). Hence it's not possible to focus the buttons. Defining a sublist using list/listitem roles for div.product-actions was not of benefit. Do you have any ideas how to achive this?


text:
Q: C# DirectX Performance For a falling sand game I need to lock a surface, then modify the pixels according to a set of rules, and then unlock it. The Texture has a Size of 800x500 and has the Format A8R8G8B8.
TEXTURE DECLARATION
texture = new Texture(device, 800, 500, 1, Usage.Dynamic, Format.A8R8G8B8, Pool.Default);

The Update-Method (which should ideally be called about 40/s)
    public new void Update()
    {
        count++;
        byte[] data = (byte[])texture.LockRectangle(typeof(byte), 0, LockFlags.None, 800 * 500 * 4);
        for (int i = 0; i < 1600000; i++)
        {
            data[i] = 255;
        }
        texture.UnlockRectangle(0);
    }

I have a highend graphics card and this simple loop reduces my fps rate to 10-13.
Is there a faster way in DirectX to directly change the pixels of a surface?

A: What are you doing is reading this texture from memory of graphics card into computer memory, then modyfying it and then writing it back. This obviously means huge performance kill because you need to wait for copying between both memories.
Usualy, this kind of operation is achieved using Shaders all on graphics card.

A: Usually game model is stored in regular memory and handled by CPU, while graphic card is used purely to render results. If you have no particular reasons not go this way it would be easier to write and debug.
In you case you seem to have all game data in video memory. As Euphoric pointed out in this case you should make all logic run in shaders. There are plenty of samples how to perform data manipulation using several texture targets (2 would be probably enough in your case).
I'd recommend to find "game of life" sample written using shaders (search - http://www.bing.com/search?q=directx+shader+sample+%22game+of+life%22, I'd probably start with this one - http://www.xnainfo.com/content.php?content=21). Game of life is probably simplest thing close enough to waht you trying to achieve. DirectX SDK and Nvidia SDK are good sources of samples too like - http://developer.download.nvidia.com/SDK/9.5/Samples/3dgraphics_samples.html.
For more samples search for "prostprocess shader" as pretty much all of them are implemented by manipulating final rendered image with shaders.


text:
Q: MongoDB: sort collection A using collection B property and vice versa I have collection A that have properties :

*

*subscriptionPlan:string

*businessId:string

collection B properties:

*

*name:string

*createdAt:number

*businessId:string

how do I sort by: name, createdAt, and subscriptionPlan ?


text:
Q: "Critical value at 5%" or "critical value at 95%": what is the right way to say it? I have a quite simple (and not particularly intriguing) question about the way to present a test. I was wondering what is the right expression (or more widespread) when I talk about critical values.
In particular, if for example the rejection region is defined by the 95 percentile, is it preferred to say that I am using the critical value of the, say, t "at 95%" or "at 5%"?
Is is correct in both ways? Is one "more correct" than the other?
Do I incur in some ambiguity if I do not specify further? Are there some conventions? Do they vary based on the distribution I am referring?
Thank you very much

A:
In particular, if for example the rejection region is defined by the 95 percentile

Consider three hypothesis tests for a parameter, with alternatives respectively:
$$H_{1a}: \theta < \theta_0\\
H_{1b}: \theta > \theta_0\\
H_{1c}: \theta \neq \theta_0\,,$$
all conducted with a significance level of $\alpha = 0.05$.
Further, assume that the test statistic is a simple function of $\hat \theta - \theta_0$ and has a symmetric distribution, so everything is 'nice and simple', but includes the $t$ test you mention as an example.
The 95th percentile comes up in computing only one of those three rejection regions.
The test is a test at the 5% level because that's what you specify when you choose the type I error rate.
If you're talking about the hypothesis test itself, the phrase "95%" need never be mentioned. If for some reason you need to refer to how you calculated the critical value, in one of the above cases you compute the $1-\alpha$ quantile of the distribution of the test statistic, and in the other cases you compute the $\alpha$ and the $1-\alpha/2$ quantiles. You can mention those if you need to for some reason but they're not part of how you describe the hypothesis test itself. You choose your rejection region to be of size $\alpha$.
[In any case, pedagogy aside, these days it would be odd to compute a critical value when packages give $p$ values as a matter of course. Why would one compute a critical value when the $p$ value allows a reader to conclude whether they would reject at any significance level they wish?]
If you read the wikipedia article on Statistical Hypothesis Testing, you'll see that (in spite of some poor wording), even for the case where the critical value is computed, the discussion is in terms of $\alpha$. This is no accident.

A: I generally think of a critical value as indicating ranges in the sampling distribution of the test statistic under the null hypothesis which we consider to be consistent with that null hypothesis. Hence I would say that -1.96 and 1.96 are critical values for the central 95% of the asymptotic distribution of the test statistic under $\mathcal{H}_0$. We would trust that anything falling beyond such a range, leading to a rejection of the null hypothesis, would be a false positive error with probability 1/20.
In general, there are much more useful values to report than a critical value. Take, for instance, the 95% confidence interval. Rather than indicating an interval which is consistent with an idea (that idea being the null hypothesis), you get an interval which is consistent with that data. The null hypothesis can be reduced to a singular statistic (such as a 0 mean difference or a 1/1 odds ratio), and we simply look whether the CI is consistent with that point or not to make inference.


text:
Q: Textbox that can only accept integer ranging from 00 - 60 I want to validate the users input in a textbox by not accepting anything except integers ranging from 00 to 60.
Conditions:

*

*If the user input 0 or input nothing the system should considered it as 00 (take note that I padded it with 0.

*I know that I can do this also in numericupdown, but for some reason I can't use that.

*I need to apply this in 20 textboxes.

This is the code, actually it is working. My only problem is I can't apply it to 20 textboxes, it is only working in tb_hour_1 textbox, is there something that I can do instead of indication tb_hour_1.text in this line of code Dim num As Integer = Integer.Parse(String.Format("{0}{1}", If(Tb_Hour_1.Text = String.Empty, "", Tb_Hour_1.Text), e.KeyChar.ToString())).
Code:
    Private Sub Tb_Hour_1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Tb_Minute_2.KeyPress, Tb_Minute_1.KeyPress,
    Tb_Hour_2.KeyPress, Tb_Hour_1.KeyPress

    Dim Min_Num As Integer = 0
    Dim Max_Num As Integer = 60

    If e.KeyChar <> ControlChars.Back Then
        'allow backspace for deleting
        e.Handled = Not Char.IsNumber(e.KeyChar)
        'allow numbers only
        If Not e.Handled Then
            Dim num As Integer = Integer.Parse(String.Format("{0}{1}", If(Tb_Hour_1.Text = String.Empty, "", Tb_Hour_1.Text), e.KeyChar.ToString()))
            If num < Min_Num OrElse num > Max_Num Then
                e.Handled = True
            End If
        End If
    End If
End Sub

A: You should better create a UserControl for this purpose. which validates the input and range and instead of creating 20 textboxes, you can use your custom control then. Also, MaskedTextBox control can also be used to avoid checking length of text and it can only allow digits as well.
Also, a shortcut could be to list down all the remaining control's event like this:
Private Sub Tb_Hour_1_KeyPress(sender As Object, e As KeyPressEventArgs) Handles Tb_Minute_2.KeyPress, Tb_Minute_1.KeyPress,
    Tb_Hour_2.KeyPress, Tb_Hour_1.KeyPress, ....... further control events

A: Using a common event handler for all TextBoxes is Ok. Just replace Tb_Hour_1 by a cast, i.e. :
Ctype(sender,TextBox)


text:
Q: Typesense not listen to Firebase DB change As the title, I use Typesense self-hosted server on my localhost. When I created a new document in Firestore, Typesense did not automatically create a new document in collection.
I follow this guide: https://typesense.org/docs/guide/firebase-full-text-search.html#step-1-run-typesense
Here my code:

*

*runServer.js (to run Docker Typesense)

const functions = require("firebase-functions");
const Typesense = require("typesense");
const { exec } = require("child_process");
const command = `docker run -p 8108:8108 -v/tmp/typesense-data:/data typesense/typesense:0.23.1 \
--data-dir /data --api-key=xyz --enable-cors`;
exec(command, (err, stdout, stderr) => {
  if (!err && !stderr) console.log("Typesense Server is running...");

  if (err) {
    console.log("Error running server: ", err);
  }

  if (stderr) {
    console.log("Error running server: ", stderr);
  }

  if (stdout) {
    console.log("Server output: ", stdout);
  }
});
const TYPESENSE_CONFIG = {
  nodes: [
    {
      host: "localhost",
      port: "8108",
      protocol: "http",
    },
  ],
  apiKey: "xyz",
};
const client = new Typesense.Client(TYPESENSE_CONFIG);
exports.onHouseCreate = functions.firestore
  .document("/houses/{houseID}")
  .onCreate((snapshot, context) => {
    // Grab the document id as id value.
    id = context.params.houseID;
    const { address, area, createdAt, description, detailsummary, name, price, view } = snapshot.data();
    document = { id, address, area, createdAt, description, detailsummary, name, price, view };
    console.log(document)

    // Index the document in houses collection
    return client.collections("houses").documents().create(document)
  });
exports.onHouseUpdate = functions.firestore
  .document("/houses/{houseID}")
  .onUpdate((change, context) => {
    // Grab the document id as id value.
    id = context.params.houseID;
    const { id ,address, area, createdAt, description, detailsummary, name, price, view } = change.after.data();
    document = { id, address, area, createdAt, description, detailsummary, name, price, view };
    console.log(document)
    // Index the document in houses collection
    return client.collections("houses").documents().update(document);
  });
exports.onHouseDelete = functions.firestore
  .document("/houses/{houseID}")
  .onDelete((snapshot, context) => {
    // Grab the document id as id value.
    id = context.params.houseID;
    return client.collections("houses").documents(id).delete(document);
  });

*

*loadData.js (to index existing data in Firestore)

const Typesense = require("typesense");
const functions = require("firebase-functions");

module.exports = (async () => {
  const TYPESENSE_CONFIG = {
    nodes: [
      {
        host: "localhost",
        port: "8108",
        protocol: "http",
      },
    ],
    apiKey: "xyz",
  };

  console.log("Config: ", TYPESENSE_CONFIG);

  const typesense = new Typesense.Client(TYPESENSE_CONFIG);

  const schema = {
    name: "houses",
    fields: [
      { name: "id", type: "string" },
      { name: "address", type: "string" },
      { name: "area", type: "int32", sort: true },
      { name: "createdAt", type: "string", sort: true },
      { name: "description", type: "string" },
      { name: "image", type: "string[]" },
      { name: "detailsummary", type: "string" },
      { name: "name", type: "string" },
      { name: "price", type: "int32", sort: true },
      { name: "view", type: "int32", sort: true },
    ],
    default_sorting_field: "view",
  };

  const houses = require("./data/houses.json");

  console.log("Creating schema...");
  console.log(JSON.stringify(schema, null, 2));

  await typesense.collections().create(schema);

  console.log("Populating collection...");

  try {
    const returnData = await typesense
      .collections("houses")
      .documents()
      .import(houses);

    console.log("Return data: ", returnData);
  } catch (err) {
    console.error(err);
  }
  exports.onHouseCreate = functions.firestore
    .document("/houses/{houseID}")
    .onCreate((snapshot, context) => {
      // Grab the document id as id value.
      id = context.params.houseID;
      const {
        address,
        area,
        createdAt,
        description,
        detailsummary,
        name,
        price,
        view,
      } = snapshot.data();
      document = {
        id,
        address,
        area,
        createdAt,
        description,
        detailsummary,
        name,
        price,
        view,
      };
      console.log(document);

      // Index the document in books collection
      return typesense.collections("houses").documents().create(document);
    });
  exports.onHouseUpdate = functions.firestore
    .document("/houses/{houseID}")
    .onUpdate((change, context) => {
      // Grab the document id as id value.
      id = context.params.houseID;
      const {
        id,
        address,
        area,
        createdAt,
        description,
        detailsummary,
        name,
        price,
        view,
      } = change.after.data();
      document = {
        id,
        address,
        area,
        createdAt,
        description,
        detailsummary,
        name,
        price,
        view,
      };
      console.log(document);
      // Index the document in books collection
      return typesense.collections("houses").documents().update(document);
    });
  exports.onHouseDelete = functions.firestore
    .document("/houses/{houseID}")
    .onDelete((snapshot, context) => {
      // Grab the document id as id value.
      id = context.params.houseID;
      return typesense.collections("houses").documents(id).delete(document);
    });
})();

I read that tutorial and it does not tell me where to put the code so I try to add both sample code to all files but it didn't work. It can only search the existing data in Firestore, not the new document added after running Typesense server
Really appreciate your help !


text:
Q: Jetpack compose button action onClick leak we've encountered a problem with Jetpack Compose button actions leaking. We provide a class with resources (e.g strings, colors, and BUTTON ACTIONS):
data class CameraOnBoardingComposeViewResources(val title: String, val buttonTitle: String, val buttonAction: () -> Unit)

This data class is created in the fragment like so:
val resources = CameraOnBoardingComposeViewResources(
    "Title", "ButtonTitle"
) { navigate() }

And in our composable we use those resources like so:
@Composable
fun composeOnBoardingView(resources: CameraOnBoardingComposeViewResources) {
    Surface(
        shape = RoundedCornerShape(4.dp),
        color = colorResource(R.color.idenfyMainColorV2),
        modifier = Modifier
            .height(42.dp)
            .padding(start = 16.dp, end = 16.dp)
            .clickable(onClick = resources.buttonAction)
            .fillMaxWidth()
    )
}

The problem is that buttonAction leaks. How can we avoid this leak, should we somehow dispose of it, or do we need to change this architecture a bit?
EDIT After CommonsWare
Ok, I've located the problem, and it is indeed inside the composeOnBoardingView composable. It's this code snippet:
val currentInstructionDescription: MutableState<String> = remember {
   mutableStateOf("")
}

val progress = remember { mutableStateOf(0.0f) }

val handler = Handler(Looper.getMainLooper())
exoPlayer?.apply {
    val runnable = object : Runnable {
        override fun run() {
            progress.value =
                exoPlayer.currentPosition.toFloat() / exoPlayer.duration.toFloat()
            currentInstructionDescription.value = InstructionsDescriptionBuilder.build(
                context,
                (resources.documentCenterImageUiViewModel as OnBoardingCenterImageUIViewModel.DocumentResource).step,
                exoPlayer.currentPosition.toInt() / 1000
            )
            handler.postDelayed(this, 1000)
        }
    }
    handler.post(runnable)
}

I tried disposing the handler like this:
val lifecycleOwner: LifecycleOwner = LocalLifecycleOwner.current

DisposableEffect(lifecycleOwner) {
    onDispose {
        handler.removeCallbacksAndMessages(null)
    }
}

But that did not solve the problem. Any ideas?
EDIT
The issue is solved thanks CommonsWare! We switched to the LaunchedEffect and coroutines for an every-second in-composition timer, rather than Handler


text:
Q: SWIG Or Boost -for Mapping C structures to Python I have requirement to map C Structures to Python. Any suggestion what will be the best approach to go for SWIG or Boost with least complexity.

A: If your structures are in pure C, then it's very easy with both methods. Or, you may consider ctypes, though my favorite is SWIG -- it automates things a lot.


text:
Q: Jekyll/Github Pages -- index.html not being written? Cross-posted in a Github issue at https://github.com/SeanKilleen/seankilleen.github.io/issues/189

Digging into an issue with GitHub pages that appears like it might be recent.
I noticed an up-tick in 404s via Google Analytics. It appears that posts with trailing slashes are becoming 404'd, but appeared just fine without the slash.
My local Jekyll instance generates the following structure for how-to-leave-a-company-well.md from Feb 2015:

/2015
   /02
    /how-to-leave-a-company-well.html
    /how-to-leave-a-company-well
      /index.html

So, the following URLs work just fine locally:

*

*http://localhost:4000/2015/02/how-to-leave-a-company-well

*http://localhost:4000/2015/02/how-to-leave-a-company-well.html

*http://localhost:4000/2015/02/how-to-leave-a-company-well/index.html

*http://localhost:4000/2015/02/how-to-leave-a-company-well/
Those last two URLs that I've bolded do not seem to exist on my published site after GitHub Pages generates the documents.
I cannot reach http://seankilleen.com/2015/02/how-to-leave-a-company-well/ or http://seankilleen.com/2015/02/how-to-leave-a-company-well/index.html
This seems to indicate to me that GitHub Pages is doing something differently than my Jekyll installation. Given that the 404 spike is recent, I'm wondering if there might have been a change related to this.
Does anyone have a thought on how I might be able to diagnose this? It's a bit of a black box for me when my local is doing what I expect and I can't see the Github Pages process.

A: Jekyll 3 changed the way the permalinks worked, and dropped the trailing slash if your permalink setup did not contain one - yours does not contain a trailing slash at the end of your permalink in the config file. Jekyll 3 now respects that and thus your page is a 404 when there is a trailing slash in the url (since you want it without it).
https://jekyllrb.com/docs/upgrading/2-to-3/#permalinks-no-longer-automatically-add-a-trailing-slash
You may want to check which version of jekyll you have installed - you may be on 2.x and GH is now 3.x
When working locally, are you telling jekyll to use the GH pages gem? if you
don't do this you may get different behavior on GH than local. I do not do this, so I can't tell you how to do it (or if this particular issue would happen), but I do know that you should do it if you want to preview locally what you will get when serving via GH.


text:
Q: Update callback running after create via Accepts Nested Attributes - Rails When I create a Blog object, both the create and update callbacks are triggered in sequence.
In this case, updating the Blog object deletes all existing images and generates new ones. I want to only generate new images on create, and delete and re-create them on update.
I think it's due to the nested object via accepts_nested_attributes_for, but I can't seem to find a working alternative.
Is this a Rails bug? How can I force the correct callbacks to only trigger once per action?
  class Blog
    has_many :posts
    has_many :images

    accepts_nested_attributes_for :posts

    after_update :destory_existing_images, if: -> { images.any? }
    after_commit :create_images, on: [:update, :create], if: -> { images.none? }

    private

    def destory_existing_images
      images.destroy_all
    end

    def create_screenshots
      images.create!(tag: title)
    end
  end

A: It would be better if you use separate callbacks. Use after_create_commit for initialization and after_update_commit to update the images.
You could also check if the title changed before you update your images. Dirty API is great for that, your condition then would look like if: -> { images.any? && saved_change_to_title? }.
Solution
  class Blog
    has_many :posts
    has_many :images

    accepts_nested_attributes_for :posts

    after_create_commit :create_images, if: -> { images.none? }
    after_update_commit :update_images, if: -> { images.any? && saved_change_to_title? }

    private

    def update_images
      images.destroy_all
      images.create!(tag: title)
    end

    def create_images
      images.create!(tag: title)
    end
  end


text:
Q: Encoding and Serialization Code Gives Different Result C# and Python I tried to convert this C# code (encoding and serialization) to Python but results are different. Why?
    var dictt = new Dictionary<string, object>
    {
        { "aaa", "6mjDx3Cya4JvbTLMenPpXA==" },
        { "bbb", "4U5M+V2yoIA7rWj46rdhTBgpEjf1zYK0m11lDM7DRCI="},
    };

    JavaScriptSerializer serialzr = new JavaScriptSerializer();

    return Convert.ToBase64String(Encoding.UTF8.GetBytes(serialzr.Serialize(dictt))); //eyJpdiI6IjZtakR4M0N5YTRKdmJUTE1lblBwWEE9PSIsInZhbHVlIjoiNFU1TStWMnlvSUE3cldqNDZyZGhUQmdwRWpmMXpZSzBtMTFsRE03RFJDST0ifQ==

dictt = {
    "aaa": "6mjDx3Cya4JvbTLMenPpXA==",
    "bbb": "4U5M+V2yoIA7rWj46rdhTBgpEjf1zYK0m11lDM7DRCI="
    }

    y = json.dumps(dictt)
    #y= {"aaa": "6mjDx3Cya4JvbTLMenPpXA==", "bbb": "4U5M+V2yoIA7rWj46rdhTBgpEjf1zYK0m11lDM7DRCI="}
    json_object = json.loads(y) #convert it to json, like serialize in C#
    # json_object = {'aaa': '6mjDx3Cya4JvbTLMenPpXA==', 'bbb': '4U5M+V2yoIA7rWj46rdhTBgpEjf1zYK0m11lDM7DRCI='}
    json_object_utf8_encoded = str(json_object).encode('utf8') #encode utf8
    #json_object_utf8_encoded = b"{'aaa': '6mjDx3Cya4JvbTLMenPpXA==', 'bbb': '4U5M+V2yoIA7rWj46rdhTBgpEjf1zYK0m11lDM7DRCI='}"
    json_base64 = base64.b64encode(json_object_utf8_encoded) #convert to base64 string
    #json_base64 = "b'eydpdic6ICc2bWpEeDNDeWE0SnZiVExNZW5QcFhBPT0nLCAndmFsdWUnOiAnNFU1TStWMnlvSUE3cldqNDZyZGhUQmdwRWpmMXpZSzBtMTFsRE03RFJDST0nfQ=='"
    json_base64_str = json_base64.decode("utf-8")
    return json_base64_str
    #eydpdic6ICc2bWpEeDNDeWE0SnZiVExNZW5QcFhBPT0nLCAndmFsdWUnOiAnNFU1TStWMnlvSUE3cldqNDZyZGhUQmdwRWpmMXpZSzBtMTFsRE03RFJDST0nfQ==

A: There's a small difference between the following two python commands, resulting with two different outputs: " vs. '.
While this one:
serialized = json.dumps(dict)
print(serialized)

outputs:
{"aaa": "6mjDx3Cya4JvbTLMenPpXA==", "bbb": "4U5M+V2yoIA7rWj46rdhTBgpEjf1zYK0m11lDM7DRCI="}

This one:
serialized = json.dumps(dict)
deserialized = json.loads(serialized)
print(str(deserialized))

outputs:
{'aaa': '6mjDx3Cya4JvbTLMenPpXA==', 'bbb': '4U5M+V2yoIA7rWj46rdhTBgpEjf1zYK0m11lDM7DRCI='}

You work with the latter one: you're unnecessarily deserializing the json, and then calling str upon it, giving you the different result. Just drop the json.loads step.
EDIT:
The returned values (C# vs python) will still not match, because C# serializer (whether it's JavaScriptSerializer or the more common JsonConvert.Serialize of Newtonsoft) outputs a json with no spaces:
{"aaa":"6mjDx3Cya4JvbTLMenPpXA==","bbb":"4U5M+V2yoIA7rWj46rdhTBgpEjf1zYK0m11lDM7DRCI="}

while python's json.dumps outputs a json with spaces:
{"aaa": "6mjDx3Cya4JvbTLMenPpXA==", "bbb": "4U5M+V2yoIA7rWj46rdhTBgpEjf1zYK0m11lDM7DRCI="}

Even if you'd pass an indentation argument to json.dumps (e.g., json.dumps(dict, indent=2)), you can't do that with JavaScriptSerializer, and although you could do it with Newtonsoft's JsonConvert.Serialize it would still not work, since the latter uses CRLF characters for the indentation, while python doesn't.
That being said, it shouldn't matter, because the logical output is the same: A Base64 encoding of the serialized dictionary.


text:
Q: Определить цифры регулярным выражением я очень плохо разбираюсь в регулярах, как мне сделать, чтобы он только определял цифры? Если только есть одна буква, то не пропускал!
if (!preg_match("/[0-9]/",$g1,$matchs))
{
$g1 = $matchs[1];
echo "ошибка 0";
exit();
}

если к примеру в $g1 = "http1";
он его пропускает а нужно что бы была ошибка фильтрация только цифры!
Подскажите, пожалуйста.
A: ^\d{1,}$

A: а зачем тут регулярные выражения?..
if (($a + 0) eq $a) {...}


text:
Q: .NET Choosing between Structures and Classes Duplicate: When should I use a structure instead of a class?
Just wondering if anyone can provide some advice or examples of when it is best to use a structure over a class in .NET or vice versa
I have done some background reading and understand the differences between two, ie structures are stored on the stack, classes on the heap ect. But havent been able to find some clear examples where one would provide a benefit over the other.
Many Thanks

A: To quote a good answer to the same question (When should I use a struct instead of a class?):

MSDN has the answer: Choosing Between
  Classes and Structures.
Basically, that page gives you a
  4-item checklist and says to use a
  class unless your type meets all of
  the criteria.
Do not define a structure unless the
  type has all of the following
  characteristics:

*

*It logically represents a single value, similar to primitive types
  (integer, double, and so on).

*It has an instance size smaller than 16 bytes.

*It is immutable.

*It will not have to be boxed frequently.

A: Use a class unless you've got very specific reasons to use a struct.  See  Questions about Structs for some of the specific reasons.
Edit: One of the possible advantages to a struct over a class is that you can't ever have null instances.  See Is there a way to require that an argument provided to a method is not null?

A: I prefer Classes.
Structure TestStruct
    Dim Name as String
End Structure

Dim x as TestStruct

If x Is Nothing Then
'ALWAYS returns false. A class would return true. Nullability, baby.

A: I found this page for you. It explains where to use one or the other, the benefits and drawbacks of each one.
http://www.jaggersoft.com/pubs/StructsVsClasses.htm
Regards!!!

A: Very basic guideline, and not even .NET specific:
Use CLASS for everything except when you need very small, very simple container.
if you don't want properties nor functions, you should use a class.
a good example in my opinion for a struct is when you need to make an array of items, but the items is a "pair" of int and string.
something basic like that


text:
Q: paper_trail show log of changes to a member (no method for each error) I'm trying to show a log for changes on a particular member in the show view. The members information is there and the version history is working.
I'm having troubles showing versions/changes log for that particular member. I get this error:
 ActionView::Template::Error (undefined method `each' for #<PaperTrail::Version:0x007f55f23ee348>):

I have this in my controller:
    # Detailed Member Profile
    def show
        @versions = PaperTrail::Version.find(params[:id])
        @members_main = Members::Main.find(params[:id])
    end

And this in my show view:

        <% @versions.each do |version| %>

                <%= l(version.created_at, format: "%-d.%m.%Y %H:%M:%S %Z") %>

                Event ID: <%= version.id %>

                Target: <%= version.item_type %>
                (id: <%= version.item_id %>); action <%= version.event %>;

                    More info:

<%= version.object %>

        <% end %>

Model:
class Members::Main < ActiveRecord::Base

    # Add Paper Trail
    has_paper_trail

end

A: I think the find method of the ActiveRecord returns only one object. And that object does not have an each method.
See the documentation here.
In particular this line @versions = PaperTrail::Version.find(params[:id]). It returns an object for the given id. But that object does not have a method called each. That is your error text.
What you probably expected was that it returns an array, but it obviously did not.
Try to change it to @versions = PaperTrail::Version.find([params[:id]]) and I believe it should work. Note the brackets.


text:
Q: How to access a collection through another collection using ActiveRecord First off all, excuse me if the title is not very accurate.
Let's say I have these models:
class User < ActiveRecord::Base
    belongs_to :user_group
end

class UserGroup < ActiveRecord::Base
    has_many :users
    has_many :records
end

class Record < ActiveRecord::Base
    belongs_to :user_group
    has_many :invoices
end

class Invoice < ActiveRecord::Base
    belongs_to :record
end

I want to access from the current_user (User) to all the unpaid Invoices of his UserGroup. Something like this:
current_user.user_group.records.invoices.where(:payment => false)

Obviously the code above doesn't work. The closest approach I've found is this:
class UserGroup
  def unpaid_invoices
    records.map{|r| r.invoices.unpaid}
  end
end

class Invoice
  def self.unpaid
    where(:payment => false)
  end
end

And then I can do:
current_user.user_group.unpaid_invoices

However this is not scalable, because when I want to use a new condition, like invoices with amounts bigger than $1000, I need to create two new methods in those models.
There is some magic-rails-way to do this? Am I missing something? Thank you!

A: You can add something like that into UserGroup:
has_many :invoices, :through => :records


text:
Q: jquery.payments TypeError: undefined is not a function So I have the following issue:
Running Ruby on Rails 4.1.5
jquery.payments.js.coffee is in vendor lib
both jquery.min and jquery.payments are loaded correctly. (jquery payments after jquery.min)
I have a payment form with an input with the id "creditcard"
When I call in console:
$('#creditcard').payment('formatCardNumber');

I get:

TypeError: undefined is not a function

How can I make the input be restricted only to credit card digits?

A: I was using jQuery 1.6.4
After upgrading to the latest jQuery version (1.11) this issue is not longer.


text:
Q: Easy brain stumper, a better algorithm This was at a community college.  I failed it, but want to know the answer.
The problem is this: you have an 2D array of structs that represents an image.  Each struct has a red, green, blue, and alpha value.  There can be more info, but not required to solve the problem.
Say the image is 4000x4000 or 16 Million elements.  Every element needs to be updated/checked on every turn.
For each element you need to:

*

*Set the red byte to 50 if < 50 or set to 205 > 205

*Set the green byte to a random value between 0 and 255 using rand()

*Modify blue in an "interesting" way.

"You can't brute force this, think in a smarter way; you need a better algorithm"
I basically did a loop.  I was the fastest but he said it was "about finding a better algorithm, not using using cute compiler and pointer tricks".
Also needs to be in pure C.  No OpenMP/Threads or OpenGL shading, OpenCL, etc... just ANSI C with standard libraries (even GNU/POSIX libraries were forbidden).
I asked about bitwise operations and he said that "those are very expensive in C [??] and it's about writing a fast and solid algorithm, not these cute tricks you keep coming up with".
So any hints?

A: Yes, let's all figure out how to write an alogirithm to "Modify blue in an 'interesting' way.", as long as it's "fast and solid". Glad community colleges are teaching so strong. I've never heard that bitwise operations are expensive. Expensive compared to what? When you say that you were "the fastest", do you mean that you were the first to come up with an answer, or that your answer was the most efficient implementation? If you're forced to store the data as a 2D array of structs (as opposed to a tree), I'm not sure what else you can expect to do. So you know that you failed it, but were not told the correct answer? Now that's what I call edjumacation!

A: The rand() calls will most likely dominate the runtime of the program, so there is no point in trying to be smart with a smart loop structure or fancy bitwise operations.
So it is likely that the most effective optimization would actualy be spliting each value from rand into bytes (depends on rand implementation), to do less calls.

As for what the teacher actually wanted, here is a wild guess:

*

*Use rand to set the green byte

*Use some fancy method to set the red byte

*Include the blue byte somewhere in your fancy method, so it gets a new value as a convenient side effect

*End up with a cryptic and pointless one-liner (because he thinks the less lines a program has the faster is must run)

A: Solution 1
The single most important point in updating a big array is exploiting the memory hierarchy by using locality. This hides memory latency and thus accelerates you algorithm.
First, you want to process the colors of each pixel together as they lie in the same struct. The processing of a pixel fits entirely in the register set of modern CPUs. Depending on the actual storage some bit/byte/word tweaking is possible here but it sounds like your instructor doesn't place emphasis on this point.
Second, you want to update the pixels in the order they are stored in memory. This means looping over the inner array dimension in the inner loop. This enables the compiler and the CPU to access the pixels efficiently in big chunks (keywords cache-lines and prefetching).
Solution 2
A completely different approach is adding a layer of indirection.
Instead of accessing the image array directly, route all accesses through accessor functions. Now you can write accessor functions that implement the required changes to the image without needing to access the array or even loop over all pixels at all!
This is like the Decorator pattern in an object-oriented language.

A: This looks like an interview question. It's silly! If you have to visit each pixel, then you have to use loops! After all, this is their purpose. The best thing you can do is doing a single loop instead of two and edit more pixels on every iteration

A: ok - i see something interesting...
'on every turn'
so maybe there is some optimization to not perform red checking after the first iteration since those values will be static

A: The only way I can figure this is that "Say the image is 4000x4000 or 16 Million elements. Every element needs to be updated/checked on every turn." actually means "Say the image is 4000x4000 or 16 Million elements. Every element would need to be updated/checked on every turn."
Then, it says "Also needs to be in pure C. No OpenMP/Threads or OpenGL shading, OpenCL, etc..." Why mention "OpenGL shading" for such a basic question?
I think (I'm only guessing) the actual question had more detail and was pushing the student towards clipping the image processing in some way (ie. some part of the image is covered or off screen, so you can skip those bits).
It's just a guess. As my kid brother would say "It don't make sense otherwise!!!"

A: Maybe the instructor was looking for some performance gained by processing the colors in separate loops:
for each pixel
    red pixel = (red pixel < 50) ? 50 : ((red pixel > 250) ? 250 : red pixel);
end-for

for each pixel
    green pixel = 256 * rand()
end-for

for each pixel
    blue pixel = (green pixel * 1024) % 256;
end-for

This may have some better performance, but only profiling will tell.
Edit 1:
An advantage to this method is that each color can be processed by an independent thread or core.


text:
Q: OnChange Typescript input I want to be able to trigger an on change when a file is selected from a input(file). I want the triggered event to set a textbox to be the name of the file.
I am using HTML5, Typescript and Angular2. I can't figure out or find an example of exactly how to produce the behavior I am after.
see my code below:
component.ts
import { Component } from '@angular/core';
import { Http } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';

@Component({
    selector: 'testConnection',
    // ignore error on require
    template: require('./testConnection.component.html')
})
export class TestConnectionComponent {
    public http: Http;
    public requestData: RequestData;

    public constructor(http: Http) {
        this.http = http;

        (<HTMLInputElement>document.getElementById('fileInput')).onchange = (ev: Event) => {
            var fileInput = (<HTMLInputElement>ev.srcElement).files[0];

            var fileTextbox = (<HTMLInputElement>document.getElementById('fileTextbox'));
            fileTextbox.value = fileInput.name;
        }
    }

    public testButtonClick() {

        // Iniatialise Request object
        let request: RequestData;
        request = { "CountryCode": "", "SiteIDList": "" };

        // Get site(s)
        var siteIdList = (<HTMLInputElement>document.getElementById('siteIDInput')).value;

        // Get selected country
        var countryCode = (<HTMLInputElement>document.getElementById('countryDropdown')).value;

        // Veryify contents is just site ids.
        // TODO
        request.CountryCode = countryCode;
        request.SiteIDList = siteIdList;

        // Set Http POST options
        let headers = new Headers({ 'Content-Type': 'application/json' });
        let options = new RequestOptions({ headers: headers });

        // Call Api with test connection data
        this.http
            .post('/api/TestConnection/TestConnection', JSON.stringify(request), options)
            .subscribe(data => {
                // alert request ok
                alert('ok');
            }, error => {
                // Log error
                console.log(error.json());
            });
    }
}

interface RequestData {
    SiteIDList: string;
    CountryCode: string;
}

component.html

Test Site Connection

This will allow you to check the connectivity of a set of sites by either individually or uploading a CSV file of Site IDs.

Manual Test

            Select the country and the sites you want to test.

Multiple sites can be selected using commas (,).

you can see results in the Site Connection Results tab

                <select class="form-control" id="countryDropdown">
                    <option>Select Country</option>
                    <option>US</option>
                    <option>SG</option>
                    <option>NL</option>
                </select>

                <input type="text" class="form-control" placeholder="SiteID(s)" id="siteIDInput" />

            <button class="btn btn-primary" (click)="testButtonClick()">Test</button>

Upload file

Upload a CSV file of sites to test all at once.

                <input type="text" class="col-lg-4 form-control" id="fileTextbox" disabled/>

                Browse <input type="file" id="fileInput" style="display:none;" onchange="{ setFileName() }"/>

            <button class="btn btn-primary" (click)="searchButtonClick()">Test</button>

                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

Modal title

One fine body…

                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button type="button" class="btn btn-primary">Save changes</button>

A: Try using (change) event binding
 <input type="file" id="fileInput" style="display:none;" (change)="setFileName()"/>

A: If you need to retrieve the file name before uploading it you can do it this way :
@Component({
    selector: 'my-app',
    template: `

        <input type="file" (change)="onChange($event)"/>

Filename : {{filename}}

    `,
    providers: []
})
export class AppComponent {
  filename: string;
  constructor() { }

  onChange(event) {
    this.filename = event.srcElement.files[0].name;
  }
}

Here is a working plunker


text:
Q: PHP images not displaying. Works in HTML So I'm building a website and I'm attempting to reuse code for a scrolling photo banner.
I can mock-up everything pretty well within a strict html page.  So I decided to move everything over to PHP to help make things more efficient and with the intent of eventually using MySQL in other content on the site.  However, after I created my functions and began to plug everything in the photo banner disappeared.  Everything else including the CSS displays beautifully.  I went so far as to remove the CSS from the page to see if that was the problem.  Unfortunately the images still refuse to show up.  It was a direct copy->paste from the working HTML document so I'm not totally sure why the photos for the banner aren't appearing.  Any advice or help would be great.  Here's the code:

<?php
require( 'function.php' );

draw_titlebar();
draw_navigation();

?>

A: image path should be like this

A: change

to


text:
Q: How to resolve error 500 on Azure web app? What I have:

*

*VS2015U2

*ASP.NET 5 MVC 6 website

*Deployed to Azure Web App

*The site works locally

*When I deploy to Azure I get internal server error (500)

*I'm unable to Attach a debugger since they messed up something with the latest versions (tried manually too https://azure.microsoft.com/en-us/blog/introduction-to-remote-debugging-on-azure-web-sites/)

*I have app.UseDeveloperExceptionPage(); but I guess the site is failing during configuration so it doesn't display any other information.

So how to resolve this? I need to see the .net exception but I have no idea how to do that.

A: *

*Use the KUDU console at https://sitename.scm.azurewebsites.net

*Go to web.config file and check if the process path is correct.

A: I used the Azure Log Stream to help figure out what was going on.  As Karishma Tiwari - MSFT said, the issue ended up being my web.config file (which was built for .NET 3.5 and not 4.7)
Here's the tutorial to set up Log Streaming:  https://blogs.msdn.microsoft.com/azureossds/2016/09/28/how-to-identifyreview-errors-on-php-applications-in-azure-web-apps-using-log-stream-service/
My particular app's solution was to update my Azure App Service to use .NET 3.5, in its Application Settings, like so:

A: Try adding Application Insights to the app.  You should see errors on startup of your application.
I would also take a look at your startup code to see if you are writing to disk anywhere during configuration or app.start.  This might be the case if you are using AAD in any capacity.
You can also hit up the KUDU console by targetting https://sitename.scm.azurewebsites.net .  You will be able to navigate in the debugging console to see the RAW logs from IIS. That might shed some light into the situation.  See KUDU for more info.

A: For me it worked after I turned "Allow Azure services and resources to access this server
" to Yes

A: I solved this problem like show below.HTTP 500 error interested about that is not allowed to access the server.Go to azure portal address and choose your database.Press"Set server firewall " and Allow Azure services and resources to access this server choose "Yes" save that page and  refresh your service.Than you can see your data

A: I got this error even though I had enabled Application Logging (Filesystem), Detailed error messages and Failed request tracing in App Service logs

This page isn't working
mysite.azurewebsites.net is currently unable
to handle this request.
HTTP ERROR 500

However by navigating to Log stream and selecting Application Logs I could see a detailed error message:

A: I know this question has already been answered but here is a recent view of the Azure Portal where I found a solution to this problem


text:
Q: What are the benefits of using wp_enqueue_script? Is there any real benefit to using wp_enqueue_script on small self-managed sites? For instance, Modernizr, why enqueue it through a function rather than call it directly inside the document head?
I can see the benefit on large sites, where you may move around directories or have multiple people mucking around in the files, or in a publicly available theme with numerous unknowns, but what's the benefit on a small site like a personal blog that never - or rarely - changes and has a single user? It just seems like extra lines of code in that case.

A:                                                **YES**

 1. It only loads scripts when needed
Important for load speed.
 2. It safely handles dependencies.
Reduces errors, duplicate loading and js clashing.
3. It handles load order and placement
Tell it where to load and when.
4. Its handles $src properly
Moving the site around, perfect.
5. It has versioning
Helps with caching and ..well versioning.
The "extra lines of code" is irrelevant, especially compared to the benefits of doing it right.

A: *

*Are you using a Theme that you control?
If not, then every time the Theme updates, you'll lose your modifications to the header. Or else, you'll have to fork the Theme, or maintain/backport your changes every time the Theme updates.

*Do you only use Plugins under your control?
If not, then you'll have to check for script conflicts every time you activate or update a Plugin that uses a script.

*Are you using a core-bundled script?
If so, then you'll have to check for core script conflicts every time you update core, as well as every time you update a Plugin that enqueues a core-bundled script.

*Do you use a caching Plugin?
If so, then you lose some or all of the benefits of script concatenation/minimizing/caching, since your script is hard-coded in the document head rather than enqueued.


text:
Q: Jquery .append and links function (data) {
    var json = data;

    if (json["type"] == "story") {
        $(".title").append("
" + json["title"] + " " + json["id"] + "
");
    }
}

when i do this what i want to get is something like

The Microsoft Empire Reboots 8441095

but in some cases i get

Core Secrets: NSA Saboteurs in China and Germany 8441055

the .json is from: https://hacker-news.firebaseio.com/v0/item/8441055.json?print=pretty
{
  "by" : "patrickgokey",
  "id" : 8441055,
  "kids" : [ 8441399, 8441097, 8441985, 8441301, 8441852, 8441578, 8441287, 8441389, 8441586, 8441583, 8441584, 8441449, 8441380 ],
  "score" : 161,
  "text" : "",
  "time" : 1412995787,
  "title" : "Core Secrets: NSA Saboteurs in China and Germany",
  "type" : "story",
  "url" : "https://firstlook.org/theintercept/2014/10/10/core-secrets/"
}

Is this caused by an error in the .append function?

A: You need quotes on the href attribute:
if (json["type"] == "story") {
    $(".title").append("
" + json["title"] + " " + json["id"] + "
");
}

http://jsfiddle.net/pjammox5/1/
To see why, look at the difference in URLs:

http://www.vanityfair.com/business/2014/11/satya-nadella-bill-gates-steve-ballmer-microsoft.print
https://firstlook.org/theintercept/2014/10/10/core-secrets/

Note the end of the second, -secrets/, combines with the  to be self-closing:
 <--Closes the tag


text:
Q: Cumulatively count values between range by group in a pandas dataframe Say I have the following data. For each user_id I want to get a cumulative count every time the difference score is <= -2 until it reaches a positive value. The count should then reset to zero and stay at that value until the next <= -2 is encountered for that user, where the count then starts again from 1 until the next positive value is reached. The result should be equivalent to what I have in cum_count.
df = pd.DataFrame({'user_id': [1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3],
                       'difference_score': [0.0, 1.0, -2.5, -2.5, -0.5, -1.5, 2.25, 2.25, -1.86, 0.0, -0.33, -1.33, -2.33, 0.0, 1.0, -2.67, -0.67, -0.67, 0.67, -0.33, -0.33, 1.0],
                       'cum_count': [0, 0, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 1, 0, 0, 1, 2, 3, 0, 0, 0, 0]})

        user_id  difference_score  cum_count
0         1            0.0000          0
1         1            1.0000          0
2         1           -2.5000          1
3         1           -2.5000          2
4         1           -0.5000          3
5         1           -1.5000          4
6         1            2.2500          0
7         1            2.2500          0
8         2           -1.8571          0
9         2            0.0000          0
10        2           -0.3333          0
11        2           -1.3333          0
12        2           -2.3333          1
13        2            0.0000          0
14        3            1.0000          0
15        3           -2.6667          1
16        3           -0.6667          2
17        3           -0.6667          3
18        3            0.6667          0
19        3           -0.3333          0
20        3           -0.3333          0
21        3            1.0000          0

EDIT: Based on your solution mozway I have found a couple of instances where the proposed solution does not produce the intended results. My apologies, my example data was not extensive enough. I have now extended the above example data to highlight this.
For example, in the updated dataframe below, row 14 cum_count should be 0 as it is a new user and the difference score is > -2. However, cum_count2 produces a 1.
In addition, once a positive value is reached and the count resets to 0, the next time a value <= -2 is encountered for that user, the count should start again from 1. However, in row 19, cum_count2 continues counting from the previous count.
The updated cum_count column has the values I'm expected to be returned as compared to what the current solution is returning in cum_count2...
df = pd.DataFrame({'user_id': [1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3],
                       'difference_score': [0.0, 1.0, -2.5, -2.5, -0.5, -1.5, 2.25, 2.25, -1.86, 0.0, -0.33, -1.33, -2.33, -2.0, -1.0, -2.67, -0.67, -0.67, 0.67, -2.5, -0.33, 1.0],
                       'cum_count': [0, 0, 1, 2, 3, 4, 0, 0, 0, 0, 0, 0, 1, 2, 0, 1, 2, 3, 0, 1, 2, 0]})

    user_id  difference_score  cum_count  cum_count2
0         1              0.00          0           0
1         1              1.00          0           0
2         1             -2.50          1           1
3         1             -2.50          2           2
4         1             -0.50          3           3
5         1             -1.50          4           4
6         1              2.25          0           0
7         1              2.25          0           0
8         2             -1.86          0           0
9         2              0.00          0           0
10        2             -0.33          0           0
11        2             -1.33          0           0
12        2             -2.33          1           1
13        2             -2.00          2           2
14        3             -1.00          0           1
15        3             -2.67          1           2
16        3             -0.67          2           3
17        3             -0.67          3           4
18        3              0.67          0           0
19        3             -2.50          1           5
20        3             -0.33          2           6
21        3              1.00          0           0

A: You can use masks to define the start and stop, identify the consecutive matching values and use if to generate a group to perform a cumcount:
m1 = df['difference_score'].ge(0)
m2 = df['difference_score'].le(-2)
m3 = m2.groupby([df['user_id'], m1.cumsum()]).cummax()

group = (m3&~m3.groupby(df['user_id']).shift(fill_value=False)).cumsum()

df['cum_count'] = df.groupby(['user_id', group]).cumcount().add(1).where(m3, 0)

output:
    user_id  difference_score  cum_count     m1     m2     m3  group
0         1              0.00          0   True  False  False      0
1         1              1.00          0   True  False  False      0
2         1             -2.50          1  False   True   True      1
3         1             -2.50          2  False   True   True      1
4         1             -0.50          3  False  False   True      1
5         1             -1.50          4  False  False   True      1
6         1              2.25          0   True  False  False      1
7         1              2.25          0   True  False  False      1
8         2             -1.86          0  False  False  False      1
9         2              0.00          0   True  False  False      1
10        2             -0.33          0  False  False  False      1
11        2             -1.33          0  False  False  False      1
12        2             -2.33          1  False   True   True      2
13        2             -2.00          2  False   True   True      2
14        3             -1.00          0  False  False  False      2
15        3             -2.67          1  False   True   True      3
16        3             -0.67          2  False  False   True      3
17        3             -0.67          3  False  False   True      3
18        3              0.67          0   True  False  False      3
19        3             -2.50          1  False   True   True      4
20        3             -0.33          2  False  False   True      4
21        3              1.00          0   True  False  False      4


text:
Q: LU factorization using Gaussian elimination $A=\begin{bmatrix}
1 & 1 & 1\\
2 & 1 & 2\\
4 & 6 & 3
\end{bmatrix}$
Gaussian elimination yields:
$\begin{bmatrix}
1 & 1 & 1 & | & 1 & 0 & 0\\
0 & -1 & 0 & | &-2 & 1 & 0\\
0 & 0 & -1 & | &-8 & 2 & 1
\end{bmatrix}$
How can I rewrite $A=LU$? I get that the left side of the elimination is $U$. However, I don't understand why the right side of the elimination is helpful to know. I checked, and it is not $L$. Why was this given in the problem. I can find $L=A*U^{-1}$. I am confused why the extra information was given.

A: If the left-hand side is equal to $X\cdot A$ for some matrix $X$, then the right-hand side is equal to $X \cdot I = X$. Essentially, it tracks the exact linear transformation performed on $A$ to get $U$.
To get $L$, we only need to take the inverse of $X$. This is easy for a matrix in lower triangular form.
Sure, you could take the inverse of $U$ and then multiply by $X$ to get $L$, but that takes more steps.
Triangular matrices make many calculations easier; that's why this kind of decomposition can be useful.