Numerous Cracks in Poured Slab

Question: I am building a home in the Houston area. nearly 3000 sq. ft. 1 story house, so a pretty big slab.
I am noticing now while walking through the home during the electrical wiring stage that the slab has hairline cracks (probably 1/8") in nearly every room of the home.
Seems like they originate from the edges of the slab or at holes where the plumbing is.
I know that shrinkage is normal, but these cracks run the whole length of the slab and I've found them in all areas of the house. I've walked through a lot of homes and havn't seen this before but maybe I just wasn't looking close enough.
Do you think this is a structural problem, not structural and just sloppy, or normal concrete laying and I've just never noticed it before?
I am having a home inspector come out for phase 2 to check before the insulation and drywall is set, but I guess it's too late to do anything about the foundation. I should have had a phase 1 inspection...
Comment: You may mean mortar, and filling the crack doesn't solve the problem of seasonal movement, which will propagate through your tile (as more cracks).
Comment: Ask your contractor whether any embedded control joints were installed (zip strips). Cracks are normal, but they're typically planned for better. They probably aren't a concern except where you're installing ceramic tile. They'll need to be managed well there. P.S. 1/8" is _much_ larger than hairline and larger than I'd expect. It's probably not a structural concern, but could be a cosmetic one.
Comment: I should add the builder got back to my about my concern and said the cables in the foundation have not been stressed yet, and once they are the cracks will go away. Cracks go away?
Comment: This house will be almost entirely ceramic tile. Wont the grout fill the crack?
Comment: On the jobs that we used cable we had to release the tension plates within 36 hour on a 5 k pad, this was in a seismic zone and sand so the requirements may be different but I would think it should be under tension prior to building.
Comment: If you're going to tile it, use crack isolation membrane (ProRed, Hydraflex, etc.), and be sure you actually develop the recommenced 3(?) mil thickness during application.
Comment: In order to answer your question, we'll need more info: 1) is the slab a "post-tension" slab or slab on grade? 2) Is the slab structural, and if so, what is the reinforcing steel in the slab..and where is it located (top, middle or bottom)? What is the thickness of the slab? Is there a thickened edge at the perimeter, and if so, what is the size? It will be difficult for you to answer all these questions. So, if you take a picture of the plans and post it, we can examine your foundation system.
Answer: I personally do not like the looks of the cracks in your foundation.   I feel that the third picture already is getting into the area of "slightly more than a hairline crack".
That being said I know a lot about foundations and have had many a slab/basement poured.   My first reaction is I want more pictures.   I want to see the entire layout and as much as I can - even landscaping outside.   Even better I want to see the area prepped before pour - this is the number one picture that any home owner should take (albeit this advice is late for you but could help someone in the future).
Let's just lay out some facts:

the reason for the cracks is part concrete makeup, part soil prep (reinforcement too/rebar), part lack of control joints.   These are all on the builder 100%.   I can't stress to you the number of times I have had a basement poured and not a crack.   It is really easy for people to say "concrete cracks" or "that's normal".   If you think it is normal for a door to stick after it has been installed for a month, you probably think concrete cracks are normal too.   I have had one crew pour at least 15 slabs/foundations for me without a crack.   I will pay more to use them.
it is too late.   There is nothing you can do at this point.   It is what it is.
there is nothing in the pictures so far that suggests that this effects the footings of the house.   HOWEVER... Given the basic mistakes this crew made - shortcuts - there has to be a much greater chance that your footings are compromised.   I am not saying they are I am strictly talking percentages.
I have not done construction in Texas.   I am guessing in Houston you have a pretty high water table.   (where I like to see yard layout)  Here is the deal.   Let's say there is not a big issue with the foundation... Let's say these are harmless cracks and everything else was done right.   When it rains, and water enters under your foundation, and even if they set a path for the water to distribute away, water still goes to the place of least resistance.   Water will try to sprout up in these cracks.
Worst case scenario is soil was prepped wrong.   After a few seasons of rain and extreme heat they may lift or separate.   This causes issues with flooring in your house, causes issues with walls, and could be very costly to fix right.

What to do:

get an inspector out there.   Make sure they are willing to put their name on that foundation.
(Note - here is where I am a bit of a dick when dealing with new construction so take it with a grain of salt)... I don't trust builders that mess up.   I personally feel that if there is a mess up this builder has made this mess up many times.   So I don't trust "builder warranties".   10 year foundation warranty...  whatever.   Too many times I have seen people get hosed by a major company stringing them along on foundation issues, then learn that same company had 30 other people with same situation, they declare bankrupcy, your warranty means nothing then, then the same group opens up under a new name and is back in business in a few weeks.   So if this were me and the inspector had any doubts or if that little voice in me didn't like things - I would ask for a third party warranty through an insurance company.  I have went this way twice and it was a pain and that same insurance company paid out heavily on one of the two houses.
You can just not accept it and not pay them.   If you have an inspector come through and note issues and you cannot get third party insurance to cover it or they will only cover it with a high-risk rider that kind of makes the case for you.

The fact is the builder messed up.   Whether this is a much-to-do-about-nothing or a huge failure good chance you don't know that until you have lived in the house a few years.   So the builder is putting all that risk on you.   You either need to understand and live with that or try to find ways to divert that risk.   Nobody on this site can tell you that these cracks mean nothing and they are perfectly normal.
Answer: Is this slab really the foundation? I'm aware of 'slab on grade' shallow foundations but I've never lived in a climate where that is practiced. In my region a foundation with footings would be poured first (even when there's no basement), then the slab would be poured inside the foundation walls. In this latter technique the slab is non-structural.
You also mentioned something about cables being tightened -- is this a post-tension concrete construction?
It's probably a good idea to have a conversation with your contractor about saw-cut control joints. Concrete will move and crack and will continue to do so throughout its life. 'Control joints' are so named because they [attempt to] control and conceal these cracks. If you have the slab cut then you get the opportunity to influence where the cracks will happen. For example, you can encourage the cracks to make straight lines and to fall in places where you wanted a grout joint. If a crack is going to telegraph through your tile floor, it'll be much easier to conceal or repair if it comes up in a grout line rather than crossing a tile.
Comment: It's obviously much too late for cut control joints. They need to be done within 24 hours, and we know cracks have already formed here.
Comment: We install control joints under walls. That way they are only visible at doorways and easy to control/fix if necessary.
Comment: Here in Minnesota we use "frost-protected" shallow foundations--slabs with thickened edges. They're insulated outside and underneath with closed-cell foam sheet.
Comment: It's true that control joints under walls would have been the most ideal placement and that plenty of undesirable cracks have already formed. But even at this late stage isn't it reasonable to expect that cutting joints now could help mitigate the growth of existing or new cracks?
Comment: Yes, Greg, but few cracks are likely to form after the first 48 hours or so. It's generally not worth the effort.

Numerous Cracks in Poured Slab


Proving that $\lambda$ being an eigenvalue for $A$ implies $\lambda^{-1}$ is an eigenvalue for $A^{-1}$

Question: Let $A$ be an invertible matrix, and let $\lambda$ be an eigenvalue for $A$. We have that $Ax = \lambda x$ for some eigenvector $x$. Note that $A^{-1}Ax = A^{-1}\lambda x$, which gives $x = A^{-1}\lambda x$. Also note that multiplication with scalar is commutative, so this gives $\lambda^{-1}x = A^{-1}x$, which is the desired result.
That last sentence was a realization I made while I was writing the question; so the question has now changed to proof-verification.
Comment: Well apart from the part "...and implies $A^{-1}\lambda$ is the identity matrix.".
Answer: The fact that $x=A^{-1}\lambda x$ does not necessarily mean that $A^{-1}\lambda$ is the identity matrix; what if, for instance, $x$ is the zero-vector?
But, you do have the right idea up until there with your second comment: that $A^{-1}\lambda=\lambda A^{-1}$, so that $\lambda^{-1}x=\lambda^{-1}\lambda A^{-1}x=A^{-1}x$.
Comment: @AndrewThompson The fact that $x$ is not the zero-vector is not the point -- that's just one way that statement can go wrong. In general, $Bx=x$ for some vector $x$ just tells us that $x$ is in the $1$-eigenspace of the matrix $B$, not that $B$ is the identity matrix.
Comment: Yes, I should've written the whole task, seeing as we were told to assume that $x$ is not the zero-vector. My mistake.
Comment: @AndrewThompson The zero-vector is just easy to pick on, because it is trivially true that $B\vec{0}=\lambda\vec{0}$ for all $\lambda\in\mathbb{R}$.
Answer: This is very confuzingly written.
What do you mean when you say $A^{-1}\lambda$ is the identity matrix? $A^{-1}$ is not necesarily diagonal, and $\lambda$ is a scalar, so the matrix is not always the identity...
It is much simpler, since you have $x=A^{-1}\lambda x$ means $x=\lambda A^{-1} x$. Now just multiply this equation with $\lambda^{-1}$ and you are done. On a side note, if I was grading an assignment like this, I would like my students to explain why $\lambda^{-1}$ exists.
Answer: If $A$ is not defective, you can use the eigendecomposition $A=Q\Lambda Q^{-1}$ and therefore $A^{-1}=Q^{-1}\Lambda^{-1}Q$, where $\Lambda$ contains your eigenvaules and $\Lambda^{-1}$ their reciprocals...
Comment: I had never heard about the terminology defective, I'd +1 you for that if this answered the general case.
Comment: @GitGud
The defective matrix $\pmatrix{1& 1 \\  0 & 1}$ is invertible, but doesn't have an eigendecomposition...
Comment: Agreed. Why are you telling me this?
Comment: @GitGud I thought an example would clarify that the way via the eigendecompositions only works for non-defective matrices...


memory leak despite using weakreference

Question: In my app I am using a listview and a listadapter. When one clicks on a certain subitem in the listview there's a clickable textview that loads several bitmaps to a scrollview - and this scrollview is shown in an alertdialog.
All this happens in a class that extends BaseExpandableListAdapter and when this textlink is clicked - a static inner class is called that is responsible to load all these (9) bitmaps. This inner class extends asynctask.
Before these bitmaps are loaded to the scrollview - two static methods of this inner-class are called that scaleddown the bitamps to a size that fits the screen. Here I use Bitmapfactory.decoderesource and Bitmap.scaledownBitmap.
All this works FINE, .. BUT the program suffers from a memoryleak. This leak was rather big before because this inner class was non-static. So the leak was reduced by making this inner class static. Yes - reduced, but not eliminated.
I have also made weakreference of several objects but without success. For example - I made a weak reference of the object that refers to the inner-class. I have made a weak reference of the context that is passed to the innerclass. I have even made w weak reference of the bitmaps. No success at all.
The heapsize of my Samsung Galazy s3 is 64 MB. When the listview with all its subitem is first loaded used heap is about 17 MB. Then when 9 bitmaps are loaded it jumbs to about 42 MB. If I then click on another subitem with images used heap is the same - but after continue clicking and loading bitmaps the heap suddenly jumbs to 47 MB ... then the same scenario .... stands still for a while - then up to 52 MB .... 56 MB. So I have to click and load bitmaps pretty much to get out-of-memory. Let say 15 - 20 minutes of intensive use.
conclusion: To make the inner-class static helped me to reduce the memory leak. But despite making weakreferences of several objects (especially context) I have not been able to reduce leak further.
Any suggestions?
The code below is a bit messy ....
static class BitmapWorkerTask extends AsyncTask <Integer, Void, Bitmap[]> {

        private int[] data;
        private int[] width, height;
        private int nmbrOfImages;
        private String[] scrollText;
        private ImageView mImage;
        private View view;
        private LayoutInflater factory;
        private AlertDialog.Builder alertadd;
        private Context context;
        private WeakReference <Context> sc;
        private WeakReference <ImageView> mImageV;
        private WeakReference <Bitmap[]> bitmapV;

        public BitmapWorkerTask(int[] width, int[] height, int nmbrOfImages, String[] scrollText, Context context) {

            this.width = width;
            this.height = height;
            this.nmbrOfImages = nmbrOfImages;
            this.scrollText = scrollText;
            this.context = context;

            mImage = null;
            view = null;
            factory = null;
            alertadd = null;
            System.gc();

            sc = new WeakReference <Context> (context);

            try {
                for (int i = 0; i < scaledBitmap.length; i++) {
                    scaledBitmap[i].recycle();
                    scaledBitmap[i] = null;
                }
            } catch (NullPointerException ne) {
                System.out.println("nullpointerexception ... gick inte recycla bitmapbilder");
            }

            switch (nmbrOfImages) {
            case 0:
                data = new int[1];
                break;
            case 1:
                data = new int[3];
                break;
            case 2:
                data = new int[5];
                break;
            case 3:
                data = new int[9];
                break;
            }

        }

        @Override
        protected Bitmap[] doInBackground(Integer ... params) {

            switch (nmbrOfImages) {
            case 0:
                data[0] = params[0];
                break;
            case 1:
                data[0] = params[0];
                data[1] = params[1];
                data[2] = params[2];
                break;
            case 2:
                data[0] = params[0];
                data[1] = params[1];
                data[2] = params[2];
                data[3] = params[3];
                data[4] = params[4];
                break;
            case 3:
                data[0] = params[0];
                data[1] = params[1];
                data[2] = params[2];
                data[3] = params[3];
                data[4] = params[4];
                data[5] = params[5];
                data[6] = params[6];
                data[7] = params[7];
                data[8] = params[8];
                break;
            }

            alertadd = new AlertDialog.Builder(sc.get());
            factory = LayoutInflater.from(sc.get());
            Bitmap[] bm = decodeSampledBitmapFromResource(sc.get().getResources(), data, width, height);
            bitmapV = new WeakReference <Bitmap[]> (bm);

            return bitmapV.get();

        }

        protected void onPostExecute(Bitmap[] bitmap) {
            switch (nmbrOfImages) {
                case 0:

                    if (view == null) {
                        view = factory.inflate(R.layout.alertviews, null);
                    }
                    mImage = (ImageView) view.findViewById(R.id.extra_img);
                    mImage.setImageBitmap(bitmap[0]);
                    alertadd.setView(view);
                    alertadd.setNeutralButton("Here!", new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dlg, int sumthin) {

                        }
                    });
                    alertadd.show();

                break;
                case 1:

                    if (view == null) {
                        view = factory.inflate(R.layout.alertviews2, null);
                    }

                    mImage = (ImageView) view.findViewById(R.id.img1);
                    mImage.setImageBitmap(bitmap[0]);
                    mImage = (ImageView) view.findViewById(R.id.img2);
                    mImage.setImageBitmap(bitmap[1]);
                    mImage = (ImageView) view.findViewById(R.id.img3);
                    mImage.setImageBitmap(bitmap[2]);

                    try {
                        TextView mText2 = (TextView) view.findViewById(R.id.text_img1_scrollview);
                        mText2.setText(scrollText[0]);
                        mText2 = (TextView) view.findViewById(R.id.text_img2_scrollview);
                        mText2.setText(scrollText[1]);
                        mText2 = (TextView) view.findViewById(R.id.text_img3_scrollview);
                        mText2.setText(scrollText[2]);
                    } catch (NullPointerException ne) {
                        System.out.println("nullpointerexception ... TextView i metoden onPostExecute");
                    }
                    alertadd.setView(view);
                    alertadd.setNeutralButton("Here!", new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dlg, int sumthin) {

                        }
                    });

                    alertadd.show();

                break;
                case 2:

                    if (view == null) {
                        view = factory.inflate(R.layout.alertviews3, null);
                    }
                    mImage = (ImageView) view.findViewById(R.id.img1);
                    mImage.setImageBitmap(bitmap[0]);
                    mImage = (ImageView) view.findViewById(R.id.img2);
                    mImage.setImageBitmap(bitmap[1]);
                    mImage = (ImageView) view.findViewById(R.id.img3);
                    mImage.setImageBitmap(bitmap[2]);
                    mImage = (ImageView) view.findViewById(R.id.img4);
                    mImage.setImageBitmap(bitmap[3]);
                    mImage = (ImageView) view.findViewById(R.id.img5);
                    mImage.setImageBitmap(bitmap[4]);

                    try {
                        TextView mText3 = (TextView) view.findViewById(R.id.text_img1_scrollview);
                        mText3.setText(scrollText[0]);
                        mText3 = (TextView) view.findViewById(R.id.text_img2_scrollview);
                        mText3.setText(scrollText[1]);
                        mText3 = (TextView) view.findViewById(R.id.text_img3_scrollview);
                        mText3.setText(scrollText[2]);
                        mText3 = (TextView) view.findViewById(R.id.text_img4_scrollview);
                        mText3.setText(scrollText[3]);
                        mText3 = (TextView) view.findViewById(R.id.text_img5_scrollview);
                        mText3.setText(scrollText[4]);
                    } catch (NullPointerException ne) {
                        System.out.println("nullpointerexception ... TextView i metoden onPostExecute");
                    }
                    alertadd.setView(view);
                    alertadd.setNeutralButton("Here!", new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dlg, int sumthin) {

                        }
                    });
                    alertadd.show();

                break;
                case 3:

                    if (view == null) {
                        view = factory.inflate(R.layout.alertviews4, null);
                    }

                    AlertDialog.Builder alertadd = new AlertDialog.Builder(context);

                    mImage = (ImageView) view.findViewById(R.id.img1);
                    mImage.setImageBitmap(bitmap[0]);
                    mImage = (ImageView) view.findViewById(R.id.img2);
                    mImage.setImageBitmap(bitmap[1]);
                    mImage = (ImageView) view.findViewById(R.id.img3);
                    mImage.setImageBitmap(bitmap[2]);
                    mImage = (ImageView) view.findViewById(R.id.img4);
                    mImage.setImageBitmap(bitmap[3]);
                    mImage = (ImageView) view.findViewById(R.id.img5);
                    mImage.setImageBitmap(bitmap[4]);
                    mImage = (ImageView) view.findViewById(R.id.img6);
                    mImage.setImageBitmap(bitmap[5]);
                    mImage = (ImageView) view.findViewById(R.id.img7);
                    mImage.setImageBitmap(bitmap[6]);
                    mImage = (ImageView) view.findViewById(R.id.img8);
                    mImage.setImageBitmap(bitmap[7]);
                    mImage = (ImageView) view.findViewById(R.id.img9);
                    mImage.setImageBitmap(bitmap[8]);

                    try {
                        TextView mText4 = (TextView) view.findViewById(R.id.text_img1_scrollview);
                        mText4.setText(scrollText[0]);
                        mText4 = (TextView) view.findViewById(R.id.text_img2_scrollview);
                        mText4.setText(scrollText[1]);
                        mText4 = (TextView) view.findViewById(R.id.text_img3_scrollview);
                        mText4.setText(scrollText[2]);
                        mText4 = (TextView) view.findViewById(R.id.text_img4_scrollview);
                        mText4.setText(scrollText[3]);
                        mText4 = (TextView) view.findViewById(R.id.text_img5_scrollview);
                        mText4.setText(scrollText[4]);
                        mText4 = (TextView) view.findViewById(R.id.text_img6_scrollview);
                        mText4.setText(scrollText[5]);
                        mText4 = (TextView) view.findViewById(R.id.text_img7_scrollview);
                        mText4.setText(scrollText[6]);
                        mText4 = (TextView) view.findViewById(R.id.text_img8_scrollview);
                        mText4.setText(scrollText[7]);
                        mText4 = (TextView) view.findViewById(R.id.text_img9_scrollview);
                        mText4.setText(scrollText[8]);
                    } catch (NullPointerException ne) {
                        System.out.println("nullpointerexception ... TextView i metoden onPostExecute");
                    }

                alertadd.setView(view);

                alertadd.setNeutralButton("Here!", new DialogInterface.OnClickListener() {

                    public void onClick(DialogInterface dlg, int sumthin) {

                    }
                });
                alertadd.show();

            break;
            }
        }

         /**
           *
           * @param options
           * @param reqW
           * @param reqH
           * @return
           */
          public static int calculateInSampleSize(BitmapFactory.Options options, int reqW, int reqH) {

                int imageHeight = options.outHeight;
                int imageWidth = options.outWidth;
                int inSampleSize = 1;
                if (imageHeight > reqH || imageWidth > reqW) {
                    int heightRatio = Math.round((float) imageHeight / (float) reqH);
                    int widthRatio = Math.round((float) imageWidth / (float) reqW);
                    inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
                    System.out.println("i if-satsen!");
                    System.out.println("height-ratio: " + heightRatio + "\nwidth-ratio: " + widthRatio);
                }
                System.out.println("samplesize: " +  inSampleSize);
                inSampleSize = inSampleSize;

                return inSampleSize;
            }

            @SuppressLint("NewApi")
            /**
             *
             * @param res
             * @param resId
             * @param reqW
             * @param reqH
             * @return
             */
            public static Bitmap[] decodeSampledBitmapFromResource(Resources res, int[] resId, int[] reqW, int[] reqH) {

                scaledBitmap = new Bitmap[resId.length];

                BitmapFactory.Options options;
                for (int i = 0; i < resId.length; i++) {
                    options = new BitmapFactory.Options();
                    options.inJustDecodeBounds = true;
                    Bitmap bm =BitmapFactory.decodeResource(res, resId[i], options);

                    System.out.println("ursprunglig bild: h = " + options.outHeight + " w = " + options.outWidth);
                    options.inSampleSize = calculateInSampleSize(options, reqW[i], reqH[i]);

                    while (options.outHeight < reqH[i] || options.outWidth < reqW[i]) {

                        options.inSampleSize--;
                        System.out.println("räknar nu ner insampleseize\ninSamleSize =" + options.inSampleSize);
                    }

                    options.inJustDecodeBounds = false;

                    bm = BitmapFactory.decodeResource(res, resId[i], options);
                    System.out.println("innan omskalning: h = " + options.outHeight + " w = " + options.outWidth);
                    System.out.println("antalet bytes: " + bm.getByteCount());
                    System.out.println("native free size: " + Debug.getNativeHeapFreeSize() );

                    scaledBitmap[i] = Bitmap.createScaledBitmap(bm, reqW[i], reqH[i], true);

                    bm.recycle();
                    bm = null;

                }
                System.gc();
                WeakReference <Bitmap[] > sc = new WeakReference <Bitmap[]> (scaledBitmap);

                return sc.get();
            }
    }

}
Comment: Use MAT to determine where your leak is occurring.
Answer: You are keeping dual reference to your bitmaps
once weak and once hard copy
your problem code is :
  Bitmap[] bm = decodeSampledBitmapFromResource(sc.get().getResources(), data, width, height);
                bitmapV = new WeakReference <Bitmap[]> (bm);

