I'm working on SFML and I really want to know deeply about Transformation that is about: position, rotation, scale and origin, of an object

Question: I am looking at the "SFML/Graphics/Transform.h"
and "SFML/Graphics/Transformable.h" headers and I can't
understand one thing. I minimize
the classes so you guys can get it easily:
// "SFML/Graphics/Transform.h"
class Transform
{
 public:
// Default constructor
Transform();

// Construct a transform from a 3X3 matrix
Transform(float a00, float a01, float a02,
          float a10, float a11, float a12,
          float a20, float a21, float a22);
};

// "SFML/Graphics/Transformable.h"
class Transformable
{
private:
Vector2f mPosition;                             // Position of the object in 2D world.
float mRotation;                                // Orientation of the object, in degress.
Vector2f mScale;                                // Scale of the object.
Vector2f mOrigin;                               // Origin of translation, rotation and scaling.of the object.
mutable Transform mTransform;                  // Combined transformation of the object.
mutable bool      mTransformNeedUpdate;        // Does the transform need to be recomputed?
mutable Transform mInverseTransform;           // Combined transformation of the object.
mutable bool      mInverseTransformNeedUpdate; // Does the transform need to be recomputed?

public:
// Functions to implement transformation
void setPostion(float x, float y);
void setPosition(const Vector2f& position);
void setRotation(float angle);
void setScale(float factorX, float factorY);
void setScale(const Vector2f& factors);
void setOrigin(float x, float y);
void setOrigin(const Vector2f& orgin);

const Vector2f& getPosition() const;
float getRotation() const;
const Vector2f& getScale() const;
const Vector2f& getOrigin() const;

void move(float offsetX, float offsetY);
void move(const Vector2f& offset);
void rotate(float angle);
void scale(float factorX, float factorY);
void scale(const Vector2f& factors);

// What I don't understand
const Transform& getTransform() const;
const Transform& getInverseTransform() const;
};

In the "SFML/Graphics/Transformable.cpp" the "getTransform()" function
is implemented as the following code:
const Transform& Transformable::getTransform() const
{
    // Recompute the combined transform if needed
    if (mTransformNeedUpdate)
    {
        float angle  = -mRotation * 3.141592654f / 180.f;
        float cosine = static_cast<float>(std::cos(angle));
        float sine   = static_cast<float>(std::sin(angle));
        float sxc    = mScale.x * cosine;
        float syc    = mScale.y * cosine;
        float sxs    = mScale.x * sine;
        float sys    = mScale.y * sine;
        float tx     = -mOrigin.x * sxc - mOrigin.y * sys + mPosition.x;
        float ty     =  mOrigin.x * sxs - mOrigin.y * syc + mPosition.y;

        mTransform = Transform( sxc, sys, tx,
                                -sxs, syc, ty,
                                 0.f, 0.f, 1.f);
        mTransformNeedUpdate = false;
    }

    return mTransform;
}

My question is how they implement these values: sxc, syc, sxs, sys, tx, ty
like that and why they put them into the 3X3 matrix by that order.
Thank you a lot!!!
Answer: Maybe, this two links can help you:
The doc of sf::Transform
The github source code
Answer: It seems you're asking how geometric transformations are generally handled in computer graphics.
Be it in 2d or 3d (or nd I guess), you can implement scaling and rotation by way of matrix multiplication. That is, you have an object -a bunch of points- and you transform it by multiplying the coordinates of each point -a.k.a vectors- by a transform matrix. Those matrices have particular values.
Scaling
To scale from the origin by a factor k, the matrix will be like this:
k 0
0 k

Rotation
Rotation of angle a around the origin:
cos(a) -sin(a)
sin(a) cos(a)

These 2x2 matrices can then be multiplied by a 2d vector. The result will be a 2d vector with the transformed coordinates.
You can also combine these two transforms, i.e. do rotation and scaling all at once, by first multiplying the two transforms together, and use the resulting 2x2 matrix to do the product with a vector.
Translation
The problem is you cannot do translation as a product in this system. You could do it by way of vector addition. But to do all transforms uniformly and efficiently, something called homogeneous coordinates are used. In that system, 2d transformations need points as 3d vectors and 3x3 matrices. 3d transforms need 4d vectors and 4x4 matrices.
The matrix you see in SFML's source is the combination (or composition) of the scale, rotation and translation information contained in the sf::Transform object, in homogeneous coordinates. The values are arranged in the matrix in the right way to do the transformations just by applying the product of the matrix to a vector. sf::Vector2 actually contains 3 components.


Is it possible to perform loadtesting on thick client Excel 2007

Question: We are planning to do a load test on thick client Excel 2007 using HP Load Runner 11.0.Excel application has got macros enabled and has got web services running in the back end to communicate with the server.
Is it possible to do Load test.
Also when we tried recording excel 2007 using vugen, events were not recorded and found that this requires a patch from HP. If some one has got patch and are able to do it, please let me know.
Any timely help on this is appreciated.
Answer: One: You are engaging in software piracy when you ask for a cracked patch.  If you are legitimately able to have access to the patches because of a maintenance agreement then you can simply download the patches yourself.
That comment about the cracked patch has made me personally far less likely to assist you completely.
Two: I will say, "Yes" it is possible.   I will not give you the steps but assuming you have skills with the tool and the foundations skills required by the profession you will be able to figure this out.
Three: LoadRunner has been able to record HTTP conversations, the communication foundation for web services, via proxy wince LoadRunner version 5.02, which was available in 1998.  That capability is retained even in the most current release. That is going to be your key.
Four: Because you operate in the cracked software universe which is a stain on the whole performance testing profession you do not get the explicit steps that may well have been provided.   Good luck to you on this issue and may your next software audit go well.
Don't be a crack head.  It has long term career and social consequences.   You are introducing substantial financial risk into a profession designed from the outset to identify, eliminate, manage and control risks.   Your behavior is running counter to your profession
Comment: Thanks for the help James. When I meant crack does not mean Iam trying to crack the software or am asking help if some one has done it. We were in the process of evaluating whether LR 11.0 can go well with Excel 2007. Apologies if I sounded unprofessional with the word crack.
Comment: As you are evaluating please turn your questions to your VAR or HP Systems engineer.  Assuming you are involved in a legitimate pre-purchase evaluation of LoadRunner, the SE can provide any patch you need to complete your evaluation prior to purchase.  Changing your original post to remove the reference to the cracked patch does not alter your intended behavior, it was quite transparent in nature.     What you want to do requires no patch to the software but it does require someone who knows the software, such as your VAR or HP SE who is assisting with your evaluation. Good day to you.


Migrating data without the old model