you are not getting rid of the contents of bm
and you are doing it more than once
     scaledBitmap[i] = Bitmap.createScaledBitmap(bm, reqW[i], reqH[i], true);

                    bm.recycle();
                    bm = null;

                }
                System.gc();
   WeakReference <Bitmap[] > sc = new WeakReference <Bitmap[]> (scaledBitmap);

You should do this:
ArrayList<WeakReference<Bitmap>>scaledBitmaps= new ArrayList<WeakReference<Bitmap>>();

scaledBitmaps.add(new WeakReference<Bitmap>(Bitmap.createScaledBitmap...));

and do not use Bitmap[] array

memory leak despite using weakreference


What to do when Juju machine 0 has got "agent-state: not-started" state

Question: After running a Juju environment for some time, now machine 0 has got status: "agent-state: not-started" that has persisted for some time now and it is unable to deploy any new machines.
"Juju ssh 0" gives Waiting for machine to come up". I have also tried rebooting it from Amazon EC2 console without any change.
What do I do to to get it up again?
Comment: I am able to log into the machine using "ssh ubuntu@[public IP]", and /var/log/juju/machine-agent.log says:

Failure: txzookeeper.client.ConnectionTimeoutException: could not connect before timeout

Same error in /var/log/juju/provision-agent.log in addition to:

"2013-03-25 11:00:46,661: juju.agents.provision@INFO: Stopping provisioning agent"
Comment: Zooinspector also works from machine 0.
Answer: Seems like I experienced the following bug: https://bugs.launchpad.net/juju/+bug/995823
Workaround is to run sudo restart jujud-machine-0 after ssh-ing into it directly using ssh ubuntu@[public IP], where public IP is found from the machine list (juju status).


Matlab find all files with text in its name

Question: There are two patterns of naming files in my directory.
Pattern 1:
'XXXXXX FixedCost_zz123.mat'

Pattern 2
'XXXXXX FixedVolume.mat'

So, based on above some examples of real files in my folder are:
'Sap FixedCost_pkz123.mat'
'ASDFG FixedCost_z1.mat'
'TUP112RA FixedCost_h1453.mat'
'as FixedVolume.mat'
'P1234L FixedVolume.mat'
'afg FixedVolume.mat'

I want to be able to find all files of 'FixedCost' and 'FixedVolume' type based on what I need at any instance. How do I achieve this ? My input to the function would be either 'FixedCost' or 'FixedVolume'.
Answer: You can use the dir function with an argument specifying a filename pattern:
fixedCostFiles = dir('*FixedCost*.mat');
fixedVolumeFiles = dir('*FixedVolume.mat');

If you want more sophisticated selections and are not afraid of java you could also use the apache FileUtils, they come as part of MATLAB's java:
http://commons.apache.org/proper/commons-io/apidocs/org/apache/commons/io/FileUtils.html
Specifically, check the listFiles function.
Comment: How do I add directory structure to it if I want to provide the user the option to enter any drive he wants to use and hence the directory structure would be another input to the function.
Comment: In that case, prefix the filename-pattern with the directory `dir("path/to/files/*FixedCost*.mat")` - as in MatteoD's answer.
Answer: This will return all the files with a specific wildcard in the name
file_list_1 = dir(fullfile(directory_path, '*FixedVolume*.mat'))
file_list_2 = dir(fullfile(directory_path, '*FixedCost_zz123*.mat'))

Answer: matlab has regex if you need something more complex
http://www.mathworks.com/help/matlab/ref/regexp.html
also see the  "match" or "tokens" options


Can't see the sidebar in geany 1.27 on mac

Question: I can't see the sidebar in geany 1.27 on Mac OS. Because of this I have no way of seeing the symbol list or document list
Is there a configuration option or else I missed ?
Answer: Close Geany, then in .config/geany/geany.conf inside your home dir, set
treeview_position=100

and restart Geany.
When sidebar is collapsed, you can't restore it from the GUI
Answer: Per default it should be visible. Check .config/geany/geany.conf inside your home with e.g. vim for this options I could imaging of maybe causing the issue
tab_pos_sidebar=2
sidebar_pos=0
sidebar_symbol_visible=true
sidebar_openfiles_visible=true
sidebar_visible=true

(these values are actually taken from my working OS X configuration of Geany. I'm referring to config file as its much fast the double check than go there click here)
Comment: I have the same values set ...still no sidebar

Installed last 1.27 version no sidebar


Trying to change a lightbulb out of a ceiling fixture

Question: I am trying to change the light-bulbs in my kitchen ceiling light, I'm just unsure how to do it with this one without accidentally tearing it out of the ceiling.
Does anyone know how to unfasten this fixture, as well as what make it is?
Comment: What does the horizontal screw in the third picture do?  Are there more like that?  That's where I would start.
Comment: Fantastic pictures!! This is a prize winning example of how a new contributor posts a question with great supporting information and is able to get an answer in short order.
Comment: Please [take the tour](https://diy.stackexchange.com/tour) so you know how to resolve this post.
Answer: See that dimple in the third photo? I' guessing that there are three or four of them. They engage with slots in the other half of the housing.
Rotate the lower portion counter-clockwise roughly as far as the dimple is long and it should come down. You may have to align the screws on top with their slots as well. Loosen the set screw to avoid scratches.


Sporadic WCF Service activation error with message - An error occurred while accessing the IIS Metabase

Question: I was haivng a project in which earlier I was hosting only single WCF service. Everything used to work fine. Later, as part of enhancements we have added two more WCF services to the same project with different Interfaces and different SVC files. All three services share same web.config which define the three end points (corresponding to each service).
WCF services for my project are hosted as separate website with its own App Pool and port number. All three of my services share the same App pool.
With this setup when I am deploying application to test servers many times I am getting sporadic error as below and service stops working. Of the three service, one or two at a time gives this error other keeps on working.
<code>    System.ServiceModel.ServiceHostingEnvironment+HostingManager/4032828
    System.ServiceModel.ServiceActivationException: The service '...svc' cannot be activated due to an exception during compilation.  The exception message is: An error occurred while accessing the IIS Metabase.. --->

    System.Runtime.InteropServices.COMException: An error occurred while accessing the IIS Metabase.
   at System.ServiceModel.Activation.MetabaseReader..ctor
</code>
I enabled svclogs for the webservice and there I am seeing things like
<code>......
AppDomain unloading
To: construct ServiceHost 'myservice1'
From: construct ServiceHost 'myservice1'
To: Open ServiceHost 'myservice1'
From: ServiceHost 'myservice1'
ASP.NET hosted service activated
**Wrote To Eventlog**     << Exception at this point for myservice2.
</code>
I have tried This options but it doesn't help. I have also searched on net but not finding any other solution that can help.
I am having IIS6 on the test servers.
Any help would be greatly appreciated.
UPDATE:

I have observed a pattern. After Idle time, whichever service is hit first gets activated properly, other ones fails. Also, to add to Port part, we are specifically mentioning port on which this service would be running. for my application say the port number is 25000, then no other application on this server is sharing this port number, only my application. So if there are multiple Services, then they are sharing the port, but again the same setup is there for other projects having multiple SVC services and none has ever experienced this issue (as far as I know).
UPDATE 2: Below is the config file. I have typed in the config file but have tried to keep this as accurate as possible. (please ignore case-sensitive things)
<code><system.serviceModel>
    <bindings>
        <basicHttpBinding>
            <binding name="MyBinding">
                <security mode="TransportCredentialOnly">
                    <transport clientCredentialType="Basic" proxyCredentialType="Basic" realm="prod.xxx.net" />
                    <message clientCredentialType="UserName" algorithmSuite="Default"/>
                </security>
            </binding>
        </basicHttpBinding>
    </bindings>

    <behaviours>
        <serviceBehaviours>
            <behaviour name="firstServiceBehaviour">
                <serviceMetadata httpGetEnabled="true" />
                <serviceDebug includeExceptionDetailInFaults="true" />
                <serviceCredentials>
                    <clientCertificate>
                        <authentication mapClientCertificateToWindowsAccount="true" />
                    </clientCertificate>
                </serviceCredentials>
                <dataContractSerializer maxItemsInObjectGraph="2147483646" />
            </behaviour>

<behaviours>
    <serviceBehaviours>
        <behaviour name="secondServiceBehaviour">
            <serviceMetadata httpGetEnabled="true" />
            <serviceDebug includeExceptionDetailInFaults="true" />
            <serviceCredentials>
                <clientCertificate>
                    <authentication mapClientCertificateToWindowsAccount="true" />
                </clientCertificate>
            </serviceCredentials>
        </behaviour>

<behaviours>
    <serviceBehaviours>
        <behaviour name="thirdServiceBehaviour">
            <serviceMetadata httpGetEnabled="true" />
            <serviceDebug includeExceptionDetailInFaults="true" />
            <serviceCredentials>
                <clientCertificate>
                    <authentication mapClientCertificateToWindowsAccount="true" />
                </clientCertificate>
            </serviceCredentials>
            <dataContractSerializer maxItemsInObjectGraph="2147483646" />
        </behaviour>

    <services>
        <service behaviourConfiguration="firstServiceBehaviour" name="...">
            <endpoint address="" binding="basicHttpBinding" bindingConfiguration="MyBinding" name="firstServiceEndPoint" contract="IfirstServiceContract" />
        </service>

        <service behaviourConfiguration="secondServiceBehaviour" name="...">
            <endpoint address="" binding="basicHttpBinding" bindingConfiguration="MyBinding" name="secondServiceEndPoint" contract="IsecondServiceContract" />
        </service>

        <service behaviourConfiguration="thirdServiceBehaviour" name="...">
            <endpoint address="" binding="basicHttpBinding" bindingConfiguration="MyBinding"
name="thirdServiceEndPoint" contract="IthirdServiceContract" />
        </service>
    </services>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
</System.ServiceModel>
</code>
Comment: So, sometimes it works and sometimes not ? Can you see completed calls ?
Comment: @Paddy how to identify the port conflict. It is a shared server with multiple applications sharing the servers, but having their independent AppPools and Virtual directories.
Comment: @Cybermaxs-Betclic yes I can see completed calls
Comment: If it works sometimes, I am guessing there is perhaps a port conflict. The ports in question could be from any application and might suggest why this errors out randomly
Comment: It would be better if you could post the web.config data, specifically where endpoits are configured.
Comment: @ShashankChaturvedi I'll try that will type that after some time from my home machine. Dont want to copy paste from my office machine because of security concerns.
Comment: Do you have the web services setup as virtual directories? Are they all running in the same app pool?
Comment: @PaulZahra we have each project setup as a separate website and is having its own app pool. I'll udpate my question with this information
Comment: Have you tried this on any other servers/machines in an iis instance? maybe on your development machine? IIS6 is so flaky, you might want to try and re-register asp.net on the machine? Also make sure iis is set to use the appropriate .net version for your website.
Comment: I have tried it on three different environments. My Development machine I am not seeing this issue that often as re-compilation rebuild keeps on happening. We are seeing this issue in our enterprise wide test environments. We have seen this in two different enterprise wide test environments.
Comment: I've had this before when the WCF service was running from a box also running SQL Server. The SQL Server process was eating up a lot of either processor or RAM on the box (I forget which, I think it was RAM) and so the service wouldn't activate as there wasn't enough free RAM. However at other times it was fine, when the SQL Server was not busy, so it appeared random. Check out the RAM usage on the server.
Comment: @bgs264 Thanks for your comment. We are working on resource monitoring for this application. We have also done a temporary solution so that atleast Testers can test the application by creating a dummy programme that hits our WCF services every 5-10 mins and dont let the services to unload from App Domain. This is bad that we have to do such work around :(
Comment: @Guanxi are you using Repository pattern with Dependency Injection (Ninject)?
Comment: @mutek We are not using Repository pattern and Dependency Injection. What difference this would have made?
Comment: @Guanxi I've seen issues very similar to this and it was due to the way we published. I'll spare the details since you aren't using it. Originally we would overwrite the production code when publishing changes. To clear it up for us, we had to actually delete the production bin folder when publishing.  Doesn't sound like it will help you though, sorry.
Comment: do they all really have a name of `...`? I've seen an error before based on the name in the .svc file not matching that in the web.config
Comment: @mutek .. our deployment process really do what you are saying, everytime we deploy new change ... no matter even change is in once line, completd application folder is deleted and all the files are copied again. ... so we are already doing what you have suggested.
Comment: @SimonHalsey, yes they have names. Service names, I dont want to give the service names so just written ....svc. Once example can be common.svc. The issue is coming with all with the pattern as mentioned in updates.
Answer: I won't say this as complete answer, but this somewhat helped solve our problem. I still want to know reason / solution to actual cause of the problem. I am mentioning this work around as this might help somebody Temporarily resolve their issues as well who might face similar problem.
As I mentioned the issue was coming only when application was idle for some time. In that case IIS was shutting down (unloading) the application's AppDomain (This is from SVC Logs).
So we created a simple console app that was hitting all the services of our application every 5-10 minutes and was not letting AppDomain to shut down. There is an alternative way for achiving this - Setting IIS configuration to not to unload AppDomain (this was less feisible for us provided the shared infrastructure). This helped us to complete testing.
Then as we moved to load-balanced environments (Testing environments close to production), we suddenly stopped getting the issue and with some analysis we found that the Load-Balancer itself was pinging these services so as to make sure that they are up, and because of this App Domain of these services was never unloading.
So, for now we can say that we are not getting this issue in a load balanced environment, but the question still remains why was it even happening (for non load Balanced environments).


Can I bury RG6 in the same conduit as electric?

Question: I am burying electric wire in a PVC conduit from my house to my shed, I want to run RG6 cable for cable TV also, can I run the RG6 in the same conduit as the electric wire? without any trouble or interference?
Answer: No, you cannot. Unless you're not covered by National Electrical Code (or similar), you don't care about following codes, or you're also installing a permanent barrier or listed divider.

National Electrical Code
Chapter 8 Communications Systems.
Article 820 Community Antenna Television and Radio Distribution Systems.
820.133 Installation of Coaxial Cables and Equipment.
  Beyond the point of grounding, as defined in 820.93, the
  coaxial cable installation shall comply with 820.133(A)
  and (B).
(A) Separation from Other Conductors.
(1) In Raceways, Cable Trays, and Boxes.
(b) Electric Light, Power, Class 1, Non–Power-Limited
  Fire Alarm, and Medium-Power Network-Powered Broadband
  Communications Circuits. Coaxial cable shall not be
  placed in any raceway, compartment, outlet box, junction
  box, or other enclosures with conductors of electric light,
  power, Class 1, non–power-limited fire alarm, or medium-power
  network-powered broadband communications
  circuits.
Exception No. 1: Where all of the conductors of electric
  light, power, Class 1, non–power-limited fire alarm, and
  medium-power network-powered broadband communications
  circuits are separated from all of the coaxial cables by
  a permanent barrier or listed divider.

You can Either put a second conduit in the trench for communications circuits, or put direct-burial coaxial cable in the trench.
Comment: Conduit, conduit, conduit. Direct burial is a dirty word when you have the expensive part (trench) done. Conduit means never having to dig that trench again - direct burial just about guarantees that you will have to dig it over.
Comment: @Ecnerwal I agree that conduit is useful if you ever have to run cable again, but direct burial cable is easier and cheaper to install and should last quite a long time.


Why is my json response not conforming to my struct?

Question: I have made a simple api to test on apiary, I have created a struct for the response. But when the call is made and I try to make it conform to my struct for some reason I do not get the body and only get the header. I would like to get the little league teams and place them into this struct and then print them.
API link:
https://littleleaguers.docs.apiary.io/#reference/0/little-league-teams/list-all-little-league-teams
Response Body:
 {
    "name": "Little League Teams"
    "teams": [
        {
            "id": 1,
            "team": "Yankees",
            "players": [
                {
                    "id": 1,
                    "position": 1,
                    "player": null
                },
                {
                    "id": 2,
                    "position": 2,
                    "player": {
                        "name": "John",
                        "last": "Johnson",
                        "jersey": 5
                        "signed_up": "2018-07-16T08:40:51.620Z"
                    }
                },
                {
                    "id": 3,
                    "position": 3,
                    "player": null
                },
                {
                    "id": 4,
                    "position": 4,
                    "player": null
                },
                {
                    "id": 5,
                    "position": 5,
                    "player": {
                        "name": "Blake",
                        "last": "Smith",
                        "jersey": 28
                        "signed_up": "2018-07-14T18:23:23.000Z"
                    }
                },
                {
                    "id": 6,
                    "position": 6,
                    "player": null
                },
                {
                    "id": 7,
                    "position": 7,
                    "player": null
                },
                {
                    "id": 8,
                    "position": 8,
                    "player": null
                },
                {
                    "id": 9,
                    "position": 9,
                    "player": null
                },
                {
                    "id": 10,
                    "position": 10,
                    "player": null
                },
                {
                    "id": 11,
                    "position": 11,
                    "player": null
                },
                {
                    "id": 12,
                    "position": 12,
                    "player": null
                }
            ]
        },
        {
            "id": 2,
            "team": "Red Sox",
            "players": [
                {
                    "id": 13,
                    "position": 1,
                    "player": null
                },
                {
                    "id": 14,
                    "position": 2,
                    "player": null
                },
                {
                    "id": 15,
                    "position": 3,
                    "player": null
                },
                {
                    "id": 16,
                    "position": 4,
                    "player": null
                },
                {
                    "id": 17,
                    "position": 5,
                    "player": null
                },
                {
                    "id": 18,
                    "position": 6,
                    "player": null
                },
                {
                    "id": 19,
                    "position": 7,
                    "player": null
                }
            ]
        }
    ]
}

League.swift:
struct League: Decodable {
var name: String
var  teams: [Teams]

}
Team.swift:
    struct Team: Decodable {
var id: Int
var team: String
var players: [Players]

}

Players.swift:
 struct Players: Decodable {

var id: Int
var position: Int
var player: player?

}

    struct player: Decodable {

var name: String
var last: String
var jersey: Int
var signed_up: String

}

I then have a class to retrieve this data:
GetData.swift:
    class GetData{
    func getLeague(){
        let url = URL(string: "https://private-4df2e8-littleleaguers.apiary-mock.com/league")!
        let request = URLRequest(url: url)

    let task = URLSession.shared.dataTask(with: request) { data, response, error in
      if let response = response {
        print("RESPONSE \(response)")

       /* if let data = data, let body = String(data: data, encoding: .utf8) {
          print("BODY \(body)")
          // this line prints the body
        }*/
        if let data = data, let dataObtained = try? JSONDecoder().decode(League.self, from: data){

            print("DATA \(dataObtained).....")// this line does not print
        }
      } else {
        print(error ?? "Unknown error")
      }
    }

    task.resume()
    }

 }

I then call this in ViewController.swift by:
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view.
    let getData = GetData()
    getData.getLeague()
}

The only thing that prints in the console is:
 RESPONSE <NSHTTPURLResponse: 0x6000008e5e80> { URL: https://private-4df2e8-littleleaguers.apiary-mock.com/league } { Status Code: 200, Headers {
    "Access-Control-Allow-Origin" =     (
        "*"
    );
    "Content-Encoding" =     (
        gzip
    );
    "Content-Length" =     (
        427
    );
    "Content-Type" =     (
        "application/json"
    );
    Date =     (
        "Fri, 06 Mar 2020 13:35:40 GMT"
    );
    Vary =     (
        "Accept-Encoding"
    );
    "access-control-allow-methods" =     (
        "OPTIONS,GET,HEAD,POST,PUT,DELETE,TRACE,CONNECT"
    );
    "access-control-max-age" =     (
        10
    );
    "x-apiary-ratelimit-limit" =     (
        120
    );
    "x-apiary-ratelimit-remaining" =     (
        119
    );
    "x-apiary-transaction-id" =     (
        5e6251ac6b105b008135d67a
    );
} }

Comment: Don't `try?`, remove the question mark and **`catch`** the `Decoding` error.
Comment: Your JSON is invalid, it's missing commas after some of the values
Answer: Fixing a bit the JSON that comes back, which is wrong, everything in your struct models is fine check this out on online swift playground:
import Foundation

let json = """
 {
    "name": "Little League Teams",
    "teams": [
        {
            "id": 1,
            "team": "Yankees",
            "players": [
                {
                    "id": 1,
                    "position": 1,
                    "player": null
                },
                {
                    "id": 2,
                    "position": 2,
                    "player": {
                        "name": "John",
                        "last": "Johnson",
                        "jersey": 5,
                        "signed_up": "2018-07-16T08:40:51.620Z"
                    }
                },
                {
                    "id": 3,
                    "position": 3,
                    "player": null
                },
                {
                    "id": 4,
                    "position": 4,
                    "player": null
                },
                {
                    "id": 5,
                    "position": 5,
                    "player": {
                        "name": "Blake",
                        "last": "Smith",
                        "jersey": 28,
                        "signed_up": "2018-07-14T18:23:23.000Z"
                    }
                },
                {
                    "id": 6,
                    "position": 6,
                    "player": null
                },
                {
                    "id": 7,
                    "position": 7,
                    "player": null
                },
                {
                    "id": 8,
                    "position": 8,
                    "player": null
                },
                {
                    "id": 9,
                    "position": 9,
                    "player": null
                },
                {
                    "id": 10,
                    "position": 10,
                    "player": null
                },
                {
                    "id": 11,
                    "position": 11,
                    "player": null
                },
                {
                    "id": 12,
                    "position": 12,
                    "player": null
                }
            ]
        },
        {
            "id": 2,
            "team": "Red Sox",
            "players": [
                {
                    "id": 13,
                    "position": 1,
                    "player": null
                },
                {
                    "id": 14,
                    "position": 2,
                    "player": null
                },
                {
                    "id": 15,
                    "position": 3,
                    "player": null
                },
                {
                    "id": 16,
                    "position": 4,
                    "player": null
                },
                {
                    "id": 17,
                    "position": 5,
                    "player": null
                },
                {
                    "id": 18,
                    "position": 6,
                    "player": null
                },
                {
                    "id": 19,
                    "position": 7,
                    "player": null
                }
            ]
        }
    ]
}
""".data(using: .utf8)!

struct player: Decodable {
    var name: String
    var last: String
    var jersey: Int
    var signed_up: String
}

struct Players: Decodable {
    var id: Int
    var position: Int
    var player: player?
}

struct Team: Decodable {
    var id: Int
    var team: String
    var players: [Players]
}

struct League: Decodable {
    var name: String
    var teams: [Team]
}

if let results = try? JSONDecoder().decode(League.self, from: json) {
    print(results)
}

Output:

League(name: "Little League Teams", teams: [SwiftPlayground.Team(id:
  1, team: "Yankees", players: [SwiftPlayground.Players(id: 1, position:
  1, player: nil), SwiftPlayground.Players(id: 2, position: 2, player:
  Optional(SwiftPlayground.player(name: "John", last: "Johnson", jersey:
  5, signed_up: "2018-07-16T08:40:51.620Z"))),
  SwiftPlayground.Players(id: 3, position: 3, player: nil),
  SwiftPlayground.Players(id: 4, position: 4, player: nil),
  SwiftPlayground.Players(id: 5, position: 5, player:
  Optional(SwiftPlayground.player(name: "Blake", last: "Smith", jersey:
  28, signed_up: "2018-07-14T18:23:23.000Z"))),
  SwiftPlayground.Players(id: 6, position: 6, player: nil),
  SwiftPlayground.Players(id: 7, position: 7, player: nil),
  SwiftPlayground.Players(id: 8, position: 8, player: nil),
  SwiftPlayground.Players(id: 9, position: 9, player: nil),
  SwiftPlayground.Players(id: 10, position: 10, player: nil),
  SwiftPlayground.Players(id: 11, position: 11, player: nil),
  SwiftPlayground.Players(id: 12, position: 12, player: nil)]),
  SwiftPlayground.Team(id: 2, team: "Red Sox", players:
  [SwiftPlayground.Players(id: 13, position: 1, player: nil),
  SwiftPlayground.Players(id: 14, position: 2, player: nil),
  SwiftPlayground.Players(id: 15, position: 3, player: nil),
  SwiftPlayground.Players(id: 16, position: 4, player: nil),
  SwiftPlayground.Players(id: 17, position: 5, player: nil),
  SwiftPlayground.Players(id: 18, position: 6, player: nil),
  SwiftPlayground.Players(id: 19, position: 7, player: nil)])])


About "PIL" error, NameError: name 'PIL' is not defined

Question: I am a new python user and new one in "Stack Overflow", when I try to compile a tensorflow code I met some question, and I can't found answer from the website, so I want get some helps from here, thank everyone in advance!
And this is my compiling result:
D:\Python\Anaconda2\envs\tensorflow\python.exe D:/Python/pycharm_project/test/mnist_chuji
Traceback (most recent call last):
    File "D:/Python/pycharm_project/test/mnist_chuji", line 52, in <module>
      DisplayArray(u_init, rng=[-0.1, 0.1])
    File "D:/Python/pycharm_project/test/mnist_chuji", line 15, in DisplayArray
      PIL.Image.fromarray(a).save(f, fmt)
NameError: name 'PIL' is not defined

Process finished with exit code 1

Here is my code, and I marked the line number that my errors happened to make you finding it easily:
#导入模拟仿真需要的库
import tensorflow as tf
import numpy as np

#导入可视化需要的库
from PIL import Image
from io import StringIO #python3 使用了io代替了sStringIO
from IPython.display import clear_output, Image, display

def DisplayArray(a, fmt='jpeg', rng=[0,1]):
  """Display an array as a picture."""
  a = (a - rng[0])/float(rng[1] - rng[0])*255
  a = np.uint8(np.clip(a, 0, 255))
  f = StringIO()
  PIL.Image.fromarray(a).save(f, fmt) #line 15
  display(Image(data=f.getvalue()))

sess = tf.InteractiveSession()

def make_kernel(a):
  """Transform a 2D array into a convolution kernel"""
  a = np.asarray(a)
  a = a.reshape(list(a.shape) + [1,1])
  return tf.constant(a, dtype=1)

def simple_conv(x, k):
  """A simplified 2D convolution operation"""
  x = tf.expand_dims(tf.expand_dims(x, 0), -1)
  y = tf.nn.depthwise_conv2d(x, k, [1, 1, 1, 1], padding='SAME')
  return y[0, :, :, 0]

def laplace(x):
  """Compute the 2D laplacian of an array"""
  laplace_k = make_kernel([[0.5, 1.0, 0.5],
                           [1.0, -6., 1.0],
                           [0.5, 1.0, 0.5]])
  return simple_conv(x, laplace_k)

N = 500

# Initial Conditions -- some rain drops hit a pond

# Set everything to zero
u_init = np.zeros([N, N], dtype="float32")
ut_init = np.zeros([N, N], dtype="float32")

# Some rain drops hit a pond at random points
for n in range(40):
  a,b = np.random.randint(0, N, 2)
  u_init[a,b] = np.random.uniform()

DisplayArray(u_init, rng=[-0.1, 0.1]) #line 52

# Parameters:
# eps -- time resolution
# damping -- wave damping
eps = tf.placeholder(tf.float32, shape=())
damping = tf.placeholder(tf.float32, shape=())

# Create variables for simulation state
U  = tf.Variable(u_init)
Ut = tf.Variable(ut_init)

# Discretized PDE update rules
U_ = U + eps * Ut
Ut_ = Ut + eps * (laplace(U) - damping * Ut)

# Operation to update the state
step = tf.group(
  U.assign(U_),
  Ut.assign(Ut_))

# Initialize state to initial conditions
tf.initialize_all_variables().run()

# Run 1000 steps of PDE
for i in range(1000):
  # Step simulation
  step.run({eps: 0.03, damping: 0.04})
  # Visualize every 50 steps
  if i % 50 == 0:
    clear_output()
    DisplayArray(U.eval(), rng=[-0.1, 0.1])

And I have install the pillow in my tensorflow environment(python 3.5.2).
Thank you everyone very much!
Comment: please learn how to create a [mcve]
Answer: Use Image.fromarray, since Image was imported from PIL but PIL itself was never imported.
Comment: Thank you very much firstly! I have tried your solution  but It returns me a new error:     AttributeError: type object 'Image' has no attribute 'fromarray'. What's that mean...
Comment: @EricKani Well, I don't know, since both my `python2` and `python3` have `PIL.Image.fromarray`. Look into the documentation, upgrade your PIL version, or ask a new question.


How to insert move comments in the replayer

Question: I am unable to figure out how to put move comments into the PGN file here. I have tried putting them within <code>{  }</code> after the move, but they get ignored. I also looked at the games posted by others, but none seem to have comments.
Does the replayer here does not support comments? The discussion here How do I add a replayer to my post? seems to suggest that it does.
Comment: I've now highlighted the part of the post that you link to which points out that comments aren't functional yet.
Answer: The ability to insert comments is a feature of the PGN viewer that Andrew created; however, comments are not currently enabled on chess.SE's implementation of the PGN viewer. At some point (I don't know when exactly) there should be a rebuild of the site which will incorporate the features such as comments and arrows/highlighting into the PGN viewer.
Comment: Thanks for clarifying that. I was worried I had missed something.