Question: I accidentally managed to lose the old version of our data model, and now the automatic lightweight migration doesn't work (obviously). I managed to let Core Data delete the old store if this problem occurs, but i obviously would want to not lose the old data. So how can i manually migrate? On startup, i just get an error that the store coordinator has no persistent stores (error 134140).
I have already tried making a new model version that matches the old one (It actually states the old, used model in the error message), but somehow this doesn't work either. It used to work before, but apparently i just messed up saving the model verison of the current app store version.
Edit: I just thought of possibly another way (No idea why i didn't think of this before): Because core data is backed by an SQLite database, can't i get the information i need (That is, 4 rows from the database, then i can repopulate the rest of it myself) directly from it? If so, what could i use to do this?
Comment: Your current question cannot be answered.  You need to provide more details.
Comment: What additional information would you need? I have a database without the old model, and when updating the app it can't migrate the data to the new model.
Comment: I just thought of possibly another way (No idea why i didn't think of this before): Because core data is backed by an SQLite database, can't i get the information i need (That is, 4 rows from the database, then i can repopulate the rest of it myself) directly from it? If so, what could i use to do this?
Answer: I'm not exactly sure how it's done, but the model is versioned, perhaps using an GUID or a cryptographic hash of the model file. So you need exactly the same file that the model was created with.
Or put another way, you need to be using version control.
I guess it should be theoretically be possible to exactly recreate your model, but I don't know of a way of doing it.
Comment: Damn, i was afraid of that. I do have git, but it appears there are no commits of that update... i messed up quite a bit.
Comment: The way i did it was by reading the most important data manually via SQL, and then recreating the database with that data.

Migrating data without the old model


iphone app performance data

Question: i was trying running application with instrument tool. but it collects so many data. so i am confuse where to look exactly in  order to optimize my app. is there any best start up guide or any best practice.
hope my question is genuine and clear.
Edit: attaching sample image from instrument.how to interpret this data.alt text http://www.freeimagehosting.net/uploads/7c99370ca9.png
click here for full screen Here
Comment: ++ English is a difficult language, but your question is very clear.
Comment: thanks Mike. i have edited my question. i am still confuse whether orange bar is a leak or blue bar (in the leaks tab)..
Comment: [Check this answer.](http://stackoverflow.com/questions/2052598/line-level-profiling-for-iphone/2066207#2066207)
Answer: What that screenshot is showing me is that you have some leaks in your code. You can find out more details about them by turning on the extended detail. You can do this by going to View->Extended Detail you can then use this information to help you get rid of the leak.
If you want to look at the CPU performance of your app you can use the CPU Sampler that is built in to Instruments. You can access it from Xcode Run -> Run with Performance Tool -> CPU Sampler
Answer: In the leaks bar you see the orange spikes which show you the occurrence of the leak (the point in time it happened); the blue below it is an indication of the total leak amount  which builds over time - you see it continue at one level for a while after the first leak, then you have the second leak and the total leaks display grows.
To get more detail double-click on the items in the list view. You will drill down to more levels of details and hopefully come to a view which will help you find the leak. But it's nowhere near as easy to see what is wrong as the little blue arrows that you get with a static analysis build...
The best approach I think is to make sure you are running Snow Leopard, the latest Xcode and start using static analysis. Since I started using it I found leaks in older code that Instruments hadn't revealed (probably my fault in not using it correctly, but anyway...) and I have found no new leaks in new code. The worst thing about it is false positives but it certainly kills leaks.
Comment: thanks Adam.that really help. but i do i fix leaks which are in not in my code, like in image i posted all leaks belong to system.
Comment: If you are sure it is a system leak be sure to use the http://developer.apple.com/support/iphone/bugreports/ page. In the WWDC09 videos Apple engineers said these are mostly false positive reports (tool error) but you might have found a real leak.

iphone app performance data


Calculating the Lyapunov exponent of the times-m map, $E_{m}$.

Question: I'm trying to compute the Lyapunov exponents for $E_{m}$, where $E_{m}:S^{1}\to S^{1}$, $x\mapsto mx\mod 1$.
The Lyapunov exponent is given by $$\chi(x,v)=\overline{\lim_{n\to\infty}}\frac{1}{n}\log\|df^{n}(x)v\|$$
I take $f^{n}(x)=E^{n}_{m}x=(mx\mod 1)\underbrace{\circ...\circ}_{n\text{ times}}(mx\mod 1)$
Then $$\chi(x,v)=\overline{\lim_{n\to\infty}}\frac{1}{n}\log\|dE^{n}_{m}xv\|$$
$E_{m}$, $m>1$, has positive exponents at all points. So there is a sequence $n_{j}\to\infty$ such that for all $\eta>0$, $$\|dE^{n}_{m}xv\|\ge e^{(\chi-\eta)n_{j}}\|v\|$$
To be honest I don't really know where I am going with this. I have never calculated Lyapunov exponents before and I could not find any similar examples.
Answer: What stops you from using the definition directly? The derivative of $E_m$ is everywhere equal to $m$. It is enough.
Comment: I already worked it out actually. I will write out the answer later.


how do you save the output of a function that prints in C language?

Question: let's say there is a (void)function I define that prints some numbers and I want to check if it prints the correct content. I'm thinking writing the content to a file and read it back and check if it is what I wanted.  But I dont know how since the function is void and returns nothing.
Comment: Environment? Shell? Language? Fix tags and expand the question please.
Comment: Sorry, I'm using my phone and for some reason I can't put file I/O as one tag .
Comment: That looks good now :)
Comment: Sorry my question wasn't really clear because I was using my phone. I was trying to find out how I can write data that is printed to stdout in to a file and I found freopen() which does the job :). Thanks for the help tho
Answer: I just found out I can use freopen() to write data into a file from stdout. My bad for not making the question more clear.


Making the leap from PhP to Python

Question: I am a fairly comfortable PHP programmer, and have very little Python experience. I am trying to help a buddy with his project, the code is easy enough to write in Php, I have most of it ported over, but need a bit of help completing the translation if possible.
The target is to:

Generate a list of basic objects with uid's
Randomly select a few Items to create a second list keyed to the uid containing new
properties.
Test for intersections between the two lists to alter response accordingly.

The following is a working example of what I am trying to code in Python
<?php
srand(3234);
class Object{  // Basic item description
    public $x       =null;
    public $y       =null;
    public $name    =null;
    public $uid     =null;
}
class Trace{  // Used to update status or move position
#   public $x       =null;
#   public $y       =null;
#   public $floor   =null;
    public $display =null;  // Currently all we care about is controlling display
}
##########################################################
$objects = array();
$dirtyItems = array();

#CREATION OF ITEMS########################################
for($i = 0; $i < 10; $i++){
    $objects[] = new Object();
    $objects[$i]->uid   = rand();
    $objects[$i]->x     = rand(1,30);
    $objects[$i]->y     = rand(1,30);
    $objects[$i]->name  = "Item$i";
}
##########################################################

#RANDOM ITEM REMOVAL######################################
foreach( $objects as $item )
    if( rand(1,10) <= 2 ){  // Simulate full code with 20% chance to remove an item.
        $derp = new Trace();
        $derp->display = false;
        $dirtyItems[$item->uid] = $derp;  //#  <- THIS IS WHERE I NEED THE PYTHON HELP
        }
##########################################################
display();

function display(){
global $objects, $dirtyItems;
    foreach( $objects as $key => $value ){  // Iterate object list
        if( @is_null($dirtyItems[$value->uid]) )  // Print description
            echo "
$value->name is at ($value->x, $value->y) ";
        else  // or Skip if on second list.
            echo "
Player took item $value->uid";

    }
}
?>

So, really I have most of it sorted I am just having trouble with Python's version of an Associative array, to have a list whose keys match the Unique number of Items in the main list.
The output from the above code should look similar to:
Player took item 27955
Player took item 20718
Player took item 10277
Item3 is at (8, 4)
Item4 is at (11, 13)
Item5 is at (3, 15)
Item6 is at (20, 5)
Item7 is at (24, 25)
Item8 is at (12, 13)
Player took item 30326

My Python skills are still course, but this is roughly the same code block as above.
I've been looking at and trying to use list functions .insert( ) or .setitem( ) but it is not quite working as expected.
This is my current Python code, not yet fully functional
import random
import math

# Begin New Globals
dirtyItems = {}         # This is where we store the object info
class SimpleClass:      # This is what we store the object info as
    pass
# End New Globals

# Existing deffinitions
objects = []
class Object:
    def __init__(self,x,y,name,uid):
        self.x = x  # X and Y positioning
        self.y = y  #
        self.name = name #What will display on a 'look' command.
        self.uid = uid

def do_items():
    global dirtyItems, objects
    for count in xrange(10):
        X=random.randrange(1,20)
        Y=random.randrange(1,20)
        UID = int(math.floor(random.random()*10000))
        item = Object(X,Y,'Item'+str(count),UID)
        try: #This is the new part, we defined the item, now we see if the player has moved it
            if dirtyItems[UID]:
                print 'Player took ', UID
        except KeyError:
            objects.append(item) # Back to existing code after this
            pass    # Any error generated attempting to access means that the item is untouched by the player.

# place_items( )
random.seed(1234)

do_items()

for key in objects:
    print "%s at %s %s." % (key.name, key.x, key.y)
    if random.randint(1, 10) <= 1:
        print key.name, 'should be missing below'
        x = SimpleClass()
        x.display = False
        dirtyItems[key.uid]=x

print ' '
objects = []
random.seed(1234)

do_items()

for key in objects:
    print "%s at %s %s." % (key.name, key.x, key.y)

print 'Done.'

So, sorry for the long post, but I wanted to be through and provide both sets of full code.  The PhP works perfectly, and the Python is close. If anyone can point me in the correct direction it would be a huge help.
  dirtyItems.insert(key.uid,x) is what i tried to use to make a list work as an Assoc array
Edit: minor correction.
Comment: try to use `dirtyItems` as `dict` instead of `list`. You can insert an key value pair as `dirtyItems[key]=value`
Comment: This is great, I got it working now thanks, I think it is hilarious that basically the extent of the change consisted of **switching [] to {}** and a few other minor corrections. Now I can have this integrated into the main project for next release.
Comment: If you're doing things such as intersecting sets then you should make the objects [hashable](http://docs.python.org/2/reference/datamodel.html#object.__hash__) so that they can participate in `set`.
Answer: You're declaring dirtyItems as an array instead of a dictionary. In python they're distinct types.
Do dirtyItems = {} instead.
Comment: Thanks Loads guys! I could feel it was close, I'm not sure how long it would have taken me to figure out to look for a Dictionary type.
Answer: Make a dictionary instead of an array:
import random
import math

dirtyItems = {}

Then you can use like:
dirtyItems[key.uid] = x

Making the leap from PhP to Python


getting status 503 from google cloud storage

Question: I'm having trouble uploading images to google cloud storage in newly created app engine apps using the default bucket.
I'm using upload code that works perfectly fine when deployed to older app engine apps that have already active default buckets. When I create a new app engine project or activate the default gcs bucket on appengine.google.com then I get a strange 500 (503) error.
my upload code uses the cloudstorage client and looks like this:
def save_to_gcs(file_obj, obj):
    # pass a file and a datastore entity to associate the file to

    serving_url = ''#just assign it adn reassign later

    time_stamp = int(time.time())
    app_id = app_identity.get_application_id()

    logging.error("got app_id .... %s" % app_id)

    fname = '/%s.appspot.com/post_%s_%s.jpg' % (app_id, obj.key.id(), time_stamp)

    # logging.error(file_obj)
    logging.error("fname .... %s" % fname)

    gcs_file = gcs.open(fname, 'w', content_type="image/jpeg")
    gcs_file.write(file_obj)
    logging.error("written file obj ....")# <-- this is where the logs stop
    gcs_file.close()

    gcs_filename = "/gs%s" % fname
    serving_url = images.get_serving_url(blobstore.create_gs_key(gcs_filename))
    logging.error("got serving url ....")
    media_obj = save_gcs_to_media(gcs_filename, serving_url, obj)
    logging.error("saved media obj ....")

    return media_obj

I think the errors have something to do with the file.close() method and probably some auth thing with the default bucket.
I'm properly authenticated and the file I'm uploading is I about 100kb, so nothing large.
Any help would be really appreciated (in fact it would prevent my hair first going grey, then falling out).
Sorry for the mess, but here are the logs:
E 11:05:54.412 - - - - COVER - - - -

E 11:05:54.413 True

E 11:05:54.413 got time stamp

E 11:05:54.413 got time file name

E 11:05:54.413 got app_id .... emile-test

E 11:05:54.413 fname .... /emile-test.appspot.com/post_5629499534213120_1436432754.jpg

E 11:05:54.696 written file obj ....

D 11:05:55.025 Tasklet is <bound method _StorageApi.urlfetch_async of <cloudstorage.storage_api._StorageApi object at 0xfbd7bf10>>

D 11:05:55.025 Got result <google.appengine.api.urlfetch._URLFetchResult object at 0xfbd9a810> from tasklet.

D 11:05:55.025 Retry in 0.1 seconds.

D 11:05:55.477 Got result <google.appengine.api.urlfetch._URLFetchResult object at 0xfbd9a9b0> from tasklet.

D 11:05:55.478 Retry in 0.2 seconds.

D 11:05:56.152 Got result <google.appengine.api.urlfetch._URLFetchResult object at 0xfbd9ab30> from tasklet.

D 11:05:56.153 Retry in 0.4 seconds.

D 11:05:57.244 Got result <google.appengine.api.urlfetch._URLFetchResult object at 0xfbd9acb0> from tasklet.

D 11:05:57.245 Retry in 0.8 seconds.

D 11:05:58.435 Got result <google.appengine.api.urlfetch._URLFetchResult object at 0xfbd7b690> from tasklet.

D 11:05:58.435 Retry in 1.6 seconds.

D 11:06:00.542 Got result <google.appengine.api.urlfetch._URLFetchResult object at 0xfe4ce630> from tasklet.

D 11:06:00.542 Retry in 3.2 seconds.

D 11:06:04.179 Tasklet failed after 7 attempts and 9.48189997673 seconds in total

**E 11:06:04.180 Expect status [200] from Google Storage. But got status 503.**

  Path: '/emile-test.appspot.com/post_5629499534213120_1436432754.jpg'.
  Request headers: {'content-range': 'bytes 0-108067/108068', 'x-goog-api-version': '2', 'accept-encoding': 'gzip, *'}.

  Response headers: {'content-length': '0', 'x-guploader-uploadid': 'AEnB2UqzyZwtoNSy8sTEUq7a8fai-A5aDVlMccCj1UVEo72NAUUw4kyDotehcf8RDusUzm52092rdO0CR9JxIC9ba1J5Kj1xuw'}.
  Body: ''.

  Extra info: {'upload_path': '/emile-test.appspot.com/post_5629499534213120_1436432754.jpg?upload_id=AEnB2UqzyZwtoNSy8sTEUq7a8fai-A5aDVlMccCj1UVEo72NAUUw4kyDotehcf8RDusUzm52092rdO0CR9JxIC9ba1J5Kj1xuw'}.

  Traceback (most recent call last):
    File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1535, in __call__
      rv = self.handle_exception(request, response, e)

File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1529, in __call__
      rv = self.router.dispatch(request, response)

File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1278, in default_dispatcher
      return route.handler_adapter(request, response)

File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 1102, in __call__
      return handler.dispatch()

File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 572, in dispatch
      return self.handle_exception(e, self.app.debug)

File "/base/data/home/runtimes/python27/python27_lib/versions/third_party/webapp2-2.5.2/webapp2.py", line 570, in dispatch
      return method(*args, **kwargs)

File "/base/data/home/apps/s~emile-test/1.385589451941224330/main.py", line 757, in post
      media_obj = utils.save_to_gcs(image, post)

File "/base/data/home/apps/s~emile-test/1.385589451941224330/utils.py", line 131, in save_to_gcs
      gcs_file.close()

**File "/base/data/home/apps/s~emile-test/1.385589451941224330/cloudstorage/storage_api.py", line 750, in close**
      self._flush(finish=True)
    File "/base/data/home/apps/s~emile-test/1.385589451941224330/cloudstorage/storage_api.py", line 804, in _flush
      self._send_data(data, self._written, file_len)

File "/base/data/home/apps/s~emile-test/1.385589451941224330/cloudstorage/storage_api.py", line 837, in _send_data
      {'upload_path': self._path_with_token})

File "/base/data/home/apps/s~emile-test/1.385589451941224330/cloudstorage/errors.py", line 141, in check_status
      raise ServerError(msg)
  ServerError: Expect status [200] from Google Storage. But got status 503.

  Path: '/emile-test.appspot.com/post_5629499534213120_1436432754.jpg'.
  Request headers: {'content-range': 'bytes 0-108067/108068', 'x-goog-api-version': '2', 'accept-encoding': 'gzip, *'}.

  Response headers: {'content-length': '0', 'x-guploader-uploadid': 'AEnB2UqzyZwtoNSy8sTEUq7a8fai-A5aDVlMccCj1UVEo72NAUUw4kyDotehcf8RDusUzm52092rdO0CR9JxIC9ba1J5Kj1xuw'}.
  Body: ''.

  Extra info: {'upload_path': '/emile-test.appspot.com/post_5629499534213120_1436432754.jpg?upload_id=AEnB2UqzyZwtoNSy8sTEUq7a8fai-A5aDVlMccCj1UVEo72NAUUw4kyDotehcf8RDusUzm52092rdO0CR9JxIC9ba1J5Kj1xuw'}.

Answer: I fixed exactly this problem (identical stack trace) in my own GAE project today (I'm migrating from the Files API in blobstore to cloudstorage). The steps I took were:

went to the Google Developers Console
https://console.developers.google.com/project/YOUR_APP_ID/storage/browser
where YOUR_APP_ID is the name the app without the .appspot.com suffix, e.g. 'foo', not 'foo.appspot.com',
Clicked on the three vertical dots on the right of my project
Selected Bucket Permissions
Added my email address as Entity=User, firstname.lastname@example.com, Access=Owner.

I'm not 100% sure why this fixed the problem, but it's done the trick.
Comment: You're my hero, thanks a million! I wonder what happened for that to be required so suddenly. Anyway I admire your skills of deduction for finding that out.


Strip specific tag from parent (jQuery)

Question: HTML:

Title 1

    Description goes here

Title 2

Description goes here

.. How do I strip out all
 tags from .featured?
Thanks
Answer: This works, but only because your paragraph elements are at the end of your divs:
$(".featured p").each(function(){
    var content = $(this).html();
    $(this).parent().append(content);
    $(this).remove();
});

Comment: `.text()` won't return you children tags.
Comment: @Adam Kiss - true, changed it to html() instead. Not sure if that warranted a down-vote though :)
Comment: Deleted downvote - it does not work :) Now it does - but look at my (edited) code though :) tested, does not `append()`, but `after()`, so it's in place of deleted ``.
Answer: Check out Ben Alman's unwrap "plugin"
$.fn.unwrap = function() {
  this.parent(':not(body)')
    .each(function(){
      $(this).replaceWith( this.childNodes );
    });

  return this;
};