How can I change size of y-axis text labels on a likert() object in R?

Question: I'm working with the likert() library to generate nice looking diverging stacked bar charts in R. Most of the formatting has come together, but I can't seem to find a way to shrink the text for the y-axis labels (e.g. "You and your family in the UK", "People in your local area..." etc.) which are too large for the plot. Any ideas here? I'm starting to wonder if I need to revert to ggplot, which will require more code, but have more customisability...
# Ingest data to make reproducible example:

climate_experience_data <- structure(list(Q25_self_and_family = c(4, 2, 3, 5, 3, 3, 4, 2,
4, 2, 4, 4, 3, 3, 2, 5, 3, 4, 1, 3, 3, 2, 4, 2, 2, 2, 4, 3, 3,
3, 2, 5, 5, 4, 2, 2, 2, 3, 1, 3, 2, 1, 2, 4, 2), Q25_local_area = c(3,
3, 3, 5, 3, 2, 4, 2, 4, 2, 4, 3, 2, 3, 2, 5, 4, 5, 1, 4, 3, 3,
4, 2, 3, 2, 3, 3, 2, 3, 2, 5, 5, 2, 2, 2, 2, 3, 1, 1, 2, 1, 2,
4, 3), Q25_uk = c(4, 3, 3, 5, 2, 3, 5, 2, 4, 2, 4, 3, 3, 3, 3,
5, 4, 5, 2, 3, 3, 2, 4, 2, 4, 3, 4, 3, 2, 4, 4, 5, 5, 4, 3, 3,
2, 4, 2, 5, 2, 2, 2, 3, 3), Q25_outside_uk = c(4, 4, 3, 5, 4,
4, 5, 2, 4, 3, 3, 3, 3, 4, 3, 5, 4, 5, 4, 3, 3, 2, 4, 2, 5, 3,
3, 2, 2, 3, 4, 4, 5, 4, 4, 3, 2, 4, 4, 5, 2, 3, 2, 2, 2)), row.names = c(NA,
-45L), class = c("tbl_df", "tbl", "data.frame"))

# load libraries:

require(tidyverse)
require(likert)