your usage would be:
$(".featured p > *").unwrap();

Answer: $(".featured p").remove();

This works by changing each
 to . It does that in-place, so the
s don't have to be at the end (no append - it will not reorder the elements):
$(".featured p").replaceWith(function(){
     return $('').html( $(this).html() );
});

It is using html, so the element will lose data and event bindings.
Comment: But this way, you'll delete also it's contents, as I understand it, he wants just to strip the tags out.
Comment: exactly. I want to strip the tags only, not content.
Answer: Something like this?
$(".featured p").each(
  function(){
    $(this).after($(this).html()).remove();
});

Edit 2: Tested, works. nice and simple.
Comment: I still think this is closest to requirements :P No spans included, tested(finally), just strips out wrapper (in this case ``) :]
Comment: Well, it was written just as an idea, not solution, i haven't tested it.
Answer: With jQuery 1.4 you could do it like this:
$(".featured p *").unwrap();
$(".featured p").each(function(){
  $(this).replaceWith(""+ $(this).text() + "")
});

Test it here
Text nodes don't get unwraped, so you have to do them separately. I'm not sure why replaceWith requires them to be inside tags.

Strip specific tag from parent (jQuery)


How does Blizzard determine if I preordered a retail copy of Diablo 3: Reaper of Souls?

Question: Procrastination caused me to only reserve my copy of Diablo 3: Reaper of Souls this morning at Best Buy. I'm not sure this will count as a preorder by which I can earn preorder loot. How does Blizzard determine what constitutes a Diablo 3: Reaper of Souls preorder?
Comment: The most logical guess would be some form of one-time-use code in addition to the serial key, given out by retailers or inside the packaging for the game.
Comment: If you are talking about these golden wings that everybody has now, then the answer would be: "They don't. You just have to register your copy **before 31/03** to get these wings". Otherwise I don't have any idea how they track it. Most probably just like @TZHX said
Comment: @Mkalafut thank you for the reminder, I had forgotten to close the loop on this question. ;)
Comment: @TZHX agreed, just trying to figure out if this mornings reservation will count based on how they're doing it. Hoping someone who went through the process will have the answer.
Comment: Hey Ash, if you feel like any of the answers below helped you out, go ahead and mark it with a check!
Answer: If you redeem your CD key / activation key before March 31st, you will get the pre-order bonuses.  A member of my online community bought the game digitally yesterday and got the wings without pre-ordering.
Technically if you went to your local retailer and bought a copy before March 31st you'll still get your pre-order bonuses.
TL;DR: Anyone who redeems their activation (retail or digital) key before the end of March will get their pre-order bonuses.
Additionally, if you pre-ordered a physical copy of the game but didn't receive it before March 31st, you can receive the pre-order items by submitting a ticket to Blizzard support.
Answer: In Germany we don't have Best Buy but I preorder my games at Gamestop. There you get an piece of paper with an one-time-use code inside the game's box or they hand it out when you come to get your game at the release date.
I think Best Buy would do it in the same way. I'm pretty sure the game will include an one-time-use code.
Comment: It's possible that the registration key includes data about your preorder but it's just a guess.
Comment: Now that the game is available for retail and preorders from third party sites have been honoured, has anyone actually received such a code? I pre-ordered a copy from GMG and got no such code apart from the registration key for the game that was in the box with the disc.
Comment: @Kurley, refer to my answer.  All codes redeemed before March 31st will get the pre-order items.
Comment: @Mkalafut I've upvoted your answer ;-)
Comment: @Kurley Thanks!  Hopefully he selects an answer at some point.


Timeout R package installation from Github

Question: I'm trying to install a package from github for R with devtools package.
But I'm encountering Timeout error from curl each time!

install_github('ramhiser/datamicroarray')

Error in curl::curl_fetch_disk(url, x$path, handle = handle) :
  Timeout was reached

Any Idea why this happens? Any help will be appreciated.
Comment: Are you use proxy ?
Comment: @Batanichek No! I don't.
Answer: When I want to download this package it also takes long to get a  connection but in the end it works as expected. Another possibility is to download the zip file and then install it.
To install the package after downloading, the following code works:
install.packages("/address/to/zip-package", repos = NULL, type="source")

and write the address of the downloaded package in place of /address/to/zip-package, or use RStudio and Packages -> Install.


Finding primes p such that $3x^2=2$ has no solution modulo p

Question: I am not sure how to do this. I know about Legendre symbols and reciprocity but how do I deal with the 3 coefficient?
Comment: Hint:  assuming $p>3$, $3$ is a square $\pmod p$ iff $3^{-1}$ is so your congruence has no solutions iff exactly one of $2,3$ is a square.
Answer: Hint
By the calculation with  the Legendre symbol, it has a solution if and only
$$\biggl(\dfrac2p\biggr)=\biggl(\dfrac3p\biggr)$$
By the second complementary law, $$\biggl(\dfrac2p\biggr)=\begin{cases}\phantom{-} 1 & \text{if }p\equiv1,7\mod8,\\
-1& \text{if }p\equiv3,5\mod8\end{cases}. $$
Next, the law of quadratic reciprocity asserts that
$$\biggl(\dfrac3p\biggr)=\begin{cases}\phantom{-}\biggl(\dfrac p3\biggr)& \text{if }p\equiv1\mod4,\\[1ex]
-\biggl(\dfrac p3\biggr)& \text{if }p\equiv3 \mod 4.\end{cases}$$
Last, the only non-zero square mod. $3$ is $1$.
From these relations, you should be able to find the pairs $(p\bmod 3,p\bmod 8)\in\mathbf Z/3\mathbf Z\times \mathbf Z/8\mathbf Z$ that solve the problem.
There will remain to deduce the corresponding values of $p\bmod24$ by the Chinese remainder theorem.


Transpose all rows in one column of dataframe to multiple columns based on certain conditions

Question: I would like to convert one column of data to multiple columns in dataframe based on certain values/conditions.
Please find the code to generate the input dataframe
df1 = pd.DataFrame({'VARIABLE':['studyid',1,'age_interview', 65,'Gender','1.Male',
                            '2.Female',
                            'Ethnicity','1.Chinese','2.Indian','3.Malay']})

The data looks like as shown below

Please note that I may not know the column names in advance. But it usually follows this format. What I have shown above is a sample data and real data might have around 600-700 columns and data arranged in this fashion
What I would like to do is convert values which start with non-digits(characters) as new columns in dataframe. It can be a new dataframe.
I attempted to write a for loop but failed to due to the below error. Can you please help me achieve this outcome.
for i in range(3,len(df1)):
#str(df1['VARIABLE'][i].contains('^\d'))
    if (df1['VARIABLE'][i].astype(str).contains('^\d') == True):

Through the above loop, I was trying to check whether first char is a digit, if yes, then retain it as a value (ex: 1,2,3 etc) and if it's a character (ex:gender, ethnicity etc), then create a new column. But guess this is an incorrect and lengthy approach
For example, in the above example, the columns would be studyid,age_interview,Gender,Ethnicity.
The final output would look like this

Can you please let me know if there is an elegant approach to do this?
Answer: Use itertools.groupby and then construct pd.DataFrame:
import pandas as pd
import itertools

l = ['studyid',1,'age_interview', 65,'Gender','1.Male',
                            '2.Female',
                            'Ethnicity','1.Chinese','2.Indian','3.Malay']
l = list(map(str, l))
grouped = [list(g) for k, g in itertools.groupby(l, key=lambda x:x[0].isnumeric())]
d = {k[0]: v for k,v in zip(grouped[::2],grouped[1::2])}

pd.DataFrame.from_dict(d, orient='index').T

Output:
     Gender studyid age_interview  Ethnicity
0    1.Male       1            65  1.Chinese
1  2.Female    None          None   2.Indian
2      None    None          None    3.Malay

Comment: Thanks a lot for response..I see that you have created a list. But in real time, I might have more than 600 columns and corresponding data for them.  So wondering whether I would be able to manually create this list at that time
Comment: @SELVA I guess you mean you have a dict with 600 keys and values? In such case, you can always iterate your dict. Do your columns share the columns names and thus need to be concatenated eventually?
Comment: My input file in real time would be like as shown above, an excel sheet with one column of data (VARIABLE Column). But then I have to process it to identify the column names (gender, ethnicity etc) and create them as new column and key in the value as shown in the " Expected Output" section
Answer: You can use groupby to do something like:
m=~df1['VARIABLE'].str[0].str.isdigit().fillna(True)
new_df=(pd.DataFrame(df1.groupby(m.cumsum()).VARIABLE.apply(list).
                                    values.tolist()).set_index(0).T)
print(new_df.rename_axis(None,axis=1))

  studyid age_interview    Gender  Ethnicity
1       1            65    1.Male  1.Chinese
2    None          None  2.Female   2.Indian
3    None          None      None    3.Malay

Explanation: m is a helper series which helps seperating the groups:
print(m.cumsum())
0     1
1     1
2     2
3     2
4     3
5     3
6     3
7     4
8     4
9     4
10    4

Then we group this helper series and apply list:
df1.groupby(m.cumsum()).VARIABLE.apply(list)
VARIABLE
1                                 [studyid, 1]
2                          [age_interview, 65]
3                   [Gender, 1.Male, 2.Female]
4    [Ethnicity, 1.Chinese, 2.Indian, 3.Malay]
Name: VARIABLE, dtype: object

At this point we have each group as a list with the column name as the first entry.
So we create a dataframe with this and set the first column as index and transpose to get our desired output.
Comment: can you please help me with this? https://stackoverflow.com/questions/56373708/replace-values-in-a-dataframe-with-values-from-another-dataframe-regex
Comment: q1) can you please help me understand what this line does "df1.groupby(m.cumsum()).VARIABLE.apply(list)". I understand that it groups the values together based on their cumsum value. The output of this line is a series datatype. Do we apply "df1.groupby(m.cumsum()).VARIABLE.apply(list).values.tolist())" to be able to convert it to dataframe.
Comment: Sure. No worries
Comment: @SELVA updated explanation. Thanks for your patience, yes since the lists are of different lengths, we do `.values.tolist()` so we can create a dataframe and keep missing values as None
Comment: can you please help me with this? https://stackoverflow.com/questions/56421236/select-rows-based-on-columns-which-doesnt-have-a-specific-value-and-make-use-of
Answer: col1=(~df1.VARIABLE.astype(str).str[0].str.isdigit()).cumsum()
def function1(dd1:pd.DataFrame):
    return dd1.reset_index(drop=1).T

df1.groupby(col1).apply(function1).set_index(0).T.fillna('')

:

┌───────┬─────────┬───────────────┬──────────┬───────────┐
│ index │ studyid │ age_interview │  Gender  │ Ethnicity │
│ int64 │ varchar │    varchar    │ varchar  │  varchar  │
├───────┼─────────┼───────────────┼──────────┼───────────┤
│     1 │ 1       │ 65            │ 1.Male   │ 1.Chinese │
│     2 │         │               │ 2.Female │ 2.Indian  │
│     3 │         │               │          │ 3.Malay   │
└───────┴─────────┴───────────────┴──────────┴───────────┘


How to set a magento widget form to enctype="multipart/form-data" for file upload?

Question: I am trying to make a widget for a gallery as all the modules I have seen don't really do what I am after and widgets seem like the way forward to allow the end user to have nice and easy control over placement.
So so far I have followed the Magento how to make a widget tutorial:
http://www.magentocommerce.com/knowledge-base/entry/tutorial-creating-a-magento-widget-part-2/
which has allowed me to set up the files I need and have things recognised in the back end.
Now I can add an image upload field through the code below but the file does not get uploaded, this is it seems due to enctype="multipart/form-data" not being set automatically when I add a file field.
So I looked about and it seems you can add a helper block for the widget form
local/WebsiteDevelopment/GalleryWidget/etc/Widget.xml
<?xml version="1.0"?>
<widgets>
    <WebsiteDevelopment_GalleryWidget type="widgets/list" translate="name description" module="GalleryWidget">
        <name>Banner Gallery</name>
        <description>Adds a full page width gallery</description>
        <parameters>
            <enabled_services>
                Enabled Services
                <visible>1</visible>
                <required>1</required>
                <type>multiselect</type>
                <source_model>WebsiteDevelopment_GalleryWidget_Model_Services</source_model>
            </enabled_services>
            <helper_block>
                <type>WebsiteDevelopment/GalleryWidget_Adminhtml_Edit_Form</type>
            </helper_block>
            <template translate="label">
                Frontend Template
                <visible>1</visible>
                <required>1</required>
                <type>select</type>
                <values>
                    <text translate="label">
                        <value>GalleryWidget/view.phtml</value>
                        Text Links
                    </text>
                </values>
            </template>
            <image>
                Image One
                <description>The first image for the banner</description>
                <visible>1</visible>
                <type>image</type>
            </image>
        </parameters>
    </WebsiteDevelopment_GalleryWidget>
</widgets>

so after i add my helper block into the params section of the xml above i create my helper at WebsiteDevelopment/GalleryWidget/Block/Adminhtml/Edit/Form.php (which i think is where it should be, i am still unsure whether a block has to be in a specific structure like this for use in the backend ) and then add the following code
WebsiteDevelopment/GalleryWidget/Block/Adminhtml/Edit/Form.php
<?php
class WebsiteDevelopment_GalleryWidget_Block_Adminhtml_Edit_Form extends Mage_Adminhtml_Block_Widget_Form
{
    protected function _prepareForm()
    {
        $form = new Varien_Data_Form(array(
            'id' => 'edit_form',
            'enctype' => 'multipart/form-data'
        ));

        $form->setUseContainer(true);
        $this->setForm($form);
        return parent::_prepareForm();
    }
}

obviously the form will need some more attributes to work fully but I was just hoping to get some different attributes on to the form so I could make sure the block was being applied.
So at the moment when I go into the back end the form with the helper on it has no enctype still, and I am unsure if my helper block is even being loaded or whether it is and its just having no effect.
Am I going about this in the correct manner or not?
Comment: If you are trying to create a image gallery that has albums and is spread across multiple pages then I would not use a widget. I would only use a widget if you just wanted to sisplay multiple images on 1 page that is formatted nicely.

I would create a custom module that has a database table to store the data and has controllers to allow moving through the gallery. I did this for a client and mimic-ed the Admin interface for categories to allow creating albums and images.
Answer: The form should be initialized like this:
protected function _prepareForm()
{
    $form = new Varien_Data_Form(array(
                                  'id' => 'edit_form',
                                  'action' => $this->getUrl('*/*/save', array('id' => $this->getRequest()->getParam('id'),'store' => $this->getRequest()->getParam('store'))),
                                  'method' => 'post',
                                  'enctype' => 'multipart/form-data'
                               ));
    $form->setUseContainer(true);
    $this->setForm($form);
    return parent::_prepareForm();
}


find number of rows without using count() in mysql

Question: Can anybody help me to find way to count number of rows found while running query. I want to run this query in stored procedure depending on the count i want to perform certain actions.
I was trying to set variable value something like.
 Select abc_master_id,
        abc_name,
        abc_parent_id,
       (@row := @row +1)  rownum
 from abc_master
 where blah..  blah.. limit 18,9

Above query is completely wrong. But here I want to count or set some flag that records found are less than or equal to limit set to query i.e here 9. By doing this i will save one query for counting rows fetched by query.
I have tried using SQL_CALC_FOUND_ROWS and Found_rows() but it gives me total number of rows if query run without limit.
Answer: The solution:
SELECT abc_master_id,
       abc_name,
       abc_parent_id,
       @i:=@i+1 AS rownum
FROM abc_master ,(SELECT @i:=0) foo
where blah.. blah.. limit 18,9

Answer: Replace your query with a similar one
Select count(*)
from abc_master where blah.. blah..

and fetch the first row.
Mysql has improved over the years but I don't know if your engine supports the much simpler subquery:
select count(*) from (
Select abc_master_id, abc_name, abc_parent_id ... from abc_master
where blah.. blah..)

Thus: your original query but without the limit clause, between parens.


How to find constructors of a datatype?

Question: I'm tring to define the following functions by analogy with this one:
fun int_divide :: "int option ⇒ int option ⇒ real option" where
  "int_divide _ (Some (int 0)) = None"
| "int_divide (Some a) (Some b) = Some (a / b)"
| "int_divide _ _ = None"

fun real_divide :: "real option ⇒ real option ⇒ real option" where
  "real_divide _ (Some (real 0)) = None"
| "real_divide (Some a) (Some b) = Some (a / b)"
| "real_divide _ _ = None"

But these types doesn't have int or real constructors. int and real types are defined as a quotient_type. And I can't find something that looks like a constructor in their theories.
The following definition doesn't work:
definition int0 :: "int" where
  "int0 = Abs_Integ (0,0)"

fun int_divide :: "int option ⇒ int option ⇒ real option" where
  "int_divide _ (Some int0) = None"
| "int_divide (Some a) (Some b) = Some (a / b)"
| "int_divide _ _ = None"

How to find all constructors for a type? Or at least for a quotient_type? Or how to define required constructors?
Answer: Not every type is built from free constructors. Sets 'a set and reals real are not. One could of course show an isomorphism and declare this as a constructor, say between sets 'a set and predicates 'a => bool, but this will not be useful for defining functions and proving.
You can look up the registered constructors for a type using an ML block. For example, the following shows the constructors for nat.
ML ‹Ctr_Sugar.ctr_sugar_of @{context} @{type_name nat} |> Option.map #ctrs›

User-defined constructors can be registered using free_constructors, which is documented in the tutorial on (co)datatype definitions (available from the documentation panel).
This having been said, I do not believe that there is much point in trying to define free constructors for various number types because you would also have to prove lemmas about how all the operations on the numbers behave w.r.t. to these new constructors. This is a lot of work. It is probably easier to just use conditionals instead of pattern-matching, say
fun int_divide :: "int option ⇒ int option ⇒ real option" where
  "int_divide (Some a) (Some b) = (if b = 0 then None else Some (a / b))"
| "int_divide _ _ = None"

Another suggestion would be to avoid all the options in the arguments by using the option monad and the function Option.bind for sequencing.
Answer: Adding to Andreas's answer, type definitions in Isabelle/HOL are always modulo some underlying base type. E.g. integers are defined as a quotient of pairs of natural numbers.
The typical way of defining functions on such types initially is either directly via the morphisms you get from the type definition, which convert between the underlying base type and the new type (usually something like Abs_mytype and Rep_mytype) or through lift_definition, which allows you to directly lift a function from the base type to the new type.
However, for library types like int and real, that is not advisable. You should not peek into the internal representation of these types but rather just use them abstractly, like you would in 'normal' pen-and-paper mathematics as well.

How to find constructors of a datatype?


mysql - Long query execute time locks table

Question: I have a mysql database which collects data from all kinds of resources.
In order to show some statistics from different tables, I run a long query which takes about a couple of minutes to execute.
The query locks some tables and therefore I can't write to these tables.
The tables are InnoDB engine.  I tried several options including:
1. Increasing the lock timeout
2. Adding SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; and COMMIT; (link)
3. Adding indexes to the tables (made the query run faster, but I still get a lock timeout error)
How can I execute the long query without locking the tables?
Comment: and what is the query?
Comment: It's a bunch of SELECT's, JOIN's, SUM's and more...
Comment: Are you sure there's a lock? Please `SHOW PROCESSLIST` and `SHOW ENGINE INNODB STATUS`. Selects do not lock anything. But they might *be waiting* for locks to be released
Comment: try running the set of query's that updates the table in a different transactions than the one that just retrive's them
Comment: Did you ever resolve this issue?
Answer: From the comments in Any way to select without causing locking in MySQL? :