# Q25 - generate diverging stacked bar chart using likert()
q25_data <- select(climate_experience_data, Q25_self_and_family:Q25_outside_uk)
names(q25_data) <- c("You and your family in the UK", "People in your local area or city", "The UK as a whole", "Your family and/or friends living outside the UK")
# Set up levels text for question responses
q25_levels <- paste(c("not at all", "somewhat", "moderately", "very", "extremely"),
                    "serious")
q25_likert_table <- q25_data %>%
  mutate(across(everything(),
                factor, ordered = TRUE, levels = 1:5, labels=q25_levels)) %>%
  as.data.frame %>%

# make plot:

plot(q25_likert_table, wrap=20, text.size=3, ordered=FALSE, low.color='#B18839', high.color='#590048') +
  ggtitle(title) +
  labs(title = "How serious a threat do you think \nclimate change poses to the following?", y="") +
  guides(fill = guide_legend(title = NULL)) +
  theme_ipsum_rc() +
  theme()

Here's a sample of output:
Answer: As your plot is still a ggplot object you could adjust the size of the y axis labels via theme(axis.text.y = ...):
library(tidyverse)
library(likert)
library(hrbrthemes)

q25_likert_table <- q25_data %>%
  mutate(across(everything(),
    factor,
    ordered = TRUE, levels = 1:5, labels = q25_levels
  )) %>%
  as.data.frame() %>%
  likert()

plot(q25_likert_table, wrap = 20, text.size = 3, ordered = FALSE, low.color = "#B18839", high.color = "#590048") +
  ggtitle(title) +
  labs(title = "How serious a threat do you think \nclimate change poses to the following?", y = "") +
  guides(fill = guide_legend(title = NULL)) +
  theme_ipsum_rc() +
  theme(axis.text.y = element_text(size = 4))


Isolation valves on tankless heater: is this setup ok?

Question: I had a tankless water heater installed with isolation valves.  The setup that I got is a little different from what I normally see, and I'd like to make sure that this is a good solution and I'd like to ask a few questions about descaling with this setup.  There are two shutoff valves, one each on hot and cold lines.  However, there are no drain valves on these valves, all they do is shutoff water with no way to attach lines for descaling.  Instead, flexible hose is used to attach from these lines to the tankless heater.  Here is an image of the attachments from the lines to the hose:
Then, the hose attaches to the heater as shown:
The hose is marked as stainless steel water heater hose, 3/4" FIP.
My questions are:

Is this setup an ok installation?
To descale with this setup, I assume that I just close the valves, unscrew the hose, and re-attach it to a pump to run descaling solution through.  Is this so?  Is it better to unscrew the hose at its attachment to the lines or at its attachment to the heater?  When I re-attach the hose, should I put anything on the threads such as pipe dope?  Will there be any problem long term with repeatedly unscrewing and rescrewing the hose every time I descale it?
Answer: This kind of connection does not need pipe dope because a plastic washer or seal is compressed between two hard metal rims. The threads are not exposed to water pressure and are not part of the sealing so pipe dope would not be useful.
Twelve years ago I bought and supplied to the plumber who installed my tankless heater a set (hot and cold) of Webstone 50443 service and isolation valves. I had bought two of these Bosch heaters as discontinued models on sale at Home Depot, intending to put one in my house and the other in a rental house I owned, but I chickened out on doing it myself and hired a plumber. He acted like he had never seen valves of this type. These are specifically for tankless heaters and allow cutting off the cold water supply and the hot water piping of the house from the water heater and then opening up the heater for draining and for descaling with vinegar.
I had it descaled once in 12 years of service. The plumber who did the descaling was not familiar with these valves and wrenched one in the wrong direction over the stop. Luckily this didn't break it and I was able to remove the handle and restore normal operation. He used a pump in a bucket to circulate a couple of gallons of white vinegar but  decided to turn the heater on with the vinegar circulating. I don't think that is a good idea.
I wonder whether descaling is necessary for most installations. If yours is new just use it for 10 years and then think about descaling.
What model is your tankless water heater? Mine is a Bosch Aquastar 125 (?), a discontinued model with a standing pilot light that does not require electric power.
Noritz seems to think that there is no one universal descaling time interval. http://www.noritz.com/blog/biggest-myth-tankless-water-heater/
Comment: The Webstone valve set I got had a pressure relief valve (or temperature/pressure relief valve) included. This attaches to a port on the hot valve. Does your installation have a relief valve and where is it connected?
Comment: Thanks for the info.  Can I re-use this kind of connection multiple times?  That is, can I detach and re-attach it each time I descale without problem?  There is no relief valve on the installation and no drain valve.  The valves are just levers to shut off the flow of water through the line, with no other connection on them.
Comment: I think you could disconnect and reconnect the supply and output lines multiple times for descaling. However, it will not be convenient. As to the absence of a pressure relief valve in your installation, this is a major deficiency and I must think is a code violation. Tank water heaters have a temperature/pressure relief valve, in which a temp sensor is in contact with the water in the tank. Tankless water heaters are, I think, pressure relief only because a heat sensor would not be effective.
Comment: What is the make and model of your water heater?
Comment: You must have a pressure relief valve on the hot output side of the tankless water heater and it must be one which is specified for tankless heaters. You will not be able to use the TPV for a tank heater.  You might be able to rig up a way to connect the pressure relief valve using standard copper or brass fittings, but the normal way would be to use the specific valve for that purpose. Where in the US or elsewhere is the structure with this tankless heater?
Comment: It **may** be that your tankless heater does not require a pressure relief valve unless the local code requires it. Check on the installation requirements for your heater and check with your local plumbing inspection authority.
Comment: Thanks.  It is a Navien NPE 240A in Washington state.  The Navien installation manual for some other models indicates that a pressure relief valve is required.  For this model, it mentions where to install the valve, but does not seem to say that it is required; I do not know the Washington code.  I will check with Navien.  Thanks much for your answer.  It seems that there may indeed be problems with the installation that I will need to raise with the installer.
Comment: FYI the pressure relief valves used in the output line or output valve of tankless water heaters are rated for pressure (usually 150 psi) but also rated for heat output rate of the heater. The one for my rather small tankless heater is rated at 200,000 BTU/HR sufficient for my heater output of about 120,000 BTU/HR. If your heater is 199,000 BTU/HR then this one would presumably work or maybe you'd need one with a higher heat rating. My relief valve is labeled  WILKINS ZURN P1000A-150PSI  3/4" NPT CSA 200,000 BTU/HR.


Junit - program verification vs whitebox fuzzing?

Question: I understand that program verification is a branch of computer engineering - but that it's practical application to real world code bases is limited by combinatorial explosion.
I also understand that as part of designing your software change,  for a modification to an existing Java framework, it's helpful to think about whitebox, boundary and blackbox tests for your algorithm, in advance. (Some people call this hammock driven development - thinking before you code.)
Assuming you take this thinking and embed it in junit style tests, I'm assuming that the Computer Science name for the contents is strictly 'whitebox testing/fuzzing' and not sufficient to comprise 'program verification'.
So my question is - junit tests - whitebox fuzzing or program verification?
Answer: Program verification is done proving mathematical properties on a mathematical model which is related to your application (it can be derived from the formal semantic of the programming language or by hand, like writing behavioral types that models your web service).
Take a look at pi-calculus to understand what I mean.
Of course, junit has nothing to do with formal program verification.


Different durations for different properties using WebKit transitions/animation

Question: I'm using WebKit transition to animate certain CSS changes.
For example, say I've got a red box that I want to change to green when someone hovers. I use this:
<code>-webkit-transition-duration: 200ms;
-webkit-transition-property: background;
-webkit-transition-timing-function: ease;
</code>
That works great. But now, say I want it to also slide downwards a bit. I use this:
<code>-webkit-transition-property: background, margin;
</code>
That also works okay, but I want the box to slide down quickly (say 50ms). I can't change <code>-duration</code> because that would make the color animate fast.
How can I assign different durations to different properties in CSS animations?
I'm fine with using keyframe animations if necessary, but I haven't seen a way that they can help me.
jsfiddle for reference
Answer: Duratons can be comma-separated, corresponding to the transitioned properties, ie:
<code>-webkit-transition-duration: 50ms, 200ms;
-webkit-transition-property: margin, background;
</code>
http://jsfiddle.net/bQ8d7/1/


How to define global variables in terraform?

Question: I have a terraform project I am working on. In it, I want a file to contain many variables. I want these variables to be accessible from any module of the project. I have looked in the docs and on a udemy course but still don't see how to do this. How does one do this in terraform? Thanks!
Answer: I don't think this is possible. There are several discussions about this at Github, but this is not something the Hashicorp team wants.

In general we're against the particular solution of Global Variables, since it makes the input -> resources -> output flow of Modules less explicit, and explicitness is a core design goal.

I know, we have to repeat a lot of variables between different modules
Comment: I just have seen these github discussions. Thanks.
Answer: For pathing constants between lots of modules we can use the following simple way.
/modules/global_constants/outputs.tf:
Describe module with global constants as outputs:
output "parameter_1" {
  value     = "value_1"
  sensitive = true
}

output "parameter_2" {
  value     = "value_2"
  sensitive = true
}

/example_1.tf
After we can use in any *.tf
module "global_settings" {
   source = "./modules/global_constants"
}

data "azurerm_key_vault" "keyvault" {
   name                = module.global_settings.parameter_1
   resource_group_name = module.global_settings.parameter_2
}

/modules/module2/main.tf
Or in other any modules:
module "global_settings" {
   source = "../global_constants"
}

data "azurerm_key_vault" "keyvault" {
   name                = module.global_settings.parameter_1
   resource_group_name = module.global_settings.parameter_2
}

Answer: I try to do this

Define a the set of common variables e.g. common_tags at the bottom/top of the variables.tf file for all modules. Usually, your tech ops admin/cloud admin will have a template project created for this.

For each module, I add the following as the last item
global_var   = var.global_var_val

An example is common tags. In any root/child module I combine them using merge() function. I hope that makes sense.
Answer: You can use -var-file to pass the overrides. Example:
terraform -chdir=staging/000base apply -var-file ../../global.tfvars

Other way can be dedicated shared module.
For example you have module with:
output "my_var" {
  value = "apollo440"
}

And in other modules you can use it like:
module "gvars" {
  # source = "email@example.com:user/terraform-global-vars.git?ref=v0.0.1-alpha"
  source="../../../modules/global_vars"
}

provider "something" {
  name="${module.gvars.my_var}"
}

Third way could be to use https://registry.terraform.io/providers/hashicorp/http/latest/docs/data-sources/http to query some http endpoint.
Ouh... and forth way could be to utilize Vault Provider https://registry.terraform.io/providers/hashicorp/vault/latest/docs


Apache2 configuration. Different PHP versions

Question: I have a big problem with MyBB. I uploaded the files fine, gave rights 777.
000-default.conf entry from apache2:
<VirtualHost *:80>
    ServerName 192.168.1.19
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/web/

    <Directory /var/www/web>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>
    <FilesMatch \.php$>
        SetHandler "proxy:unix:/run/php/php8.2-fpm.sock|fcgi://localhost/"
    </FilesMatch>

    ErrorLog ${APACHE_LOG_DIR}/web_error.log
    CustomLog ${APACHE_LOG_DIR}/web_access.log combined