Setting "set session transaction isolation level read committed;" did not help.
Setting "set session transaction isolation level read uncommitted;" did not help.
Using lock tables on either side did not help.
Setting innodb_locks_unsafe_for_binlog=1 in my.cnf fixes the problem, but I guess the downside is that now I will not be able to use replication in this database.

If you don't need replication, then I would try that.
Comment: no idea if this will work.  I've never had an issue with locking, and I tend to stay out of my.cnf as much as possible.  Good luck!


Inserting an image to a particular position in a word document using docx4j

Question: I want to add an image to particular position in my  word document using docx4j. I don't want inline insertion. The code below performs adding the image inline with text. But I want floating insertion where I can explicitly give the location of where the image should be placed in the page. Please help me.
<code>    public R addUserPic(P parag, WordprocessingMLPackage wordMLPackage)
                throws Exception {

            File file = new File("src/main/resources/PictureNew.png");
            byte[] bytes = convertImageToByteArray(file);
            BinaryPartAbstractImage imagePart = BinaryPartAbstractImage
                    .createImagePart(wordMLPackage, bytes);
            int docPrId = 1;
            int cNvPrId = 2;

            Inline inline = imagePart.createImageInline("Filename hint",
                    "Alternative text", docPrId, cNvPrId, false);

            ObjectFactory factory = new ObjectFactory();
            R run = factory.createR();
            org.docx4j.wml.Drawing drawing = factory.createDrawing();
            run.getContent().add(drawing);
            drawing.getAnchorOrInline().add(inline);

            return run;

        }

        private static byte[] convertImageToByteArray(File file)
                throws FileNotFoundException, IOException {
            InputStream is = new FileInputStream(file);
            long length = file.length();

            if (length > Integer.MAX_VALUE) {
                System.out.println("File too large!!");
            }
            byte[] bytes = new byte[(int) length];
            int offset = 0;
            int numRead = 0;
            while (offset < bytes.length
                    && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
                offset += numRead;
            }

            if (offset < bytes.length) {
                System.out.println("Could not completely read file "
                        + file.getName());
            }
            is.close();
            return bytes;

}
</code>
Comment: How have you attempted to do this in docx4?
Comment: yes.. i have tried it in inline way.. but i want to place the image in any given position in the document
Comment: I asked how not what. The subtle difference is that the latter was already answered in your question and the former requests the code you have written so far to get an understanding of what you may be doing wrong or how you may be incorrectly approaching the problem. It also expects that you have done some work of your own on the problem and didn't just come here asking for some canned code to paste into your project.
Answer: The thread you have cross posted in, at http://www.docx4java.org/forums/docx-java-f6/how-to-create-a-floating-image-t1224.html answers your question.


Beginning Hour: What are the minimum requirements to get the true ending?

Question: This question relates to the Resident Evil 7 demo, which is subtitled "Beginning Hour".
There are a number of different endings to this demo, and I don't know how many different ones there are, but my question is: What are the minimum requirements for achieving the true/best ending?
I guess I am looking for the shortest list of steps that will result in the true ending.
Answer: So after a fair bit of searching I have found this guide. The guide is actually for obtaining the 'dirty coin' but it also happens to result in the 'true ending'. Using this guide I have managed to work out the minimum steps in takes to get the true ending:

Pull the hidden level in the fireplace to open the secret door
Enter the secret door and grab the fuse on the stool
Put the fuse in the fusebox (in the room where you start)
Go upstairs, activate the attic stairs, go up to the main room in he attic and grab the basement key next to the bed
Go to the basement to get the attic window key, at this point a Molded will spawn and you MUST get out of the basement without taking any damage
Return to the attic and escape out of the window (up the ladders) using the key

Essentially, you just need to escape without taking any damage and you will get the true ending.

TIP for step 5:

Grab the key then immediately run past the Molded (sometimes it will hit you, sometimes it will miss)
Immediately try to open the door to get the animation started
Turn around and get into a position where the hanging body bag is between you and the Molded. Kick it into the Molded so it gets knocked to the floor
Run to the door and keep trying it until you get through - you should get enough time before the Molded gets back up and attacks you.

It may take a few attempts to pull this off, but it is very doable once you get the hang of it.
Comment: A second strategy (and iirc the way the game expects you to play) is to grab the valve, leave the room, get the gun from the bathroom, and when you return, shoot the Molded to stun it before grabbing the key.  Any time you return to the basement, the Molded does the "drop into the first room" bit like he does if you'd tried to open the basement door the first time.
Comment: On a side note: Where the molded spawns depends on what you do in the basement.  If you try to go for the key first, it will break the shelves and come through.  If you try to open the door first, it will fall onto the floor of the first room instead.


Show facebook like & twitter follow buttons on hover

Question: I'm trying to replicate the social media icons for my site similar to Hypebeast (http://hypebeast.com) whereby the Facebook like button and twitter follow buttons only show when you hover over the respective icons (see the example in the top right of the page).
As a starting point current code for my social icons is as follows:

And the CSS for the facebook iframe is:
#header li.facebook iframe.facebook-like {
position: absolute;
top: -30px;
left: -27px;
display: none;
}

#header li.facebook iframe.facebook-like:hover {
display: block;
}

I am not very experienced with coding (self-taught and a lot of mine is trial and error) Is there anyway someone can explain or provide code for this to work in http://jsfiddle.net/
I can force the like button to show if I force element state of the iframe to :hover but not if I hover the mouse over the icon or list item area at all?
Thanks in advance for your help.
EDIT: Everything seems to be positioned correctly but I'm having trouble loading the javascript to toggle the display state on hover.
I have saved the following in social-popup.js in my child theme directory folder
$(document).ready(function($) {
// Your jQuery code goes here. Use $ as normal.
   $(".facebook").hover(function(){$('.facebook-like').toggle();});
$(".twitter").hover(function(){$('.twitter-follow').toggle();});
});

Then I have added this to the functions.php file in the child directory:
function wpb_adding_scripts() {
wp_register_script('my_amazing_script', get_template_directory_uri() . '/social-popup.js', array('jquery'),'1.1', true);
wp_enqueue_script('my_amazing_script');
}
add_action( 'wp_enqueue_scripts', 'wpb_adding_scripts' );

Everything else seems to be working fine & positioned correctly apart from the Javascript
Answer: Hide the facebook like iframe initially:
.facebook-like{
    display:none;
}

Then use jQuery's .hover function combined with .toggle to toggle the iframe on hover:
$(".facebook").hover(function(){$('.facebook-like').toggle()})

EDIT: Updated the JSFiddle

JSFiddle:
http://jsfiddle.net/s9ts65f6/3/
Comment: Thanks Jim! How would you go about doing this for the twitter Follow button as well? Would the code be the same?
Comment: Do I add the jQuery to the functions table in wordpress?
Comment: Please check out the updated JSFiddle to see how twitter would work.  It looks like you had some issues with your html also.  If you're trying to use font-awesome, the correct class name is "fa fa-facebook".  You just had "fa-facebook".  Also you had two "i" tags..not sure why.

As far as including jQuery in wordpress, I am not sure how to do that, you can check this link out:
http://matthewruddy.com/using-jquery-with-wordpress/
Comment: Thanks again Jim. All the elements seem to be there but I'm having great difficulty including the correct javascript to toggle the hover/ display state. I've edited the code above to show you what I mean.
Comment: Try changing $(document).ready(function($) to jQuery(document).ready(function($)
Comment: Hi Jim, Unfortunately that didn't seem to work either? Any ideas?
Comment: Honestly I don't know..it seems like an issue getting the jQuery to work in wordpress but I've never used wordpress so I wouldn't be much help there.


Run Shell Script after click on button - YAD

Question: I have three shell scripts and I would like to run each script after click on button in yad - lets say - I have one yad session with three buttons - if I click on one button I will open 1. script - second button open 2. script and so on.. See my example bellow -
#!/bin/bash
files=$(yad --width 100 --height 100 --title "Choose the Shell Script" \
    --text="  Please enter analysis details:" \
    --button="ShellScript1:2" \
    --button="ShellScript2:3" \
    --button="ShellScript3:3" \
    --button="Cancel:1" \
    --on-top \
    --center \
)

ret=$?
[[ $ret -eq 1 ]] && exit 0

Thank you for any idea or help.
Answer: I just add condition:
ret=$?

[[ $ret -eq 1 ]] && exit 0

if [[ $ret -eq 2 ]]; then

      /path/to/shell/1.sh
fi

if [[ $ret -eq 3 ]]; then

    /path/to/shell/2.sh

fi

Comment: To write a good answer, please add some explanations about what you changed and why.
Answer: Alternatives:
1. You could use case instead of if like this:
case $ret in
    1) /path/to/script1 ;;
    2) /path/to/script2 ;;
    3) /path/to/script3 ;;
esac

You could alternativelly call the scripts directly from each button, without the need to manipulate the $? return code using this synthax:
--button="ShellScript1:bash /path/to/script1.sh"

In my similar script with yad list this works fine:
yad --list --width=800 --height=600 --center \
    --button="Display":"/home/gg/Tests/yadabout.sh" --button="Cancel":0  \
    --column "ID" --column "File" \
    --column "Exec" "${list[@]}")

Difference:
When you assign an exit code/id to each button, after a button press yad returns it's value to the variable (files in your code) and the yad dialog exits.
If instead a button id you assign a command to run (case 2 above) then yad dialog remains on screen and does not exit.
But in this mode there is not a yad return value , and thus you can not parse the selection from the yad dialog to this external command/script (not 100% sure, but i have not found any way to do it yet).
Comment: Thank you so much George for your help and helpful advice.
Answer: To elaborate on the previous response:
processes=$(yad --width 100 --height 100 --title "Chose Process" --text="Select" --button="Run Cmd":1 --on-top --center)
ret=$?
if [[ $ret -eq 1 ]]; then
  /path/process.sh
fi


ie7 and ie8 Unable to get value of the property

Question: I am trying to build a table using jQuery Datatables. Everything works on all browsers except ie7 and ie8.
Here is the error:
SCRIPT5007: Unable to get value of the property 'sName': object is null or undefined

Here is the JS code:
var jsonData = [];

for (var i = 0; i < docs.length; i++) {
   var obj = docs[i];

   var row = [];

   row.push('<input type="checkbox" class="article_checkbox" />');

   for (var j = 1; j < columns.length; j++) {

       var value = obj[columns[j].sName];
       console.log(value);
       row.push(value);
   }

   jsonData.push(row);
};

My only thought is that the JSON response had a loose comma somewhere but I ran it through jsonlint and it came back valid.
Any ideas on this nasty lil' thing?
Thanks!
Comment: Use console.log on columns[j]
Comment: Hi @cwallenpoole,
Thanks for your response. Here is what is returned in the console.
(A shortened version due to character limit in comments here)