</VirtualHost>

<VirtualHost *:80>
    ServerName 192.168.1.19
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/mybb/

    <Directory /var/www/mybb>
        Options Indexes FollowSymLinks
        AllowOverride All
        Require all granted
    </Directory>

    <FilesMatch \.php$>
        SetHandler "proxy:unix:/run/php/php8.1-fpm.sock|fcgi://localhost/"
    </FilesMatch>

    ErrorLog ${APACHE_LOG_DIR}/mybb_error.log
    CustomLog ${APACHE_LOG_DIR}/mybb_access.log combined

    Alias /mybb /var/www/mybb

</VirtualHost>
<VirtualHost *:80>
    ServerName 192.168.1.19
    ServerAdmin webmaster@localhost
    DocumentRoot /usr/share/phpmyadmin/

    <Directory /usr/share/phpmyadmin/>
        Options FollowSymLinks
        DirectoryIndex index.php
        AllowOverride All
    </Directory>

    <FilesMatch \.php$>
        SetHandler "proxy:unix:/run/php/php8.2-fpm.sock|fcgi://localhost/"
    </FilesMatch>

    ErrorLog ${APACHE_LOG_DIR}/phpmyadmin_error.log
    CustomLog ${APACHE_LOG_DIR}/phpmyadmin_access.log combined

    Alias /phpmyadmin /usr/share/phpmyadmin
</VirtualHost>

After typing 192.168.1.19/mybb does not work, same if I type 192.168.1.19/mybb/install or 192.168.1.19/install
MyBB must be using version 8.1. How to fix this? I have no strength left. ChatGPT can't help, I don't know anything about it. I am using Ubuntu 22.04.2 LTS. Apache version is 2.4.56, mariadb version is 10.11.2, php version is 8.1.17 (All packages from the stable release)
/var/ww/web and phpmyadmin must use php 8.2. The site and phpmyadmin work, but mybb does not.
Comment: I would *strongly* suggest replacing `777` with `755` unless you want your websites to be "hacked" by a drive-by script kiddie. Only the web server should be permitted to write files on the server
Comment: I know, but it was for testing. I changed it to 755, thanks ! :)
Comment: What is inside `/var/www/mybb/`? Could you paste the output of `ls /var/www/mybb/`?
Comment: You have three `VirtualHost` configurations with the same `ServerName`. Only the first configuration that matches will be used. The other VirtualHosts will be ignored.
Answer: You've configured several vhosts with the same ServerName 192.168.1.19 on the same port (80). Since the last vhos takes precedence over the others phpmyadmin will work. You can make it work by using different ports for each site. For example:
<VirtualHost *:8082>
...
<VirtualHost *:8081>
...
<VirtualHost *:8080>
...

Comment: Changed to: https://pastebin.com/5V1eMWfV And mybb still doesn't work. There is an error somewhere in this file, I just don't know where :( After editing the file, I ran the command sudo systemctl restart apache2
Comment: Please show the error you get. Don't forget to add the Listen instruction for each port


Startopia multiplayer crashes to desktop