Object { sName="hasAlikeDocuments", bVisible=false}
Object { sTitle="Date", sName="createDateDisplay"}
Object { sTitle="Source", sName="sourceName"}
Object { sTitle="Articles", sClass="dt_title", sName="title"}
Object { sTitle="Quick Tools", sClass="dt_tools"}
Object { sName="isArchived", bVisible=false}
Object { sName="isTranslatable", bVisible=false}
Answer: I had a similar problem and the issue was that I had an additional , in the end of my array.
Comment: Many thanks! I had a similar problem and spent the whole morning trying to figure it out. I would never have suspected the comma at the end of the list.
Answer: All of the sName definitions had to be wrapped in double quotes : )


Confused about a proof on co-meager sets

Question: Let  $X$ be a completely metrizable space and let $A\subset X$ be a co-meager subset.
Since $X$ is Baire, we know that there is some dense $G_\delta$ set contained in $A$, say $G\subset A$.
But since $X$ is complete and $G$ is $G_\delta$, then $G$ is complete. Hence, as a complete subspace of another complete subspace, $G$ is closed.
But since $G$ is dense, $G=X$ which implies that $A=X$.
So we conclude that any co-meager subset of a completely metrizable space, has to be the space itself. This is not true but I can't see where I made a mistake.
Can somebody help me?
Thanks
Answer: Your mistake is "since $X$ is complete and $G$ is $G_\delta$, then $G$ is complete, hence . . . $G$ is closed." Nope. $\mathbb R$ is a complete metric space, and $(0,1)$ being an open set is a $G_\delta,$ but $(0,1)$ is not closed in $\mathbb R.$ You see, $(0,1)$ is completely metrizABLE (being homeomorphic to $\mathbb R$), but it is not complete with respect to the usual metric of $\mathbb R.$ A $G_\delta$ subset $G$ of a complete metric space $X$ is completely metrizable, there is a complete metric on $G$ which induces the topology which $G$ inherits as a subspace of $X,$ but in general it's not the same as the metric in $X.$ It can't be, unless $G$ happens to be closed in $X.$
Comment: Thanks to you it is now very clear the silly (but for me, subtle) mistake I made in my reasoning.


how to calculate the second to ninth root of a number

Question: I'm a CS student and i got this question in my C++ assignment and i don't understand the math behind it.
the question is:

For a natural number m we define its n-th root to be the natural number k that exists That-n k is closer to m than any nth power of any other natural number 'k.

for example:
A. What is the tenth root of a hundred?
In other words: what is the number x so that: 10 near x to a hundred more than any other number to the power of ten?
The answer: 1.
B. What is the third root of a hundred? What is the number whose third power is close to one hundred More than any other number in the third?
The answer: 5.

Write a program that reads a natural number. The plan must present its second to ninth roots of the number.
I didn't understand how they say they define the nth root of a number and the examples provided didn't help me understand it.
hope that someone has an idea so i understand what the program I'm coding is supposed to do.
Comment: "That-n k is closer to m than any nth power of any other natural number 'k" does not make sense
Answer: Obviously, this is not the standard definition of the $n$th root in mathematics, so I will not use the $\sqrt[n]{\cdot}\ $ notation.
Lets say we want to compute the $3$rd root of $100$. We need to find the integer $x$ such that for all other integers $y$, we have that $x^3$ is closer to $100$ than $y^3$. "Closer" here, I believe, means the distance in terms of the absolute value of the difference of the two numbers.
If we make a list:
\begin{align}
1^3 &= 1  & |100-1| &= 99\\
2^3 &= 8  & |100-8| &= 92\\
3^3 &= 27 & |100-27| &= 73\\
4^3 &= 64 & |100-64| &= 36 \\
5^3 &= 125& |100-125| &= 25\\
6^3 &= 216& |100-216| &= 116
\end{align}
Since $5^3$ is closer to $100$ than any other, $5$ is the $3$rd root of $100$.
Answer: The English and mathematics in the question as quoted is close to nonsense, but I think I know what the author meant to say.

The $n$th root of $m$ is the integer $k$ that minimizes $$ | k^n - m
 |. $$

So to find the $3$d root of $100$ you look at the sequence of cubes
$$
1, 8 = 2^3, 27 = 3^3, 64 =4^3, 125 = 5^3
$$
The closest cube to $100$ is $5^3 = 125$ so this "cube root of $100$" is $5$.
(Building that sequence is probably not the best way to calculate the answer in a program.)
Answer: In math we define the $n^{th}$ root of $k$ to be the number that when multiplied by itself $n$ times results in $k$.  We write this $m=\sqrt[n]k$.  For many $n,k$ pairs this will not be an integer, it will be an irrational number.  For your example $\sqrt[10]{100} \approx 1.58489$  They want the result to be an integer, so they define it to be so with a particular rounding.  You are expected to find that $1^{10}=1, 2^{10}=1024,$ that $1$ is closer to $100$ than $1024$ is, and return $1$.  For the second example, $4^3=64, 5^3=125$ so you return $5$.


Hiding the next to next child element using jquery

Question: Say I have the below HTML

   //hide this one

    ...

How can I hide the second div .$('#target').children().hide(); will hide starting the first .
Thanks
Answer: I guess you want:
$('#target div div').hide();

Select the div inside the div inside #target.
Comment: I think as a general rule it is best to get as close as possible to the desired element using selectors
Comment: It just depends on the use case and what you know in advance. More general solutions exist that compute the children of `#target`, but why have the computer figure it out if you already know it?
Answer: And if you need to do this with css
#target > div div:first-child {display:none;}

jsfiddle


What's the ratio $\displaystyle \frac{e^{2(\theta+\phi)}-1}{e^{2\theta}+e^{2\phi}}$ equal to?

Question: I'm asked what the ratio $\displaystyle \frac{e^{2(\theta+\phi)}-1}{e^{2\theta}+e^{2\phi}}$ is equal to.
The answer I'm given is $\displaystyle \frac{\sinh(\theta+\phi)}{\cosh(\theta-\phi)}$. I could work backwards from this, but how do I show it's equal to this directly?
Comment: Every time I see something like $e^{2x}\pm 1$ I wanna divide by $e^{x}$ to give it a "usual" form.
Answer: Diving the N & D  by $e^{x+y}$ $$\dfrac{e^{2(x+y)}-1}{e^{2x}+e^{2y}}=\dfrac{e^{x+y}-e^{-(x+y)}}{e^{x-y}+e^{-(x-y)}}$$
Now use $e^A=\cosh A+\sinh A $


Is this a valid query? (Repetition of Aliases)