Question: Starting a two player game (TCP/IP or IPX, doesn't matter) works great, but after ~10 minutes of playing the client (and always the client even when switching roles) crashes to desktop without any logfile left. A second, possibly related problem is that on the server one cannot get back to the game from the menu after hitting escape, so loading a previous game doesn't work either :-(
Any ideas what is causing this?
Tested configurations:

Server: win7pro, 64bit (=:PC1), client: win xp pro 32 bit (=:PC2)
Server: PC2, client: PC1
both client and server xp pro 32bit

The game runs fine on each configuration for single player (ok, CTDs occur too but after several hours only).
Answer: I've never tried online play myself.
The brilliant guide RTSC Startopia has a few notes on its starting page. In particular, they say:

That online play, different from LAN play, doesn't work well. (Yeah, you figured that out yourself.) Meaning it's probably caused by desyncs due to the higher latency, something many older games struggle with.
That the autosave helped them after the frequent crashes.
That there's a rumour that the autosave itself causes the crashes and that disabling the autosaving by write-protecting the file might help. (Could this explain why it's almost after ten minutes for you?)
Do not try to save. Do not pause. Do not open the menu. (More indicating that desyncing is the issue at hand.)
That you shouldn't get frustrated by crashing multiplayer games, because it will just happen a lot. (Probably the most helpful tip, but also much easier said than done. :))
Comment: +1. And it was me that [originally suggested](http://forums.eidosgames.com/showthread.php?t=21755) that autosaving caused crashes (almost 7 years ago now looking at the timestamps...blimey), no real official confirmation was obtained - but saving in general is "dangerous" and could cause the desyncs. I'd probably advice *against* blocking autosaves unless you really *have* to, because they're the only real way to recover from a crash, but if you can't get past the first 10 minutes, it may be worth trying.
Comment: +1 thanks, I'll try blocking the autosave since I can't load them anyway because of that weird behaviour when entering the menu (also @DMA, the autosave doesn't help much if I can't load it...). Although there _are_ autosaves from the multiplayer which when loaded into singleplayer have the second player being totally idle.


Axon: Multi Command for single Aggregate

Question: I have a pretty nice idea for fine granular API command handling.
Our web API should provide single simple update endpoint, but you can provide multiple commands to it. Something like this:
POST /myAggregate/12345/update
[
  { command1Name: "command1Data" },
  { command2Name: "command2Data" },
  { command3Name: "command3Data" }
]

Within Axon this seems quite difficult to handle. Especially in combination with @AggregateVersion.

My first idea was to have a new UpdateWrapperCommand. which internally has a List commands. And then within the Aggregate, you use reflection to call the correct @CommandHandler methods:
class UpdateWrapperCommand {
  List commands;
}

@Aggregate
class MyAggregate {
  // id, version, constructor, etc. pp.

  @CommandHandler
  public void handle(SomeCommand cmd) { ... }

  @CommandHandler
  public void handle(UpdateWrapperCommand cmd) {
    // iterate over cmd.commands
    // iterate over this.getClass().getMethods()
    // find correct method(s), and invoke it
  }
}

But when the @CommandHandlers also use @MetaData and/or Spring Bean injection, then it's getting really hard.

My second idea was to simple call commandGateway.send in a loop. But that blows up, because @TargetAggragateVersion must be set for every command, and you have to wait for every command to complete, before sending the next one. That's not nice.

Do you have any ideas for that?
It should load the aggregate once and then run all commands.
And maybe even have some transaction-like behavior: Apply all resulting events, or none.
Answer: I think you're best bet to get this resolved right now, without the need to wait to the issue you've added to Axon Framework's issue tracker, is to add an External Command Handler.
The External Command Handler is just a regular Component with an @CommandHandler annotated function on it. That method would handle your UpdateWrapperCommand and know the works to issue separate commands for every command payload contained it.
The loading optimization of the Aggregate as you're suggesting is however really tied to implementing a Batch Command solution. Although this is definitely doable in the framework, this feature isn't in place yet.
I'd suggest you keep tracking the issue you've created to follow the progress of it.
Hope this helps you out Benjamin!
Answer: If the transaction means that is all or nothing, then probably the boundaries of each commands are not well modelled.
Without understanding of domain I would say options are:
1 Wrap all the commands in only one and apply to one handle-all aggregate.
2 Apply all the commands independently and in case of any failure then apply compensating actions.
3 Not to use commands at all and just apply the transactional logic over something simpler.
Comment: The commands are modeled well, that's not the problem. They are very fine granular, but it depends on the client if this granularity is needed or not. Of course I could use `ChangeName` and `ChangeAddress` for mobile clients and introduce `ChangeNameAndAddress` for desktop clients, but that doesn't feel DRY. Though I'd like to reuse the existing commands. `...` And additionally this is some kind of optimization for the server: It only has to load the aggregate once, and then run all commands. Instead of load aggregate, run command, apply event, persist, load aggregate, run command, ...


while loop doesnt work, javascript only

Question: I want to move this red rectangle randomly over the screen and if I click on it,  it should fall down. I need this code in javascript only , no jQuery, please.

        <canvas id="myCanvas" width="1280" height="600" style="border:1px solid #d3d3d3;color:red;"></canvas>

the main purpose of this code is i need to move this div randomlly and if i click on it it will fall down ,
                i need this code in javascript only , no jquery,please help

Comment: `=` is not a comparison operator. Use `==`.
`while(s == true){`
`if (w.onclick == true){`
Comment: Nothing bro ,need help
Comment: Delete `()` after `else`.
But your code seems infinity loop.
Answer: You have a couple of errors in your code, both syntactic and logically:

else() else is not a function
while(s = true) see the comment by @yasuyuki-uno
you are declaring var i without using it

Then you have an infinite loop that is so fast that the browser locks up. You need to use setInterval() instead.
A fixed version looks like this:
  var c = document.getElementById("myCanvas");
  var ctx = c.getContext("2d");
  var w = document.getElementById("myCanvas");
  timer = setInterval(function() {

        var f = Math.floor(1+Math.random()*680);
        var f2 = Math.floor(1+Math.random()*400);
      console.log (f, f2);

        ctx.fillStyle="#FF0000";
        ctx.clearRect(0, 0, c.width, c.height);
        ctx.fillRect(f, f2, 100, 50);
        w.onclick = function() {
            clearInterval(timer);
            falling();
        }
     }, 100)
    function falling(){
       // do something here
    }

See also the JSBin.
But please, before coming with code containing syntax errors, go to something like http://www.jslint.com/ and check your code first.
Comment: Thank you man a lot , but how can I add transition duration to the canvas ?
I'm so new in coding
Comment: That should be a new question with a `canvas` tag
Comment: I'm sorry man , I mean between evey position of the canvas I need like
-webkit-transition-duration: 1s;
Comment: I know. But Stackoverflow really works like "one problem per question". So if you need transitions, ask a new question.

while loop doesnt work, javascript only


Magento module add rows to totals in pdf invoice

Question: I'm trying to write module for add item to row totals in pdf invoice. This is my modules config.xml:
<?xml version="1.0"?>
<config>
<modules>
<Devpassion_Rowtotal>
    <version>0.0.1</version>
</Devpassion_Rowtotal>
</modules>
<global>
 <pdf>
     <totals>
         <rowtotal translate="title">
            <title>Subtotal less discount</title>
            <source_field>rowtotal</source_field>
            <model>rowtotal_pdf_model_totalpdf</model>
            <font_size>7</font_size>
            <display_zero>1</display_zero>
            <sort_order>200</sort_order>
         </rowtotal>
     </totals>
  </pdf>

And this is my model class:
class Devpassion_Rowtotal_Pdf_Model_Totalpdf extends   Mage_Sales_Model_Order_Pdf_Total_Default {

public function getTotalsForDisplay () {

$order = $this->getOrder();
$item = $this->getItem();

$subtotaldisc = $item->getRowTotal() + $item->getTaxAmount() + $item->getHiddenTaxAmount() ; - $item->getDiscountAmount();
$result = $order->formatPriceTxt($subtotaldisc) ;

$totals = array(array(
    'label' => 'Cijena sa popustom',
    'amount' => $result,
    'font_size' => $fontSize,
    )
    );

return $totals;

}

}

And nothing shows up on pdf invoice. Can anybody advice please what can be wrong here. Thanks.
Comment: Have you got the solution @srdan? I have the same problem. Please share if you solved it.
Comment: please see my and @Wakanina answer below
Answer: I solved my problem, after I looked at my code, there is some mistakes. But my problem is not like yours.
I noticed that you have incorrect code in your config.xml and also in your model class. Try this.
config.xml
<global>
   <pdf>
     <totals>
         <rowtotal translate="title">
            <title>Subtotal less discount</title>
            <source_field>rowtotal</source_field>
            <model>Devpassion_Rowtotal_Pdf_Model_Totalpdf</model>
            <font_size>7</font_size>
            <display_zero>1</display_zero>
            <sort_order>200</sort_order>
         </rowtotal>
     </totals>
  </pdf>
</global>

Model class, Totalpdf.php
class Devpassion_Rowtotal_Pdf_Model_Totalpdf extends Mage_Sales_Model_Order_Pdf_Total_Default {

   public function getTotalsForDisplay() {

      $order = $this->getOrder();
      $item = $this->getItem();

      $subtotaldisc = $item->getRowTotal() + $item->getTaxAmount() + $item->getHiddenTaxAmount() - $item->getDiscountAmount();
      $result = $order->formatPriceTxt($subtotaldisc);

      if($this->getAmountPrefix()){
         $result= $this->getAmountPrefix().$result;
      }

      $fontSize = $this->getFontSize() ? $this->getFontSize() : 7;

      $totals = array(array(
                'label' => 'Cijena sa popustom:',
                'amount' => $result,
                'font_size' => $fontSize,
             )
         );

      return $totals;
   }

}

Answer: I have tried the above code, it doesn't get the value of $item. I have get the subtotal value and discount value from $order object and it worked.
    $order = $this->getOrder ();
    $subtotaldisc = $order ['subtotal'] + $order ['discount_amount']; //discount amount returns negative value, so add
    $result = $order->formatPriceTxt ( $subtotaldisc );
    $fontSize = $this->getFontSize () ? $this->getFontSize () : 10;
    $totals = array (
            array (
                    'label' => 'Subtotal with Discount',
                    'amount' => $result,
                    'font_size' => $fontSize
            )
    );
    return $totals;

Answer: I follow @Wakanina answer and change config.xml - path to pdf mode:
<pdf>
            <totals>
              <rowtotalbezpdv translate="title">
                <title>Ukupno s popustom</title>
                <source_field>rowtot_alamount</source_field>
                <model>Devpassion_Rowtotalbezpdv_Model_Pdf_Total_Totalbezpdf</model>
                <font_size>7</font_size>
                <display_zero>0</display_zero>
                <sort_order>300</sort_order>
              </rowtotalbezpdv>
            </totals>
        </pdf>

And totalpdf Model class:
class Devpassion_Rowtotalbezpdv_Model_Pdf_Total_Totalbezpdf extends Mage_Sales_Model_Order_Pdf_Total_Default
{

    public function getTotalsForDisplay(){
        $amount = $this->getAmount();
        $fontSize = $this->getFontSize() ? $this->getFontSize() : 7;
        if(floatval($amount)){
            $amount = $this->getOrder()->formatPriceTxt($amount);

            $totals = array(
                array(
                    'label' => 'Cijena knjige/a s popustom bez PDV-a',
                    'amount' => $amount,
                    'font_size' => $fontSize,
                )
            );

            return $totals;
        }
    }

    public function getAmount(){
        $order = $this->getOrder();
        $subtotaldiscnopdv = 0;
        foreach ($order->getAllItems() as $item) {
            $subtotaldiscnopdv += $item->getRowTotal() - $item->getDiscountAmount();
        }
        return $subtotaldiscnopdv;
    }
}

This helps me out and solve my issue.


How to evaluate $\prod_{n=1}^{p-1} \sin(\frac{2n^2\pi}{p})$

Question: According to Quadratic Gauss sum
I want to know what is the exact value of this product?,since I put this product on Wolfram Alpha and I got the result in this form $$\frac{a+b\sqrt{
p}}{c}$$ for some positive integers $a,b,c$
But I dont know How a,b,c are related to each other.
Comment: I haven't still come up with an answer, but I suggest that you consider regarding the product as a collection of pairs $\sin (2n^2\pi/p)\sin(2(p-n)^2\pi/p)$.
Comment: For $p=11$, the product is equal to a rational number $\frac{11}{2^{10}} $, which doesn't agree with your given form.
Answer: I suppose $p$ is an odd prime. Let the product be $S_p$ (it is positive). Using
$$\ln\left|2\sin\frac{x}{2}\right|=-\sum_{m=1}^{\infty}\frac{\cos mx}{m}\qquad(x\notin2\pi\mathbb{Z}),$$
we see that
$$\ln(2^{p-1}S_p)=-\sum_{m=1}^{\infty}\frac{l_p(m)}{m},\qquad l_p(m)=\sum_{n=1}^{p-1}\cos\frac{4mn^2\pi}{p}.$$
The article allows to find $l_p(m)=a_p(m)+b_p(m)$, where
$$a_p(m)=\begin{cases}p-1,&p\mid m\\\hfill-1,&p\nmid m\end{cases},\qquad b_p(m)=\begin{cases}\Big(\dfrac{2m}{p}\Big)\sqrt{p},&p=4k+1\\\hfill0,&p=4k+3\end{cases}.$$
Now we have
\begin{align}\sum_{m=1}^{\infty}\frac{a_p(m)}{m}&=\sum_{q=0}^{\infty}\left(\frac{1}{q+1}-\sum_{r=1}^{p}\frac{1}{pq+r}\right)\\&=\sum_{q=0}^{\infty}\int_0^1 x^{pq}\left(px^{p-1}-\frac{1-x^p}{1-x}\right)dx\\&=\int_0^1\left(\frac{px^{p-1}}{1-x^p}-\frac{1}{1-x}\right)dx=-\ln p,\end{align}
which settles $p=4k+3$, giving $S_p=p/2^{p-1}$.
The case $p=4k+1$ is harder. The so-called class number formula tells
$$\sum_{m=1}^{\infty}\frac{b_p(m)}{m}=\Big(\frac{2}{p}\Big)\sqrt{p}\ L(1,\chi_p)=2\Big(\frac{2}{p}\Big)h(p)\ln\epsilon_p,$$
where $L(1,\chi_p)$ is the Dirichlet $L$-function for $\chi_p(m)=\Big(\dfrac{m}{p}\Big)=\Big(\dfrac{p}{m}\Big)$ (in our case), $h(p)$ is the class number of $\mathbb{Q}(\sqrt{p})$ (fixme...), and $\epsilon_p$ is the fundamental unit of $\mathbb{Q}(\sqrt{p})$. Finally,
$$S_p=\begin{cases}\dfrac{p}{2^{p-1}}\epsilon_p^{-2h(p)(\frac{2}{p})},&p=4k+1\\ \hfill\dfrac{p}{2^{p-1}},&p=4k+3\end{cases}.$$
Comment: (I've put a "fixme..." because actually I take, for $h(p)$, the class number that PARI/GP computes. It might be not the same as referenced above...)


How do you make a single-page-application (SPA) searchable from SharePoint?

Question: We are working on a single-page-application (SPA) developed in ASP.NET MVC using knouckout and a wealth of other libraries. Routing will be done in front-end, maybe we will use crossroads.js. A lot of information is presented in virtual grids using slickgrid.js. All data is fetched from backend using AJAX.
Now, if you want to crawl and index such a site from SharePoint, how would you go about that? If you just load the main page with no javascript, it is almost empty.
Update
After more investigation into this issue, I have concluded that there are at least two possible solutions to this kind of problem.
Possible solution 1: Render HTML
This approach would involve detecting that a SP crawler is crawling your site, and then return static HTML pages for the crawler. PhantomJS could possibly be used for this. There are however several uncertain aspects to this solution, and I suspect that it would involve a lot of work.
Possible solution 2: Import data into SharePoint
As so clearly described by Josh below, you could import the data that you want crawlable into SharePoint. Then SharePoint can be configured to crawl the data, and the data is not Javascript dependant anymore as it is inside SharePoint. I think this is the best and easiest solution and will mark Josh answer as the accepted answer.
Comment: I understand if this question comes about as a bit too open-ended for stackoverflow, but information about this subject is really hard to find and it do boils down to a specific technical problem. Google has published [this article](https://developers.google.com/webmasters/ajax-crawling/docs/learn-more) but if SharePoint support that is unclear according as to what I have found.
Answer: While I see that this question is getting a lot of close requests, I did run across this very question on a previous project.  Sharepoint won't be able to index the page that data is manipulated on via your SPA, but inside SP, you can connect external data sources into the search service, thus exposing the data inside the SPA.  You would then write custom search results tied to the content type of the data exposed in order to make the results a bit more friendly than just a data row.  You might create an entry point in your SPA that can take in a URL with a parameter so you can send the user from the search results to the SPA in one shot.
There are a lot of interconnected concepts to this solution, so I'd suggest looking into connecting external data sources and adding them to the crawled index of SP.  Then, create a content type out of the exposed objects.  And finally, add a custom search result template for the content type.  MSDN will be your friend on this and so will your SP administrator.
Comment: I have gone down the same route in my design, and think this is the best and easiest solution. This answer provides a lot of valuable concepts and will help me going forward. Thanks!


How can I make a variable volatile or const using LLVM pass

Question: Is there any LLVM built in method that allows making my variable volatile or const.
For example, if my program in C is,
<code>#include<stdio.h>
int main() {
    int x=1,y=2,z=10;
    z=x+y;
    return 0;
}
</code>
I want to change this program using LLVM pass such that it behaves as below,
<code>#include<stdio.h>
int main() {
    volatile int x=1,y=2,z=10;
    z=x+y;
    return 0;
}
</code>
Answer: Ok, I got it. It would be simple setVolatile(1).
Pass would look something like this,
<code>for(Module::iterator F=M.begin(),e=M.end();F!=e;++F){
    for(Function::iterator B=F->begin(),e=F->end();B!=e;++B){
        for(BasicBlock::iterator i=B->begin(),e=B->end();i!=e;++i){
            if(isa<StoreInst>(i)){
                StoreInst *temps=dyn_cast<StoreInst>(i);
                temps->setVolatile(1);
            }
            if(isa<LoadInst>(i)){
                 LoadInst *temps=dyn_cast<LoadInst>(i);
                 temps->setVolatile(1);
            }
        }
    }
}
</code>