Question: I am trying to create nested join statements and use alias for programming purposes. Let me give you a list of tables I'm trying to join and their foreign keys.
TABLE1: id (Foreign key)
TABLE2: id (primary key), idx (foreign key)
TABLE3: id (primary key), idx (primary key)
TABLE4: id (primary key), idx (primary key)`

SELECT *
FROM (((TABLE1 JOIN
        TABLE2
        ON TABLE1.id = TABLE2.id
       ) AS NEW_TABLE JOIN
       TABLE3
       ON NEW_TABLE.id = TABLE3.id AND NEW_TABLE.idx = TABLE3.idx
      ) AS NEW_TABLE JOIN
      TABLE4
      ON NEW_TABLE.id = TABLE4.id AND
         NEW_TABLE.idx = TABLE4.idx
     );

Can you let me know if this is a valid query and using aliases this way works?
Comment: Do you have a particular DBMS you are using?
Answer: I don't think so.  I would write this as:
SELECT *
FROM TABLE1 JOIN
     TABLE2
     ON TABLE1.id = TABLE2.id JOIN
     TABLE3
     ON TABLE1.id = TABLE3.id AND TABLE2.idx = TABLE3.idx
     TABLE4
     ON TABLE1.id = TABLE4.id AND
        TABLE2.idx = TABLE4.idx;

(Well, actually, I would use table aliases but this is the idea.)
The parentheses do not do anything for you.  I also think re-using the NEW_TABLE alias is likely to generate an error.
Answer: you probably need to nest complete queries:
SELECT * FROM
  (SELECT * FROM
    (SELECT * FROM TABLE1 JOIN TABLE2 ON TABLE1.id = TABLE2.id ) A
    JOIN TABLE3 ON A.id = TABLE3.id AND A.idx = TABLE3.idx) B
  JOIN TABLE4 ON B.id = TABLE4.id AND B.idx = TABLE4.idx;

although, without knowing the contents of the tables it's hard to say what kind of results you might get or whether your query is even valid.
Answer: Format like below..
SELECT * FROM
  TABLE1
     JOIN TABLE2 ON TABLE1.id = TABLE2.id
     JOIN TABLE3 ON Table1.id = TABLE3.id
        AND Table2.idx = TABLE3.idx
   JOIN TABLE4 ON Table3.id = TABLE4.id
      AND Table3.idx = TABLE4.idx


XML returning too many rows

Question: From the below query I am returning 7 rows when I expect to only get two.
What am I doing wrong?
 go
    declare @xml xml =
    '<people>
      <person ID="18" DOB="03 Apr 1955">
        <name>
          <FirstName>Walter</FirstName>
          <LastName>Thrip</LastName>
        </name>
        <Sex>M</Sex>
         <Sex>X</Sex>
        <title>Sir</title>
      </person>
      <person ID="19" DOB="01 Jan 2010">
        <name>
          <FirstName>john</FirstName>
          <LastName>smith</LastName>
        </name>
        <Sex>m</Sex>
        <DOD>20 Jan 2014</DOD>
      </person>
    </people>'
    select
          n.value('../@ID','int') as ID
          ,n.value('@DOB','datetime') as DOB
          ,n.value('FirstName[1]','varchar(20)') as FirstName
          ,n.value('LastName[1]','varchar(20)') as LastName
          ,n.value('../Sex[1]', 'char(1)') as Sex
          ,n.value('../DOD[1]', 'datetime') as DOD
          ,n.value('../Title[1]', 'varchar(10)') as Title
    from @xml.nodes('(/people/person/*)') as a(n)

Answer: That's because you shred the XML on child of person level and there are 7 even them. You should shred on person element instead :
select
      n.value('@ID','int') as ID
      ,n.value('@DOB','datetime') as DOB
      ,n.value('(name/FirstName)[1]','varchar(20)') as FirstName
      ,n.value('(name/LastName)[1]','varchar(20)') as LastName
      ,n.value('Sex[1]', 'char(1)') as Sex
      ,n.value('DOD[1]', 'datetime') as DOD
      ,n.value('Title[1]', 'varchar(10)') as Title
from @xml.nodes('/people/person') as a(n)

rextester demo

XML returning too many rows


2nd monitor not recognized on boot after upgrade to Xubuntu 14.10

Question: I'm running Xubuntu 14.10 on a old MacBook Pro with a VGA monitor as second display. The displays were set up with xrandr in autostart as following:
<code>/usr/bin/xrandr --output VIRTUAL1 --off --output DP1 --off --output LVDS-1 --mode 1440x900 --pos 1920x180 --rotate normal --output HDMI1 --off --output DP-2 --mode 1920x1080 --pos 0x0 --rotate normal --output VGA1 --off
</code>
It worked fine in 13.04, but after upgrading the 2nd monitor only works until I login, where it shows the login  mask mirrored from the primary display. Then after login it goes into standby, Xubuntu basically no longer sees it in the config from then on.
At the moment I plug the VGA in/out and run my xrandr script again and it works, but this is rather cumbersome.
It's a GT216M GeForce GT 330M and I'm using X.Org driver.
Any advice where my setup could be wrong?
Answer: Having the monitor in standby and not off before pushing the Mac's power button solved the issue.


Action listener return value is not getting updated into input text value

Question: i called a method from action listener which returns string and i am planning to update it in inputtext field, when i am trying to this i am not getting value into input field
i tried using process ="@this" which perfectly excecute action and do not update the field if i remove that even action is not performing
//here is my backing bean
public String getNameWithFormID(long id) {
        TMapper tMapper = new TDao();
         map= new HashMap<>();
            List<TBean> tList = tMapper.getDistinctTName();

            for(TBean t1:tList) {
                map.put(t1.getID(), t1.getName());
            }
        System.out.println("id is"+id+"this is map in submit"+map);
        System.out.println("this is value of id"+map.get(id));
        return  map.get(id);
    }

// this is my jsf code

            FORM_NAME

                     output is <h:outputText value = "#{tBean.Name}"/>

Answer: In JSF ajax update means whatever ID/IDs are mentioned in update, we need to re render those components. It's does not means assigning those values. If you want that value to get bind with inputText, assign the value to backing bean variable which is bind with inputText. So after that when you call pass that inputText component to get updated, it will show latest values. Update your backing bean method as
public void getNameWithFormID(long id) {

        TMapper tMapper = new TDao();
         map= new HashMap<>();
            List<TBean> tList = tMapper.getDistinctTName();

            for(TBean t1:tList) {
                map.put(t1.getID(), t1.getName());
            }
        System.out.println("id is"+id+"this is map in submit"+map);
        System.out.println("this is value of id"+map.get(id));
        this.formName = map.get(id); // Change is here (assuming that formName is class level variable, as directly bind to backing bean.
    }

Comment: Great, I think you can accept and upvote the answer than. ;)
Comment: Thanks for the feedback! Votes cast by those with less than 15 reputation are recorded, but do not change the publicly displayed post score.
Comment: getting this response


ubuntu 16.04 `unable to mount location`

Question: I've recently installed ubuntu 16.04. Before installation, I've made a backup of my data (previous system was ubuntu 14.04). After installation I wanted to copy back my files, but I'm unable to access it. The disc doesn't appears in the files (on the left bar) under unity. Under mate I can see it, but if I try to open it, there is message unable to mount location.
sudo fdisk -l output is:
Disk /dev/sda: 298,1 GiB, 320072933376 bytes, 625142448 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 4096 bytes
I/O size (minimum/optimal): 4096 bytes / 4096 bytes
Disklabel type: dos
Disk identifier: 0x924cef05

Device     Boot     Start       End   Sectors   Size Id Type
/dev/sda1  *         2048 617050111 617048064 294,2G 83 Linux
/dev/sda2       617052158 625141759   8089602   3,9G  5 Extended
/dev/sda5       617052160 625141759   8089600   3,9G 82 Linux swap / Solaris

Partition 2 does not start on physical sector boundary.

Disk /dev/sdb: 298,1 GiB, 320072933376 bytes, 625142448 sectors
Units: sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disklabel type: dos
Disk identifier: 0x000e1e9b

Device     Boot Start       End   Sectors   Size Id Type
/dev/sdb1        2048 625141759 625139712 298,1G 83 Linux
maria@maria-Vostro-3360:/media$ sudo mount -t ntfs /dev/sdb1 /media/external

I've created mounting point in /media named external
I've run sudo mount /dev/sdb1 /media/external
The output is:
 mount: wrong fs type, bad option, bad superblock on /dev/sdb1,
        missing codepage or helper program, or other error

      In some cases useful info is found in syslog - try
      dmesg | tail or so.

I've tried mount -t ext4 /dev/sdb1 /media/external
Output:
mount: special device /dev/sdb1 does not exist
maria@maria-Vostro-3360:/media$

Is there other way I should try to access the data?
UPDATE
I was trying to see the disc in GParted. This shows unknown file system and under the details there is following:

Does it mean that my disc suddenly got broken?
UPDATE 3
Disk /dev/sdb - 320 GB / 298 GiB - CHS 38913 255 63
     Partition               Start        End    Size in sectors
 D Linux                    0  32 33 38913  70  5  625139712
 D Linux                 1215 170 44 38913  70  5  605612032
 D Linux                 1490 100 19 38913  70  5  601198592
 D Linux                19611 118 28 25015 239 56   86822912

UPDATE
Since it seems that the problem is not mounting but damaged filesystem, I've asked new question regarding data recovery: Data recovery - damaged filesystem.
Answer: You have two problems.
Problem #1
On your /dev/sda hard disk, partition sda2/sda5 is not properly aligned. This is a relatively easy fix, because it's your swap partition.

1. In gparted, you can select sda5 and issue a swapoff command
2. then delete sda5, then delete sda2
3. then recreate a fresh primary (not extended) swap partition, select the new partition, and issue a swapon command.
4. in terminal, type `sudo blkid` and note the UUID of the new swap partition.
5. still in terminal, edit your `/etc/fstab` with `gksudo gedit /etc/fstab` and find the line that contains the word "swap", and change the UUID to the new UUID. Save the file and quit gedit.
6. reboot the system, and in terminal, issue a `swapon` command to confirm that your new swap partition is working properly.

Problem #2
You need to recover your sdb1 partition, by changing it from unknown to EXT4. It's best to use testdisk.

1. in terminal, type `sudo apt-get update`
2. in terminal, type `sudo apt-get install testdisk`
3. in terminal, type `sudo testdisk`

You can learn more about the testdisk partition recovery by visiting http://www.cgsecurity.org/wiki/TestDisk_Step_By_Step.
Comment: I don't have a lot of testdisk experience yet. Maybe somebody else will chime in here. You could try setting any one of the first 3 partitions as EXT4, and assume that the other 2 are false, and if it gives you immediate feedback, then great, but once you write out a new partition table, any chance to recover later using testdisk will probably be gone. I just don't know. If you have the data backed up, then it's a no-brainer, wipe the disk and restore from backups. Please do let me know how you make out. Cheers, Al
Comment: You might post another question with "Need help with testdisk" and put the results of your updates 1- 3 in there, and see if somebody with more testdisk experience can help. Cheers, Al
Comment: I've tried your solution. I've installed testdisk and run it. Durring the deep search it stopped on 58%, finding an error. `Analyse cylinder 22785/38912: 58%
Read error at 22784/254/63 (lba=366041024)`. Since some time nothing happens.
Comment: Maria, did you already fix problem #1 using my guide? Problem #2 sounds like it's possibly a bad hard disk. Did you only have the one partition on it? Do you remember? Was it NTFS or EXT4 formatted? If you don't do a deep search, was it able to locate your existing partition and give you a chance to change it to NTFS or EXT4? If you can flip it, then mount the drive and backup whatever data you can. Let me know. Cheers, Al
Comment: I've run testdisk. I'm not sure about the choices I should do (partition type for exemple). The disk was formatted to ext4 if I remember well, I didn't make the partitions, I don't know if it should be one partition or not partitioned. The result of deep search is in UPDATE 3. Every of the partition listed seems damaged - choosing one of them and `p` - each time the result was `empty, file system might be damaged`...
Comment: I'm sorry, by mistake I've added the update to your answer instead of my question... I'm not able to remove it (or I don't know how).
Comment: p.s. First problem is solved :)
Comment: Maria, I looked at your update 3, and it's very confusing to me. The first 3 partitions all end at the same spot. Hum.  I also admit that my expertise runs out on this subject. You may just have to reinitialize the disk and start over. Cheers, Al
Comment: It means you think I've lost my data saved on the disk?
Comment: this was the backup... I've put my data on the external disk before system reistallation. When I wanted to copy it back on the computer, I couldn't... That's why it's a bit weird for me - day before the disk was fine... I mean I've managed to copy all the data on it.
Comment: I've asked new question: "http://askubuntu.com/questions/841976/data-recovery-damaged-filesystem". Thanks a lot for your help :)

ubuntu 16.04 `unable to mount location`


Using PHP Function in JSON Data

Question: I use a shopping cart called Avactis.  It returns back to me little "info tags" to use in my front end.  They look like this:
<?php ProductSmImage();?>
<?php ProductName();?>

I am trying to use the Agile Carousel script with some of my product in it.  I would like to use the small image, the product name, the product alt text and the product link.
The JSON data file looks like this:
[{
"content": "
Sample Carousel Pic Goes Here And The Best Part is that...
",
"content_button": "

Agile Carousel Place Holder
"
}]

And the script on the front end looks like this:

Using PHP Function in JSON Data


What can I use as latch hardware on doors only 1-1/4" thick.?

Question: The double door of the main bedroom are hollow and 1 1/4" thick.  All handle/lock sets I find require a 1 3/8" minimum door thickness for the locking mechanism.  Handyman who is helping me told me the doors are that thin because they are intended to be used as closet doors.

Is there an off-the-shelf handle and/or lock product that I am missing (that would accommodate our door thickness) or
Is there a creative and not too ugly MacGyver way the handyman can install something to give me and my husband some privacy.

As it stands, kids can (and do) open the door and come in at any time.
Comment: Our bedroom had double doors when we moved in. After installing some ceiling lights, that was the top priority to fix. We now have a single door and a nice built-in book shelf where the 2nd door used to be. (Wife liked the horrible wall paper in the bedroom, but we didn't have any more, so a built it it was. Not a hill I was willing to die on.)
Comment: Show us a photo of your door for better suggestions.
Answer: A privacy bolt will do the trick so long as it can be installed in a way that normal attempts to open the door won't break the door apart, no matter how unreasonable "normal" is in your home.

Hollow doors have solid frames within.  In the above photo, the bolt has two brackets.  The one nearer the edge of the door should be screwed into the solid frame, using appropriate screws of maximum possible length.  This requires some experience and finesse, knowing what the frame is made of and whether or how to drill it.  The other bracket should be installed with hollow door anchors.  Double doors will need two of these, one of which could be kept latched at all times.
Another way if the doors open inwards is to put a couple of U-shaped brackets on either side of the door frame and hang a broom stick between them.
Another approach that is more robust is to sandwich the door with metal plates about 3 inches by 8 inches in the area of the bolts or locks.  The plates on both sides of the door are bolted to one another through the door, and any locking hardware is attached to the plates.   This spreads the forces of any attempt to open the door across a wider area.  Hopefully this isn't necessary, IE, the doors aren't that sh*tty and your kids aren't that determined?
Answer: Back the latch sets with a filler plate. This can be 1/8" plywood, for example, sanded and finished to match the door, and attached with something as simple as double-sided tape. If done with craftspersonship it'll be fairly inconspicuous.
Note that Schlage, for example, manufactures spacer rings to allow commercial hardware intended for 1-3/4" exterior doors on residential interior doors. These may be suitable for your purposes.

source
Answer: It isn't pretty, but I'd suggest a surface mounted vertical deadbolt in this case. These are available with or without a lock cylinder so they can be opened from outside You might need a mounting plate on the outside so the cylinder and fasteners don't pull through the cheap door; I know those can be obtained through locksmiths and possibly through home centers.
(Image swiped from eBay; gods know where the seller swiped it from in turn.)


Correctness of proof for the convergence of a series

Question: Does the following series converge?
$\sum_{n=1}^\infty \frac{5^n + (-1)^n}{2^n3^n}$
What I've done so far.
$0\leq \sum_{n=1}^\infty \frac{5^n + (-1)^n}{2^n3^n} \leq \sum_{n=1}^\infty \frac{5^n + 1^n}{6^n} = \sum_{n=1}^\infty \left(\frac{5}{6}\right)^n + \sum_{n=1}^\infty \left(\frac{1}{6}\right)^n$
We know that last two series both converge, since they are an instance of a geometric series with both $|q|<1$.
Now from this, am I allowed to conclude that the original series converges? What stops it from alternating between 0 and the sum of the values of the geometric series?
Comment: IThe partial sums are **increasing**.
Comment: Note that $5^n + (-1)^n > 0$ for all $n\in \mathbb{N}$.
Comment: Use absolute convergence.
Comment: I'd like to know whether the proof above is correct or not. Can you help me with this?
Comment: You can just see that the series is absolutely convergent $\implies$ it is convergent.
Comment: Yes, your work is fine.  And it cannot alternate in sign since $5^n>(-1)^{n+1}$ for all $n\ge1$.  Thus, the terms in the series are positive.
Comment: Thanks Dr. MV. Now I also get the comment of André Nicolas. So if I use the sandwich theorem and the lower and upper series do converge, but not towards the same value, then I need the series to be monotonically increasing or decreasing in order to conclude that it converges (in case it should alternate, we could not conclude directly that the series converges).
Comment: @André Nicolas: Could you post it as an answer? So I can close the question.
Comment: It was just a comment, and Daniel Fischer made an equivalent comment first. For completeness, the partial sums are increasing, and are bounded above by your sum of two geometric series. So the partial sums converge. But this last part is covered by a standard theorem, so after the theorem is proved, it need not be mentioned explicitly.
Answer: Notice, we have $$\sum_{n=1}^{\infty}\frac{5^n+(-1)^n}{2^n\cdot 3^n}$$ $$=\sum_{n=1}^{\infty}\frac{5^n+(-1)^n}{6^n}$$
$$=\sum_{n=1}^{\infty} \frac{5^n}{6^n}+\sum_{n=1}^{\infty}\frac{(-1)^n}{6^n}$$
$$=\sum_{n=1}^{\infty}\left(\frac{5}{6}\right)^n+\sum_{n=1}^{\infty}\left(\frac{-1}{6}\right)^n$$
$$=\left(\frac{5}{6}+\left(\frac{5}{6}\right)^2+\left(\frac{5}{6}\right)^3+\ldots\right)+\left(\frac{-1}{6}+\left(\frac{-1}{6}\right)^2+\left(\frac{-1}{6}\right)^3+\ldots\right)$$ $$=\left(\frac{\frac{5}{6}}{1-\frac{5}{6}}\right)+\left(\frac{-\frac{1}{6}}{1-\left(-\frac{1}{6}\right)}\right)$$
$$=\left(\frac{\frac{5}{6}}{\frac{1}{6}}\right)+\left(\frac{-\frac{1}{6}}{\frac{7}{6}}\right)$$
$$=5-\frac{1}{7}=\frac{35-1}{7}$$ $$=\frac{34}{7}$$ Above is a finite value. Hence the series converges.


400 Bad Request error when using XMLRPC and RoR (3.1, 1.9.2) to post to a wordpress installation

Question: I am attempting to post a blog post to a wordpress blog using XMLRPC.  Here is the code I am using:
  def post(article)
    my_new_blog_post = {
     :description => article.article_texts.last.content,
     :title => article.article_title,
     :excerpt => '',
     :categories => [],
     :post_status => 'publish'
     }

    server = XMLRPC::Client.new(url)

    # Returns the ID of the new post, or fail
    resp = server.call("metaWeblog.newPost", 0, site_login, site_password , my_new_blog_post)
  end

Everything is created correctly, including the login and password, but for some reason I keep getting a 400 Bad Request error.  I logged in on the wordpress site and it worked with the username and password, so I thought maybe there are some incompatibilities with the newest ruby and the XMLRPC client. If so, is there some other method I should be using that would accomplish the same results?
Thanks!
Comment: Have you done a `puts` to verify that url, site_login and site_password are set correctly before server.call?
Answer: Not sure if this will help anyone, but figured I should put it up here.  I just had to call XMLRPC::Client.new2(url) instead.  Apparently this other type of client works.


Jquery once clicked loop two times

Question: In my meteorjs app I have a problem. I made accordion, and when clicked it quickly open and close. I did console log and see that one click activate function two times. Here is my code:

        {{#each tasksToDo}}
            {{>task}}
        {{/each}}

<template name="task">

    <divs class="editable-text-trigger">
      {{> editableText collection="tasks" field="title" wysiwyg=true}}
    </divs>

        <button class="completed">Completed</button><button class="edit">Edit</button><button class="delete">Delete</button>

Template.task.onRendered(function(){
    $('.list_item').click(function(){
        $('.editBt-active').children('.editBt').hide(400);

        if(!$(this).hasClass('editBt-active')){
            if($('.list_item').hasClass('editBt-active')){
                $('.list_item').removeClass('editBt-active');
            }

            $(this).addClass('editBt-active').children('.editBt').show(400);
        }else{
            $(this).removeClass('editBt-active');
        }
    });
});

EDIT: tried this doesn't work
'click .list_item':function(click,task){
        $('.list_item').click(function(){
            $('.editBt-active').children('.editBt').hide(400);

            if(!$(this).hasClass('editBt-active')){
                if($('.list_item').hasClass('editBt-active')){
                    $('.list_item').removeClass('editBt-active');
                }

                $(this).addClass('editBt-active').children('.editBt').show(400);
            }else{
                $(this).removeClass('editBt-active');
            }
        });
    },  still the same

SECOND EDIT:
Template.task.events({

    'click .delete': function(){
        Meteor.call("deleteTask",this._id);
    },

    'click .list_item':function(click,task) {
        $(task.find('.editBt')).hide('.editBt');
    },

    'click .editable-text-trigger': function(click, task){
            $(task.find('.editable-text-trigger')).addClass('test');
        },

    'click .edit': function(click,task){
            $(task.find('.test')).trigger('click');
         },

    'blur .editable-text-trigger': function(blur, task){
        $(task.find('.editBt')).hide('.editBt');
    }
});

Answer: On rendering a new task template instances, you add one more event handler to all existing .list_item elements (including the ones from other instances of the task template).
In Meteor, the 'official' way to define events handlers is this: (http://docs.meteor.com/#/full/template_events)
Template.task.events({
  'click .list_item': function(event, template){
        // here the handler logic
    }
});

It will register only one event handler for one .list_item element.
Comment: Just like Rafael said - remove `$('.list_item').click()` and also instead of `$('.list_item')` (or `$('.editBt-active')`), use `$(template.find('.list_item'))` (and `$(template.find('.editBt-active')`) in the handler logic - this way you'll only modify elements within a template.
Comment: 'click .list_item':function(click,task){
            $('.list_item').click(function(){
                $('.editBt-active').children('.editBt').hide(400);

                if(!$(this).hasClass('editBt-active')){
                    if($('.list_item').hasClass('editBt-active')){
                        $('.list_item').removeClass('editBt-active');
                    }

                    $(this).addClass('editBt-active').children('.editBt').show(400);
                }else{
                    $(this).removeClass('editBt-active');
                }
            });
        },  still the same
Comment: You don't put `$('.list_item').click()` into the function anymore, because the code shown by Paweł already registers click handler for .list_item element. Inside the function you just put your logic for showing/hiding elements. Also be careful with searching using `$('.list_item')` and `$('.editBt-active')`, because if performs global (whole-document) search instead of local search (relative to the rendered template).
Comment: I didn't know about that `template.find()` trick, pretty clever!
Comment: @MichelFloyd `template.find(selector)` is another way of using `Template.instance().$('selector')` ;)

Jquery once clicked loop two times


RequireJS, $.Deferred how to?

Question: Following is the code
define(['jquery'], function ($) {
  var App = function () {
    var settings = {};
    var identity = {};

    var dSettings = $.when($.getJSON("models/settings.json"));
    var dIdentity = $.when($.getJSON("models/identity.json"));

    var dApp = $.when(dSettings, dIdentity);

    dSettings.done(function (data) {
      settings = data;
      console.log(settings);
    });

    dIdentity.done(function (data) {
      identity = data;
    });

    return {
      "settings" : settings,
      "identity" : identity
    };
  };
  return App();
});

I want to create a module, who can "know" my settings and identity.
Return will do before Deferred objects is resolved and module App.js have empty Settings and Identity objects.
How can I do that?
Comment: Have a look at this plugin - https://github.com/jokeyrhyme/requirejs-promise
Comment: FYI, there is zero reason to use `$.when()` in this `var dSettings = $.when($.getJSON("models/settings.json"));`.  It can just be `var dSettings = $.getJSON("models/settings.json");`.  `$.getJSON()` already returns a promise which is all you need.
Answer: From what I can get, you want the module to fetch your settings and identity data and return it as an AMD module. Unfortunately, you have an asynchronous operation there. The best you could do is to return a promise from the module instead and let the depending modules attach then.
// SettingsAndIdentity.js
define(['jquery'], function ($) {
  // $.when resolves when all promises passed resolves
  return $.when($.getJSON("models/settings.json"), $.getJSON("models/identity.json"))
});

// foo.js
define(['SettingsAndIdentity'], function(SettingsAndIdentity){
  // Since SettingsAndIdentity is a promise, we just attach then
  SettingsAndIdentity.then(function(settings, identity){
    // start doing things here
  });
});

Comment: Doesn't require.js allow modules to depend on json files?

RequireJS, $.Deferred how to?


Thermo Pride OL5-85 oil furnace and Aprilaire 60 humidistat

Question: I have a Thermopride OL5-85 furnace. I've recently added an Aprilaire 600 humidifier, which comes with the Aprilaire 60 humidistat. Wiring diagrams for both are attached below.
The humidistat is supposed to run when the furnace is running, and when the humidity is below the designated target (I am using it in Manual mode). It is not running, even in Test / Reset mode.
After trying numerous things I have traced the problem to the fact that there is no voltage between the W and C terminals, even when the furnace is running. Here's what I get when the furnace is OFF:

Voltage between W and C (furnace is OFF): 1-2V - as expected
Voltage between W and Rh (furnace is OFF): ~26V - as expected
Voltage between Rh and C (furnace is OFF): ~26V - as expected

As soon as I connect W and Rh, which I've done both by turning up the temp on the thermostat, and by manually connecting the two terminals with a length of wire, the furnace turns ON, and I get the following readings:

Voltage between W and C (furnace is ON): 1-2V - NOT as expected
Voltage between W and Rh (furnace is ON): ~0V - as expected (after all, these are bridged directly)
Voltage between Rh and C (furnace is ON): 1-2V - NOT as expected

Furnace seems to be running fine in every regard. I am completely stumped, because this is not only running counter to my understanding of HVAC wiring, it is running counter to my understanding of basic electricity. Help me, O DIY StackExchange, you are my last hope!
Furnace wiring:

Humidistat wiring
Answer: Per reading more on this model of furnace on the internet... It will not in fact energize the W terminal when the heat is on. The solution is to use an A50 relay to detect when the blower is going. Make sure to wire the relay into the circuit running from the humidistat to the humidifier!