text:
Q: The common practice for polling inside Windows services Usually you're adviced to use something like that (using timeouts):
Thread workerThread = null;
AutoResetEvent finishedEvent = new AutoResetEvent(false);

protected override void OnStart(string[] args) {
    this.finishedEvent.Reset();
    this.workerThread = new Thread(this.Poll);
    this.workerThread.Start();
}

protected override void OnStop() {
    this.finishedEvent.Set();
    if(!this.workerThread.Join(2000)) {
        this.RequestAdditionalTime(5000);
    }
}

where Poll function is defined like:
private void Poll() {
    try {
        var timeout = Int32.Parse(ConfigurationManager.AppSettings["pollingTimeout"]);
        while(!this.finishedEvent.WaitOne(timeout, false)) {
            // do polling
        }
    }
    catch(Exception ex) {
        Logger.Log.Fatal(ex);
        throw;
    }
}

*

*Are these constructs essentially equal:
while(!this.finishedEvent.WaitOne(0, false))
and
while(true) with no finishedEvent?

*I've read that timeouts are used to reduce the cpu usage. Is it a bad choice to use polling without timeouts?

A: There is a very simple way to do this providing you don't strictly need an orderly shutdown.  If you mark the workerThread as a background thread, it will shut down automatically when the service stops.  In this example, you can forego the use of the finishedEvent and use an infinite loop.  For example,
Thread workerThread = null;

protected override void OnStart(string[] args)
{
    this.workerThread = new Thread(this.DoWork);
    // Signal the thread to stop automatically when the process exits.
    this.workerThread.IsBackground = true;
    this.workerThread.Start();
}

protected override void OnStop()
{
}

private void DoWork()
{
    try
    {
        while (true)
        {
            // do your work here...
        }
    }
    catch (Exception ex)
    {
        // handle exception here...
    }
}

Note that this approach should only be used if the work you are doing can be interrupted at any point without adverse effects.  Let's say for an example that you were writing data to an Excel spreadsheet.  Once the the Windows service exits, the thread represented by your DoWork() method will also exit immediately.  If it is in the middle of adding data to the spreadsheet, it is very likely that the spreadsheet could have incomplete information or, worse case, might even be in a state that it cannot be opened in Excel.  The point is, this approach could be used, but only in certain circumstances.
A better approach would be to fully transition to an event-based mechanism.  It is much more efficient than polling, and it allows for an orderly shutdown to your service.  Below is an example with comments.
Thread _workThread = null;
// I use ManualResetEvent instead of AutoResetEvent because I do NOT want
// this event to EVER reset.  It is meant to be set exactly one time.
ManualResetEvent _shutdownEvent = new ManualResetEvent(false);

protected override void OnStart(string[] args)
{
    _workThread = new Thread(DoWork());
    _workThread.Start();
}

protected override void OnStop()
{
    // Trigger the DoWork() method, i.e., the _workThread, to exit.
    _shutdownEvent.Set();

    // I always shutdown my service by simply joining the work thread.
    // There are probably more advanced techniques that take into account
    // longer shutdown cycles, but I design my worker thread(s) to have
    // tight work cycles so that the shutdownEvent is examined frequently
    // enough to facilitate timely shutdowns.
    _workThread.Join();
}

Now let's look at the details of the DoWork() method.  For this example, I'm gonna use a timer to illustrate the event-based approach.  Note that this illustration is not substantively different from calling the WaitOne() method with a timeout.  However, if the work to be done involves processing input from other threads, e.g., a thread that receives data from a network socket or a thread that reads data from a database, this approach easily accommodates those scenarios.
// Creature of habit.  AutoResetEvent would probably work for this event,
// but I prefer to manually control when the event resets.
ManualResetEvent _timerElapsedEvent = new ManualResetEvent(false);
System.Timers.Timer _timer = null;

private void DoWork() {
    try {
        // Create, configure, and start the timer to elapse every second and
        // require a manual restart (again, I prefer the manual control).
        // Note when the timer elapses, it sets the _timerElapsedEvent.
        _timer = new Timer(1000) { AutoReset = false };
        _timer.Elapsed =+ (sender, e) => _timerElapsedEvent.Set();
        _timer.Start();

        // Create a WaitHandle array that contains the _shutdownEvent and
        // the _timerElapsedEvent...in that order!
        WaitHandle[] handles = new WaitHandle[] { _shutdownEvent, _timerElapsedEvent };

        // Employ the event-based mechanism.
        while (!_shutdownEvent.WaitOne(0)) {
            switch (WaitHandle.WaitAny(handles) {
                case 0:
                    // This case handles when the _shutdownEvent occurs,
                    // which will cause the while loop to exit.
                    break;
                case 1:
                    // This case handles when the _timerElapsedEvent occurs.
                    // Do the work, reset the event, and restart the timer.
                    DoProcessing();
                    _timerElapsedEvent.Reset();
                    _timer.Start();
                    break;
            }
        }
    } catch (Exception ex) {
        // handle exception here...
    }
}

The WaitHandle array is what makes the event-based mechanism possible.  When you create the array, always be sure to add the events to the array in priority order.  This is why the _shutdownEvent is listed before the _timerElapsedEvent.  If the events were reversed in the array, it is possible that the _shutdownEvent would never get processed.  You can add as many events to the WaitHandle array as necessary.  That's what makes this approach so flexible.
Last thought.  To facilitate timely shutdowns of your service, you want to make sure that work to be done when the _timerElapsedEvent is triggered doesn't take too long.  In other words, the _shutdownEvent will not be checked by the while loop until the DoProcessing() method exits.  So you'll want to limit the amount of time you spend inside the DoProcessing() method.  If that method is long-running, then you'll probably want to check the _shutdownEvent inside DoProcessing() and exit at strategic points when the service has indicated it is shutting down.
Hope this helps.


text:
Q: Unselect a Select Input I have a "select" input that is programmed to open up a modal box when clicked to get some information before proceeding.  That part all works great.
The problem is that once the modal box is up, the select dropdown options are all still visible.  I want that select input to go back to being a normal, not clicked on at all, select box.
What javascript or jquery code can I use to make that select dropdown clear away?

A: I think it is more correct to move handler from click to change. In this case select will be close and keyboard changes also will be processed

A: Try using this instead:
$('#mySelect').focus(function(event){
    event.preventDefault();
    // code here
});

If that does't work, try using the preventDefault() with the click event.
The focus will at least allows users navigating fields with the keyboard (tab, etc) instead of the mouse.

A: Prior to jQuery 1.6
$('#mySelectBox :selected').attr('selected', '');

jQuery 1.6 and higher
$('#mySelectBox :selected').removeProp('selected', '');

A: I'm not sure that you can do it with standard select tag. Maybe because it still has focus. What I did when I needed a customized select tag is to avoid the select tag completely and use a button which graphically looks like the select button. Look at this page - look at the TAX button and the button to the left of it. There is no select tag, but it works great.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Mongodb query excessively slow I have a collection of tweets, with indexes on userid and tweeted_at (date).  I want to find the dates of the oldest and newest tweets in the collection for a user, but the query runs very slowly.
I used explain, and here's what I got.  I tried reading the documentation for explain, but I don't understand what is going on here.  Is the explain just on the sort?  If so, why does it take so long when it's using the index?
    > db.tweets.find({userid:50263}).sort({tweeted_at:-1}).limit(1).explain(1)
{
        "cursor" : "BtreeCursor tweeted_at_1 reverse",
        "isMultiKey" : false,
        "n" : 0,
        "nscannedObjects" : 12705,
        "nscanned" : 12705,
        "nscannedObjectsAllPlans" : 12705,
        "nscannedAllPlans" : 12705,
        "scanAndOrder" : false,
        "indexOnly" : false,
        "nYields" : 188,
        "nChunkSkips" : 0,
        "millis" : 7720,
        "indexBounds" : {
                "tweeted_at" : [
                        [
                                {
                                        "$maxElement" : 1
                                },
                                {
                                        "$minElement" : 1
                                }
                        ]
                ]
        },
        "allPlans" : [
                {
                        "cursor" : "BtreeCursor tweeted_at_1 reverse",
                        "isMultiKey" : false,
                        "n" : 0,
                        "nscannedObjects" : 12705,
                        "nscanned" : 12705,
                        "scanAndOrder" : false,
                        "indexOnly" : false,
                        "nChunkSkips" : 0,
                        "indexBounds" : {
                                "tweeted_at" : [
                                        [
                                                {
                                                        "$maxElement" : 1
                                                },
                                                {
                                                        "$minElement" : 1
                                                }
                                        ]
                                ]
                        }
                }
        ],
        "server" : "adams-server:27017",
        "filterSet" : false,
        "stats" : {
                "type" : "LIMIT",
                "works" : 12807,
                "yields" : 188,
                "unyields" : 188,
                "invalidates" : 0,
                "advanced" : 0,
                "needTime" : 12705,
                "needFetch" : 101,
                "isEOF" : 1,
                "children" : [
                        {
                                "type" : "FETCH",
                                "works" : 12807,
                                "yields" : 188,
                                "unyields" : 188,
                                "invalidates" : 0,
                                "advanced" : 0,
                                "needTime" : 12705,
                                "needFetch" : 101,
                                "isEOF" : 1,
                                "alreadyHasObj" : 0,
                                "forcedFetches" : 0,
                                "matchTested" : 0,
                                "children" : [
                                        {
                                                "type" : "IXSCAN",
                                                "works" : 12705,
                                                "yields" : 188,
                                                "unyields" : 188,
                                                "invalidates" : 0,
                                                "advanced" : 12705,
                                                "needTime" : 0,
                                                "needFetch" : 0,
                                                "isEOF" : 1,
                                                "keyPattern" : "{ tweeted_at: 1.
0 }",
                                                "boundsVerbose" : "field #0['twe
eted_at']: [MaxKey, MinKey]",
                                                "isMultiKey" : 0,
                                                "yieldMovedCursor" : 0,
                                                "dupsTested" : 0,
                                                "dupsDropped" : 0,
                                                "seenInvalidated" : 0,
                                                "matchTested" : 0,
                                                "keysExamined" : 12705,
                                                "children" : [ ]
                                        }
                                ]
                        }
                ]
        }
}
>

> db.tweets.getIndexes()
[
        {
                "v" : 1,
                "key" : {
                        "_id" : 1
                },
                "name" : "_id_",
                "ns" : "honeypot.tweets"
        },
        {
                "v" : 1,
                "unique" : true,
                "key" : {
                        "tweet_id" : 1
                },
                "name" : "tweet_id_1",
                "ns" : "honeypot.tweets",
                "dropDups" : true
        },
        {
                "v" : 1,
                "key" : {
                        "tweeted_at" : 1
                },
                "name" : "tweeted_at_1",
                "ns" : "honeypot.tweets"
        },
        {
                "v" : 1,
                "key" : {
                        "keywords" : 1
                },
                "name" : "keywords_1",
                "ns" : "honeypot.tweets"
        },
        {
                "v" : 1,
                "key" : {
                        "user_id" : 1
                },
                "name" : "user_id_1",
                "ns" : "honeypot.tweets"
        }
]
>

A: By looking at the cursor field you can see which index was used:
"cursor" : "BtreeCursor tweeted_at_1 reverse",

BtreeCursor indicates that the query used an index and tweeted_at_1 reverse is the name of the index that was used.
You should check the documentation for each field in the explain to see a detailed description for each field.
Your query  lasted 7720 ms (milis) and 12705 documents were scanned(nscanned).
The query is slow because MongoDB scanned all documents that matched your criteria. This happened because MongoDB didn't use your index for querying, but for sorting the data.
To create an index that will be used for querying and sorting, you should create a compound index. Compound index is a single index structure that references multiple fields. You can create a compound index with up to 31 field. You can create a compound index like this (order or fields is important):
db.tweets.ensureIndex({userid: 1, tweeted_at: -1});

This index will be used for searching on userid field and to sort by tweeted_at field.
You can read and see more examples about adding indexes for sorting here.
Edit
If you have other indexes MongoDB is maybe using them. When you're testing query performance you can use hint to use a specific index.
When testing performance of your queries you should always do multiple tests and take an approx. of the results.
Also, if your queries are slow, even when using indexes, then I would check if you have enough memory on the server. Loading the data from disk is order of magnitude slower then loading from the memory. You should always ensure that you have enough RAM, so that all of your data and indexes fit in memory.

A: Looks like you need to create an index on tweeted_at and userid.
 db.tweets.ensureIndex({'tweeted_at':1, 'userid':1})

That should make the query very quick indeed (but at a cost of storage and insert time)


text:
Q: Is there a name for transformations that are rigid except for possible scaling? Is there a special name for the category of 3D transformation matrices that are rigid but then may have possibly non-uniform scaling / reflections included? I.e. transforms that can represent translations, rotations, scaling, and reflection; but not shear or other non-rigid transformations.
So, I guess, the name for all the matrices $T$ that can be represented as:
$$T=\begin{bmatrix}\begin{matrix}R\end{matrix} &\begin{matrix}t_x \\ t_y \\ t_z\end{matrix}\\\begin{matrix}0 & 0 & 0\end{matrix} &1\end{bmatrix} \begin{bmatrix}s_x & 0 & 0 & 0 \\0 & s_y & 0 & 0 \\0 & 0 & s_z & 0 \\0 & 0 & 0 & 1\end{bmatrix}$$
Where $R$ is some 3x3 orthogonal rotation matrix, $s_x\neq0$, $s_y\neq0$, $s_z\neq0$, and all the numbers are in $\mathbb{R}$.

A: With uniform scaling, the transformation is called a similarity.
With non-uniform scaling, you can't avoid shear (think of a transformed diamond). I have never heard a specific term for the combination of an isometry and a non-uniform scaling (or conversely), which involves $5$ degrees of freedom. It makes more sense to consider a general affinity ($6$ DOF).


text:
Q: How to establish communication between flex and python code build on Google App Engine I want to communicate using flex client with GAE, I am able to communicate using XMl from GAE to FLex but how should I post from flex3 to python code present on App Engine.
Can anyone give me a hint about how to send login information from Flex to python
Any ideas suggest me some examples.....please provide me some help
Regards,
Radhika

A: I've been able to use flex on GAE using the examples found at The GAE SWF Project which uses PyAMF.

A: Do a HTTP post from Flex to your AppEngine app using the URLRequest class.


text:
Q: Area of intersection between two circles with same radius I am absolutely sure that there exists loads of other posts about this general type of question. However I could not find one correcting my inevitable mistake.
So I am to find the area of the intersection between two circles with the same radius and the second circles centre on the circumference of the first one.
So I thought that I could make a circle sector by connecting two radii from circle 1 to the points of intersection. This sectors area is $\frac{r^{2}\alpha}{2}$ where $\alpha$ is the angle, in radians, between the two radii.
Using the law of sines the area of the triangle $OP_1P_2$, where $O$ is the centre of the first circle, $P_1$ and $P_2$ are the points of intersection, $r\times r \times \frac{r}{2}sin(\alpha) = \frac{r^3sin(\alpha)}{2}$.
Thus the wanted area is $2(\frac{r^2\alpha}{2} - \frac{r^3sin(\alpha)}{2})$
Now we need to find $\alpha$. We can see a triangle with the sides $r$ and $\frac{r}{2}$ with the angle $\frac{\alpha}{2}$. And again using the law of sines we get $\alpha = \pm \frac{2\pi}{3}+4k\pi$. But this is supposedly wrong, from an answer by Alvin Chen link
I am sure that if I have done any trivial errors it must be with this triangle and maybe that it really doesn't have the side $\frac{r}{2}$?
Very grateful for a correction of my errors!
Thanks.
Edit: A poorly drawn Here's image of the problem!

A: If you accept decision with double integrals, then let's consider 2 circles $x^2+y^2=R^2$ and $x^2+(y-R)^2=R^2$. Area you want calculate is
$$2\int\limits_{0}^{\frac{R\sqrt{3}}{2}}\int\limits_{R-\sqrt{R^2-x^2}}^{\sqrt{R^2-x^2}}\,dx\,dy$$


text:
Q: Disable programmatic access to AWS Can we disable programmatic access using access key / secret key to the entire account? In case there is a security breach and the access key and secret key is exposed to the outside world, can the AWS account administrator freeze the programmatic access to the AWS account?

A: You can disable or delete an Access Key. You must disable access keys one at a time. There is no "global" disable or delete for access keys.
There are several types of Access Keys:

*

*AWS Root User Access Keys. You should not be using these keys. If you are, issue IAM User Access Keys and delete the root keys.

*IAM User Access Keys. These are the key types that you should use for normal access.

*Temporary Access Keys. These keys are generated by Roles or Simple Token Service (STS). These keys are temporary and expire.

Managing Access Keys for Your AWS Account Root User
Managing Access Keys for IAM Users
Revoking IAM Role Temporary Security Credentials


text:
Q: Does taking courses in mathematics give any help for mathematical logic? I'm undergraduate student of philosophy department and I think I'll major in mathematical logic.
For studying mathematical logic, I thought studying math lectures would give help to logic. So I planned to take courses in mathematics department. But I don't have conviction my thought is right. My question is whether taking math courses gives help to mathematical logic or not. Do I have to give up studying those things and just study mathematical logic only?
If taking courses gives any help, I would study same as a math major; that is, I will take analysis, linear algebra, abstract algebra, topology, differential geometry, complex analysis +alpha (maybe real analysis, number theory)ㅡI already learned calculus and set theoryㅡ. If math study is suitable, does any unnecessary course exist among above?

A: Yes, and no.
It helps because you will see proofs, you will see careful statements and you will learn, even if not directly more examples that can be used later on to study mathematical logic better.
But on the other hand, rarely anyone mentions formal logic in a course about analysis. You don't think about the inference rules, or what sort of statement you're writing, and so on. This might come up in set theory, or in model theory courses, but even then, you might be surprised how little thought we give these processes.
I am teaching a course about naive set theory (well, I'm the TA, but I'm giving a minicourse about extended topics under the guise of an exercise session). In the first class I wrote that if a set is not empty we can pick an arbitrary element of that set.
I've used existential instantiation, to move from $\exists x(x\in X)$ to an actual element $x$ from $X$; of course I didn't mention this. I hoped that they will let it slide, and they did.
But sure enough, when we discussed the axiom of choice, some six weeks later, they asked why can we choose from one non-empty set? How can we be sure that this is doable? And I explained that we have been doing that since the first class. The reason is the rules of logic, which we didn't mention to them -- because it's a naive set theory course, and these rules are applied naively.

To sum up, yes, taking math courses can help (at least those that deal with proofs) and it is very important to learn some basics as well, algebraic structures make excellent examples for theories and models in logic; but don't expect any mention of logic in those courses. You still have to learn it properly on its own.

A: Let me tell you how I got interested in logic during my undergrad. In our measure theory class, after constructing Lebesgue measure, Vitali sets were given as examples of Lebesgue non measurable sets. I wondered if one could extend the Lebesgue measure to a measure defined for all sets of reals. My instructor (an expert in applied probability and statistics) showed me how to do one step extension and tried to do a Zorn's lemma argument but he could not handle the limit stages. He forwarded my question to a set theorist who wrote a very interesting answer to me. He first sketched a proof of why continuum hypothesis implies that such a measure does not exist. This I understood without much pain (although, I had no idea then why CH could not be disproved). Then he said that the existence of such measures is equiconsistent with the existence of a measurable cardinal and ZFC is insufficient to prove this consistency. The quoted reason was Godel's incompleteness theorem whose statement I could not understand then. So I took a class in intro logic and suffered through the initial syntax-semantics boring stuff. Unfortunately, I did not find the proof of the incompleteness theorem terribly exciting (I came to a better understanding of incompleteness after learning recursion theory). It wasn't until I took a set theory class in my grad school that I finally learned the techniques needed to understand the proofs of the entire content of that email. I hope your reasons for learning logic turn out to be as exciting as mine did.

A: Unquestionably, it will help a lot. This is for two main reasons:
1) One needs exposure to proofs and practice solving problems using proofs at a high level. It's much easier to get this at first in dealing with relatively concrete objects (numbers, numerical functions, finite groups, etc.) than with very abstract objects (such as structures in a first-order language).
2) Many of the examples studied in logic come from other areas of math. For example, model theory has major applications to field theory and algebraic geometry. Set theory is interested in the provability of statements coming from all sorts of other areas, often topology or measure theory. Several areas of logic also have significant overlap with theoretical computer science.
You should consider logic a subfield of math, from a practical standpoint. You should be as interested in areas of math outside your field of specialization as non-logician mathematicians would be in areas outside theirs. Abstract algebra (including some amount of linear algebra and number theory) is the first and most important of these you should study. Analysis and topology should also be a priority.
What directions are most important after that will depend on your specialization within logic, and any of the ones you mentioned could conceivably be useful. It is likely that complex analysis and differential geometry would be less important than the others.

A: Well, mathematical logic is different from what we normally mean when we say 'logic'. To understand where it comes from and some of the motivation, it is generally good to take other math classes, but they will not teach you (much) mathematical logic. Your department should offer classes in logic, and you should take them, but other math classes will show you the context that the problems come from. Without the context, it will be hard for you to understand the mathematical logic. If you specialise in mathematical logic, you will also interact with a lot of logicians that come from a math background, so having taken some basic analysis, algebra, topology and so on will help you communicate with them.

A: Yes, of course.
To master mathematical logic you need to know mathematics, for at least two reasons:
-- methods of mathematical logic are mathematical, and you need to understand how they works from within a core mathematics area of knowledge, tackling pure mathematics issues;
-- mathematical logic developed mostly thanks to mathematicians, if you do not know mathematics to some degree, you are going to miss a real understanding of why and how mathematical logic developed.
I am not sure which math course could be better to attend. I would not go for intro courses of cutting edge issues. Some basic deep understanding of the classic areas is maybe better. Geometry is always important.
Good luck
m.


text:
Q: Lagrange optimization of vectors with two constraints I hope here is he correct place to ask my question. I am trying to develop a portfolio strategy with three assets (one of which is risk free). For this I need to determine a vector of weights (w) and maximize the return. However, I want that the volatility/variance of the portfolio is set to a predetermined level (constraint 1) and that the sum of the weights is 1 (second constraint).
I found the following formula:
$ \max_{L=w, \lambda_1, \lambda_2} = w' \mu + \lambda_1 (\sigma_{target}^2 - 0.5 w'\Sigma w) + \lambda_2 * (1 - w'\textbf{1})$
Can anyone help me solve this problem? I work with R. Is there any package that can help me with this?


text:
Q: Group/list/sort custom post type posts by date in tabs from acf datepicker field im working with foundation tabs and i want to sort my custom posts by YEAR from datepicker field. Each tab is a year (2016 2015 etc). When users click on the tab and displays is, all the custom posts that had that event-date meta field (acf datepicker field) will then display and be listet in that tabs content. But now with my code it lists every posts in its own tab wich results in multiple tabs with the same year like this (2015-2015-2015-2016-2016) Instead of (2016-2015-2014-2013) with posts lited in tab content.  This example here is what i am trying to achieve: exactly what i am after
I am not sure where i am at right now but i have done a lot and nothing does what its supposed to. Never done something like this before so i am probably a little ou of my leage here but i would like to know how this could be done and what i need to change in my code to get it done. Here is my code so far:
$currentTime = current_time('Ymd'); // getting current time
$format_in = 'd/m/Y'; // the format your value is saved in (set in the field options)
$format_out_fields = 'Y'; // the format you want to end up with
$date = DateTime::createFromFormat($format_in, get_field('event_date'));

$args = array(
    'post_type' => 'cpt',
    'posts_per_page' => -1,
    'orderby'   => 'meta_value',
    'meta_key'  => 'acf_field',
    'order'     => 'DEC',
);
$subsQuery = new WP_Query( $args );
?>
<?php if ( $subsQuery->have_posts() ) : ?>
<?php section_open(); ?>

<?php _e('H1 tabs', 'theme'); ?>

<?php innerSection_open(); ?>

<?php /////////  TABS TITLE / BUTTONS  ///////////// ?>

    <?php
    $counter = 0;
    while ( $subsQuery->have_posts() ) : $subsQuery->the_post();
    ++$counter;

    $format_in = 'd/m/Y'; // the format your value is saved in (set in the field options)
    $format_out = __('jS F Y', 'theme'); // the format you want to end up with
    $date = DateTime::createFromFormat($format_in, get_field('acf_field'));
    ?>

        <li class="tabs-title <?php if ( $counter == 1 ) { echo "is-active"; } ?>">
            <a href="#panel-<?php the_ID(); ?>" <?php if ( $counter == 1 ) { echo 'aria-selected="true"'; } ?>>
                <?php
                $format_in = 'd/m/Y'; // the format your value is saved in (set in the field options)
                $format_out_tabs = 'Y'; // the format you want to end up with
                $date = DateTime::createFromFormat($format_in, get_field('acf_field'));
                echo $date->format( $format_out_tabs );
                ?>

    <?php endwhile; ?>

    <?php /////////  TABS CONTENT  ///////////// ?>

    <?php
    $counter = 0;
    while ( $subsQuery->have_posts() ) : $subsQuery->the_post();
    ++$counter;
    ?>

        <?php
        $format_in = 'd/m/Y'; // the format your value is saved in (set in the field options)
        $format_out = __('j.m.Y', 'theme'); // the format you want to end up with
        $format_out_year = __('Y', 'theme'); // the format you want to end up with
        $date = DateTime::createFromFormat($format_in, get_field('event_date'));
        $date_year = DateTime::createFromFormat($format_in, get_field('event_date'));
        ?>

        <div class="tabs-panel <?php if ( $counter == 1 ) { echo "is-active"; } ?>" id="panel-<?php the_ID(); ?>">

            <?php echo $date->format( $format_out ); ?>:

            <?php if( get_field( 'acf_type' ) == "event") { ?>
            <?php _e('Event', 'theme'); ?>:
            <?php } ?>
            <?php
            $theTitle = get_the_title();
            echo $theTitle;
            ?>

                <?php if( get_field( 'link' )) { ?>
                <?php if (isexternal(get_field('link')) == true ) { ?>
                <a href="<?php the_field('event_link' ); ?>" target="_blank" style="text-decoration: underline;"><?php _e('Read more', 'theme'); ?>
                <?php } ?>
            <?php } ?>

    <?php endwhile; ?>

A: It's probably best to loop through your posts two times. Once to group them by year and once to print the posts.
Something like this: (not tested)
$formatted_posts = array();
while ( $subsQuery->have_posts() ) : $subsQuery->the_post();
  $year = get_field('year');
  // add them to formatted_posts array and group by year
  $formatted_posts[$year][] = $post;
endwhile;

foreach($formatted_posts as $year => $posts) {
  // print $year
  foreach($posts as $post) {
    // print $post
  }
}


text:
Q: SQLDataReader returns string with additional break characters \\\\ I am using SQLDataReader in C# to query a SQL table. One of the fields in this table is a string that holds a file path, for example "C:\\Files\\MyFiles".
However, SQLDataReader returns this string with two additional backslashes. For example: "C:\\\\Files\\\\MyFiles".
SQLDataReader appears to be detecting the escape character "\". Is there anyway I can stop it doing this?

A: It is somehow misleading for some developers when inspecting the value in visual studio. You get a string like this:
C:\\\\Files\\\\MyFiles

But when you print it to the console you get the exact string:
Console.WriteLine(path); /* C:\\Files\\MyFiles */

You can click the Magnifier icon to check the exact string characters. So no worries, you're safe to go it is just Visual Studio adding some escape characters.

A: You can replace the \\\\ with \\.


text:
Q: Retrieving text within span class with XPath I am using python to retrieve various metrics from a website (e.g., likes, twitter shares, etc.) While XPath retrieves text just fine, I'm having trouble with these metrics (text within span).
78

Now I need to get that "78", but Python does not return anything when I feed it the XPath.
Here's the XPath, just in case:
//*[@id="u_0_2"]/span[2]

Python code:
from lxml import html
import urllib2
from unicsv import CsvUnicodeReader

req=urllib2.Request("http://www.nu.nl/binnenland/3866370/reddingsbrigade-redt-369-mensen-zomer-.html")
tree = html.fromstring(urllib2.urlopen(req).read())
fb_likes = tree.xpath('//*[@id="u_0_2"]/span[2]')
print fb_likes

A: Add /text() to the xpath:
//*[@id="u_0_2"]/span[2]/text()

A: Your span is in the iframe, so you need be 'inside' the iframe, to get the text (btw, //span[@class='pluginCountTextDisconnected']/text() is correct way, but you are outside the iframe). So you need to read the src like:
a = html.fromstring(urllib2.urlopen("http://www.nu.nl/binnenland/3866370/reddingsbrigade-redt-369-mensen-zomer-.htm").read())
iframe = html.fromstring(urllib2.urlopen(a.iframe["src"]).read())
fb_likes = iframe .xpath("//span[@class='pluginCountTextDisconnected']/text()")

sorry, didn't test the code, it's just a general idea.
Update
import urllib2, lxml.html

iframe_asfile = urllib2.urlopen('http://www.facebook.com/plugins/like.php?action=recommend&app_id=&channel=http%3A%2F%2Fstatic.ak.facebook.com%2Fconnect%2Fxd_arbiter%2FZEbdHPQfV3x.js%3Fversion%3D41%23cb%3Df112fd0c7b19666%26domain%3Dwww.nu.nl%26origin%3Dhttp%253A%252F%252Fwww.nu.nl%252Ff62d30922cee5%26relation%3Dparent.parent&href=http%3A%2F%2Fwww.nu.nl%2Fbinnenland%2F3866370%2Freddingsbrigade-redt-369-mensen-zomer-.html&layout=box_count&locale=nl_NL&sdk=joey&send=false&show_faces=true&width=75')
iframe_data = iframe_asfile.read()
iframe_asfile.close()

iframe_html = lxml.html.document_fromstring(iframe_data)

fb_likes = iframe_html.xpath(".//span[@class='pluginCountTextDisconnected']/text()")
print fb_likes[0]

prints 78


text:
Q: Object is used but not declared I understand this is a fairly common question. Regardless, having gone through forums, I couldn't find a satisfactory answer as to why I'm getting the following CT error, for the given VHDL code. Can you help me please?
VHDL Code
library IEEE;
use IEEE.std_logic_1164.all;
entity design is
port(clk:IN std_logic;
reset:IN std_logic;
A:IN std_logic;
B:IN std_logic;
Q:OUT std_logic);
end design;

architecture behave of design is
--signal R0,R1,R2,R3,R4:std_logic;
begin
process(clk,reset)
variable R0,R1,R2,R3,R4:std_logic;
begin
if (reset='1') then
R0:='0';
R1:='0';
R2:='0';
R3:='0';
R4:='0';
elsif falling_edge(clk) then
R0:=R4;
R1:=R0 xor A;
R2:=R1 xor B;
R3:=R2;
R4:=R2 xor R3;
end if;
end process;
Q<=R4;       -- ERROR POINTED HERE
end behave;

Error:-
Error (10482): VHDL error at design.vhd(31): object "R4" is used but not declared

Is there a proper way of assigning variable to port, that I'm missing?

A: R4 is declared as a variable in the declarative region for your process. It is not visible outside of your process, so your tool is giving you the error you gave. If you move the line Q<=R4; inside your process, after the end if;, the error should go away, as the variable is still visible at this point.
With that said, I don't think your code will do what you think it will. I see that you started off using signal for R1 etc. You should probably avoid using a variable until you have a good understanding of the differences between a signal and a variable. There are other existing questions that address this.

A: R4 is a variable as you declared in your code . It cant use outside the endif statement.So  thats why you device is giving you an error massage. For removing this error you can declared R4  again outside the Q<=R4 and inside the endif statement.


text:
Q: Access to file list from Explorer Bar I have created simple Explorer Bar extension for Windows explorer. How can I get access to the file list in Explorer window from my bar? And how can I change current folder in Explorer window?

A: If I recall correctly, this is how it works. Your bar object should implement IObjectWithSiteand receive a site pointer. Query that for IServiceProvider, and call QueryService requesting IShellBrowser interface. That's your portal to everything else of interest. E.g. IShellBrowser::QueryActiveShellView to get the currently displayed view; IShellBrowser::BrowseObject to navigate to a different folder.


text:
Q: How can I remove SGID bit only to files (excludig folders)? Unfortunately, I applied recursively SGID bit to my folder tree.
SGID got set to any files or directories, though I only wanted to set SGID bit to folders.
So I want to correct my mistake.
If I do a chmod -R g-s *  it will includes files and folders.
How can I remove SGID bit only to files in my folder recursively ?

A: You could use find in order to execute the command only for files:
find . -type f -exec chmod g-s {} \;


text:
Q: Find the first comma in the array and the total number of this symbol I'm a student at tech unuversity. I have my hometask on JS.
Here it is: given a char array. By pressing the "Result" button, find the first comma in the array and the total number of these characters, if it is in the array, if not, display the corresponding message.
I made my code, but the teacher said that it`s wrong, because message of number of comma must displayed one time, so as message that there is no comma. Please, help me.

function result() {
  alert('PI-20\nTask №5\nArray\nOpt. №4')
  var total = 0;
  var arr = ['s', 'b', '4', '7', ',', '5', 'a', ','];
  for (var i = 0; i < arr.length; i++) {
    if (arr[i] == ',') {
      total += 1;
      alert('First comma has index ' + i);
      alert('Total numaber of comma ' + total);
    } else {
      alert('There is no comma');
    }
  }
}
<button onclick="result()">Result</button>

A: This will give you the answer you desired.
function result(){
        alert ('PI-20\nTask №5\nArray\nOpt. №4')
        var total = 0;
        var arr = ['s', 'b', '4', '7', ',', '5', 'a', ','];
        for (var i = 0; i < arr.length; i++) {
            if (arr[i] == ',') {
                total += 1;
            }
        }
         if(total > 0){
            alert('Total numaber of comma ' + total);
            }
         else{
            alert('There is no comma');
            }
    }

All you have to do is to put an if condition after the end of the loop to get the final total value than check if the total value is greater than 0 if yes than alert the message that there are commas in the array.

A: Here's a more modern approach, using a Array.reduce to collect some aggregated values from the array and display them.
Note: It is generally not a good idea to use inline event handlers. The snippet uses event delegation.

document.addEventListener("click", handle);

const log = (...strs) => {
  console.clear();
  strs.unshift('PI-20 Task №5 Array Opt. №4');
  console.log(strs.join("\n"));
};

function handle(evt) {
  if (evt.target instanceof HTMLButtonElement) {
    return result(document.querySelector("input").value.split(""));
  }
}

function result(inputValue) {
  if (!inputValue.length) {
    return log(`no values`);
  }
  const results = inputValue
    .reduce( (acc, val, i) =>
      ({ ...acc,
        chr: acc.chr || val,
        sumOfCommas: (acc.sumOfCommas || 0) + (val === ',' ? 1 : 0),
      }), { firstComma: inputValue.indexOf(",") } );
  log(
    `Input: "${inputValue.join(``)}"`,
    `Total characters: ${inputValue.length}`,
    `${results.firstComma > -1 ? `First comma Array index: ${
      results.firstComma} (position ${
        results.firstComma + 1} in input)` : `No comma's`}`,
    `${results.firstComma > -1 ? `Number of comma's: ${
      results.sumOfCommas}` : ``}`
  );
}
<input type="text" value="sb47,5a," placeholder="Type some text"/>
<button>Result</button>

A: THE PROBLEM is in the var total = 0 ;
Set it as var total;


text:
Q: Account deleted move all posts from that account to default admin account first of thank you all for taking the time reading this and answering.
i'm trying to find example or at least some help with the logic,
what i'm trying to do, is after a user removes his/her account to automatically transfer any resources to default admin account.
Using devise for user management.
Not sure what you might need to know more on this to be able to help out, But let me know and i shall provide more information.
Thank you in advance!
Update: (so in my user.rb model i have added this and the before_destroy)
It only returns me to 404 error..
def transfert_associations_to_default_account
 #This user is the one ending account
 leavinguser = current_user.username

 #This will be the default user (archive) holder for all the content
 default_user = User.find_by(username: "archive")

 #default_user.resources << resources if default_user
leavinguser.posts.update(username: default_user)
leavinguser.reviews.update(username: default_user)
end

Update 2: (fixed)
def transfert_associations_to_default_account
 #This user is the one ending account
 leavinguser = self

 #This will be the default user (archive) holder for all the content
 default_user = User.find_by(username: "archive")

 default_user.posts << leavinguser.posts
 default_user.reviews << leavinguser.reviews
 end

A: You can do a before_destroy | before_update action (depending of your logic) on the user model, like this
before_destroy :transfert_associations_to_default_account

def transfert_associations_to_default_account
 default_user = User.find()
 default_user.resources << resources if default_user
end


text:
Q: Ionic 2 datetime displaying wrong year I have a problem with display format in ion-datetime. I don't know why ionic 2 cut last 2 characters of year.
I have code:
   <ion-datetime displayFormat="MMM DD, YYYY" [(ngModel)]="form.dateOfBirth" name="dateOfBirth"></ion-datetime>

And result is:

It is a problem with column width. How can I override this size?

A: .picker-col{
//here write your custom style to increase width
min-width:64px
}

A: For ionic 2
I figured out the solution by adding following to variables.scss for both ios and android
$picker-md-column-padding: 0 0px !default;
$picker-ios-column-padding: 0 0px !default;

A:  You can try this code it's works for me hope it will help you.

date.html
 <ion-list>
        <ion-item >
            <ion-label class="capitalize">Date</ion-label>
            <ion-datetime  displayFormat="MMM DD YYYY"[(ngModel)]="dateData" (ionChange)="dateChanged()"></ion-datetime>
        </ion-item>
    </ion-list>

showDate.ts
import { Component } from '@angular/core';
@Component({
    selector: 'date',
    templateUrl: 'date.html'
})
export class Date {
        dateData: string;
    constructor() { }
    dateChanged() {
        console.log(this.dateData)
}
}


text:
Q: How to copy subdirectories as-is in a Jekyll site I have a website; some pages I maintain manually, some others, I generate using tools (mostly Shinx). For manually maintained pages, I'd like to migrate to Jekyll.
So my idea was to copy my whole website in a jekyll project, and progressively move pages from static HTML files to jekyll-managed markdown files, much easier to maintain. Generated pages, on the other hand, would be copied untouched.
It works pretty well... except that Jekyll does not copy the files starting with an underscore, which I have quite a lot: Sphinx names some special directories with a leading underscore (_static, _modules...), and I publish some python code, in which leading underscore are also used (e.g. __init__.py).
I know I could use the include directive in _config.yml, and add one by one all known files/directories that I want to keep. But I would still risk to miss some files (especially when my generators evolve).
I would rather be able to tell Jekyll, for each generated subdirectory, "this directory should be copied as-is". This would prevent it to look at every file in it to see if it should be processed, and so any file, starting with an underscore or not, would be blindly copied.
Is there a way to do that? I could not find any...

A: The strategy I use (and, I assume, the strategy intended by the jekyll developers) is to have the generation tool (sphinx, yard, ...) generate directly into the output directory (e.g. _site/api) and add the resulting folder to the keep_files configuration option in _config.yml

A: Jekyll copies any folders it finds, as is, unless their names begin with an underscore. An underscore tells Jekyll to not copy the directory to _sites directly.
As you are moving to Jekyll I'd say it's best to follow Jekyll's standard naming format and remove the underscores from directories that you do want copied to _sites.

A: This is odd. A folder named hippo_menus wasn't being included in my output. It used to, but then stopped all of sudden. I changed it to hippomenus and now it's included in the output.


text:
Q: Error Upgrading To .NET 4.5 I'm trying to upgrade from VS2010 .NET 4 to VS2012 .NET 4.5 and I'm getting the following error in each Project that I've set to .NET 4.5 when they try to build.
The expression "[Microsoft.Build.Utilities.ToolLocationHelper]::GetPathToStandardLibraries(.NETFramework, ?, '', '')" cannot be evaluated. Version string portion was too short or too long.
I can't find any references to this in my code and the msdn reference for the function doesn't provide any hints (http://msdn.microsoft.com/en-us/library/hh135279.aspx).
Anyone seen this before or know the solution?
Edit
The solution listed here doesn't seem to work. http://social.msdn.microsoft.com/Forums/da-DK/vseditor/thread/8ca4a9b0-742d-487d-ab8c-6c3a80cffd40

A: Somehow after multiple tries, including restarting the machine and visual studio, this started working for no apparent reason.

A: Unload your project and remove the below tag from your .csproj file:
<TargetFrameworkVersion></TargetFrameworkVersion>

and reload your project again, it works for me.

A: I had the same problem when upgrading from 4.6.1 to 4.7.2 framework.
I had a big solution with many projects.
This error turned out when building the last project (win application), which had the correct <TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>.
The cause of the problem were the other projects, used by the win app project.
They had incorrect framework versions.


text:
Q: Conditional Regex Replace in C# without MatchEvaluator So, Im trying to make a program to rename some files. For the most part, I want them to look like this,
[Testing]StupidName - 2[720p].mkv
But, I would like to be able to change the format, if so desired. If I use MatchEvaluators, you would have to recompile every time. Thats why I don't want to use the MatchEvaluator.
The problem I have is that I don't know how, or if its possible, to tell Replace that if a group was found, include this string. The only syntax for this I have ever seen was something like (?<group>:data), but I can't get this to work. Well if anyone has an idea, im all for it.
EDIT:
Current Capture Regexes =
^(\[(?<FanSub>[^\]\)\}]+)\])?[. _]*(?<SeriesTitle>[\w. ]*?)[. _]*\-[. _]*(?<EpisodeNumber>\d+)[. _]*(\-[. _]*(?<EpisodeName>[\w. ]*?)[. _]*)?([\[\(\{](?<MiscInfo>[^\]\)\}]*)[\]\)\}][. _]*)*[\w. ]*(?<Extension>\.[a-zA-Z]+)$

^(?<SeriesTitle>[\w. ]*?)[. _]*[Ss](?<SeasonNumber>\d+)[Ee](?<EpisodeNumber>\d+).*?(?<Extension>\.[a-zA-Z]+)$

^(?<SeriesTitle>[\w. ]*?)[. _]*(?<SeasonNumber>\d)(?<EpisodeNumber>\d{2}).*?(?<Extension>\.[a-zA-Z]+)$

Current Replace Regex = [${FanSub}]${SeriesTitle} - ${EpisodeNumber} [${MiscInfo}]${Extension}
Using Regex.Replace, the file TestFile 101.mkv, I get []TestFile - 1[].mkv. What I want to do is make it so that [] is only included if the group FanSub or MiscInfo was found.
I can solve this with a MatchEvaluator because I actually get to compile a function. But this would not be a easy solution for users of the program. The only other idea I have to solve this is to actually make my own Regex.Replace function that accepts special syntax.

A: It sounds like you want to be able to specify an arbitrary format dynamically rather than hard-code it into your code.
Perhaps one solution is to break your filename parts into specific groups then pass in a replacement pattern that takes advantage of those group names. This would give you the ability to pass in different replacement patterns which return the desired filename structure using the Regex.Replace method.
Since you didn't explain the categories of your filename I came up with some random groups to demonstrate. Here's a quick example:
string input = "Testing StupidName Number2 720p.mkv";
string pattern = @"^(?<Category>\w+)\s+(?<Name>.+?)\s+Number(?<Number>\d+)\s+(?<Resolution>\d+p)(?<Extension>\.mkv)$";

string[] replacePatterns =
{
    "[${Category}]${Name} - ${Number}[${Resolution}]${Extension}",
    "${Category} - ${Name} - ${Number} - ${Resolution}${Extension}",
    "(${Number}) - [${Resolution}] ${Name} [${Category}]${Extension}"
};

foreach (string replacePattern in replacePatterns)
{
    Console.WriteLine(Regex.Replace(input, pattern, replacePattern));
}

As shown in the sample, named groups in the pattern, specified as (?<Name>pattern), are referred to in the replacement pattern by ${Name}.
With this approach you would need to know the group names beforehand and pass these in to rearrange the pattern as needed.


text:
Q: Distance measure of a function In Mattila's Fourier Analysis and Hausdorff Dimension, we have on page 59 that given a finite measure $\mu$ compactly supported on a set $A \subset \mathbb{R}^n$, we can define a finite measure $\delta(\mu)$ compactly supported on its distance set $D(A):=\left\{\lVert x-y \rVert : x,y \in A \right\}\subset \mathbb{R}$ as
$$
    \delta(\mu)(B)= \int \mu(\{y:|x-y|\in B\}) d \mu(x).
$$
It is then claimed that we have, for any $f \in C_0^\infty$,
$$
\delta{(f)}(r)= \int (\sigma_{r}^{n-1} *f)f,
$$
where $\sigma_{r}^{n-1}$ is the typical measure on the $(n-1)$-dimensional sphere of radius $r$. How is $\delta(f)$ defined here? I thought we could only input a measure.


text:
Q: Обновление значений модели pydantic по словарю Как это ни странно, но не могу найти никакого метода модели пакета pydantic, отвечающего за обновление значений объекта по словарю. Странно, что такое возможно при инициализации объекта, но не при его существовании.
Хочется чего-то подобного:
class Foo(BaseModel):
    num: int
    line: str

f = Foo(num=1, line="bla-bla")
f.update({"num": 3})
print(f.dict())        # {"num": 3, "line": "bla-bla"}

Я нашел нечто подобное в методе model.copy(update=dict), но оно умеет только создавать копии с изменением данных. Так же есть метод parse_obj(dict), который является классовым и тоже используется исключительно для инициализации.
Есть ли что-то подобное в штатном функционале моделей pydantic?


text:
Q: awk: Set value in second line, colunm (if it exists) to variable Consider this file:
#!/usr/bin/env bash
cat > example_file.txt <<EOL
group, value
1, 3.21
1, 3.42
1, 3.5
2, 4.1
2, 4.2
EOL

Now I want to set the value in the second column, second row to a variable val2. I try:
var='example_file.txt'
cat $var | val2=$(awk -F, "NR==2{print $2; exit}")

but

*

*This doesn't work: echo "$val2" returns nothing

*I would like to assign to val2 a default value in case the file has only one line.

A: Try this
var='example_file.txt'
val2=$(cat $var | awk -F, "NR==2{print $2; exit}")

The cat needs to be directly piped into the awk command, rather than the variable assignment line.
Note that you can get rid of the cat all together with:
val2=$(awk -F, "NR==2{print $2; exit}" <$var)


text:
Q: libgit2 and Qt error I want to use git from an Qt application. So far, I use QProcess, but I do not want to use that. So I found libgit2.
This works as expected:
#include <QApplication>
#include "git2.h"
int main(int argc, char* argv[])
{
    git_repository* repo = 0;
    git_clone(&repo, "/path_to/barerep", "/path_to/test_clone", NULL);
    git_repository_free(repo);
    repo = 0;
}

But here, git_clone crashes.
int main(int argc, char* argv[])
{
    QApplication a(argc, argv);

    git_repository* repo = 0;
    git_clone(&repo, "/path_to/barerep", "/path_to/test_clone", NULL);
    git_repository_free(repo);
    repo = 0;

    return a.exec();
}

The error is:
    *** Error in `/path_to/gittest': free(): invalid pointer: 0x09d53a88 ***
Any suggestions? Of course, omitting QApplication is not an alternative. The same error occurs without return a.exec().
Note: Actually, there is a class GitRepository with a method clone(const QString & url) (the path is stored somewhere in the class).
Again, this works
int main(int argc, char* argv[])
{
    GitRepository g;
    g.clone("path_to/barerep");
}

But this does not. (QObject!)
int main(int argc, char* argv[])
{
    QObject();  // <--
    GitRepository g;
    g.clone("path_to/barerep");
}

does not.
bool GitRepository::clone(const QString & url)
{
    git_repository* repo = 0;
    git_clone(&repo, CSTR(url), CSTR(path()), NULL);
    git_repository_free(repo);
    repo = 0;

    //loadFromTempDir();

    return true;
}

Replacing QApplication by QObject in the first example suppresses the error.

A: You need to call git_libgit2_init() before calling any other libgit2 functions. As the documentation says:

This function must the called before any other libgit2 function in order to set up global state and threading.

A: These kind of errors are really hard to find. I also had problems mixing Qt libraries with other libraries. The trick is to organize your code in a way that there is only one library included in one compilation unit.
Create a class, which wraps around libgit2, and only include the libgit2 headers in the cpp file of this class. Do not include any qt headers in the same file.
Only refer to libgit throw your wrapper. Sure it seems like a lot of work, but as a result your code will be cleaner, and these misterious errors will be gone.


text:
Q: save both image and text as single image in server we have product image in site like below image

We are providing an option for customer to upload custom image on product image.

also customer can and add text on that image

Here Problem is Customized Product design is saving as 2 different imagesas  below links in server [ 1.Text & 2.uploaded image as separately]  but what we want is once Customer click on "save design"   we want to save that "customized Product image" in server as single image.
image path : http://sbdev2.kidsdial.com:81/media/custom_product_preview/quote/White_Background_Iphone_Pics_1.jpg
text path : http://sbdev2.kidsdial.com:81/media/custom_product_preview/quote/1b22f071-1ad8-e945.png
code for svg
protected function _processSvg( $apply_offsets = false )
    {
        $request = $this->getRequest();

        $data = $request->getPost('data');

        if(empty($data)){header('Location: '.Mage::getBaseUrl());die;}
        $model = Mage::getModel('aitcg/image_svg');
        /** @var $model Aitoc_Aitcg_Model_Image_Svg */
        $model
            ->setApplyOffsets($apply_offsets)
            ->setDataType($request->getPost('type'))
            ->initLayer('top', $data)
            ->initLayer('bottom', $request->getPost('data_bottom'))
            ->setPrintType($request->getPost('print_type'))
            ->prepareBackground($request->getPost('background'), $request->getPost('areaOffsetX'), $request->getPost('areaOffsetY'), $request->getPost('print_scale'))
            ->normalizeMask()
            ->processAdditional($request->getPost('additional'));

        return $model;
    }

    public function svgAction()
    {
        $model = $this->_processSvg();
        $data = $model->normalizeSvgData();
        //$data = $mode->getSvgData();

        if ($model->getAdditionalData('order_increment_id'))
        {
            $filename = 'Order_' . $model->getAdditionalData('order_increment_id') . '_Image.svg';
        } else {
            $filename = 'Customer_Product_Image.svg';
        }

        $this
            ->getResponse()->setHttpResponseCode(200)
            ->setHeader('Pragma', 'public', true)
            ->setHeader('Cache-Control', 'must-revalidate, post-check=0, pre-check=0', true)
            ->setHeader('Content-type', 'image/svg+xml', true)
            ->setHeader('Content-Disposition','attachment; filename="'.$filename.'"',true);
        $this->getResponse()->clearBody();

        //$this->getResponse()->setBody(str_replace('xlink:','',$data));
        $this->getResponse()->setBody($data);
    }

code for SVG to PNG
public function svgtopngAction()
    {
        $model = $this->_processSvg(true);
        $model->resetMaskForPng();
        $data = $model->getSvgData(false, true);
        $data = $model->applyXlinkToData($data);
        $this->getResponse()->setBody($data);
    }

Save Design button code :
script
var aitcgBaseConfig = {
    text: {
apply: "<?php echo $this->__('SAVE DESIGN') ?>",
}

html
<?php
/**
 * @var $this Aitoc_Aitcg_Block_Catalog_Product_View_Options_Type_File
 */
$_option = $this->getOption();
$_fileInfo = $this->getFileInfo();
$_image = $this->getImage();
$_rand = rand();
$_fileOption = 'options_' . $_option->getId();
$_preview = $this->getPreview();
$_defaultValues = isset($_preview['img_data']) ?
    $_preview :
    array('img_data' => '');
$checkboxEnabled = (int)Mage::getStoreConfig('catalog/aitcg/aitcg_confirm_checkbox');
if ($checkboxEnabled) {
    $fullCheckboxEnabled = Mage::getStoreConfig('catalog/aitcg/aitcg_confirm_fullcheckbox');
}
$sharedImgId  = Mage::helper('aitcg')->getSharedImgId($_rand);
$sharedImgUrl = Mage::helper('aitcg')->getSharedImgUrl($sharedImgId);
$sharedImgWasCreatedUrl = Mage::helper('aitcg')->getSharedImgWasCreatedUrl(); ?>
<link rel="stylesheet" type="text/css" href="<?php echo Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_JS);?>fancybox/jquery.fancybox.css" />

<label<?php if ($_option->getIsRequire()) : ?> class="required"<?php endif ?>><?php //echo  $this->htmlEscape($_option->getTitle()) ?><?php if($this->isMageGtEq19() && $_option->getIsRequire()) : ?>*<?php elseif ($_option->getIsRequire()) : ?> *<?php endif ?>
    <?php echo $this->getFormatedPrice() ?>

<dd<?php if ($_option->decoratedIsLast){?> class="last"<?php }?>>

            <?php echo $this->__('Sorry, but your browser does NOT support HTML5 elements and this feature is not working or may work incorrectly.');?>

            <?php echo $this->__('Please, try using different browser.');?>
            <?php echo $this->__('Please, try using different browser (Opera Mini for example) or update your Android to a newer version.');?>

        <?php //echo $this->__('Click on the thumbnail to choose the product image for editing.'); ?>
        <div class="aitcg_image_div"  style="float:none;display:none;" id="preview_container<?php echo $_option->getId(); ?>">

        <input type="hidden" id="options_<?php echo $_option->getId() ?>" class="input-text<?php echo $_option->getIsRequire() ? ' aitcg-required' : '' ?> product-custom-option" name="options[<?php echo $_option->getId() ?>]" value='<?php echo $this->htmlEscape($_defaultValues['img_data'])?>' />
        <?php if ($checkboxEnabled == 1): ?>

            <input type="checkbox" name="<?php echo $_rand; ?>_checkbox" id="<?php echo $_fileOption; ?>_checkbox" class="product-custom-option <?php if ($_option->getIsRequire()) : ?>required-entry<?php endif ?>" <?php if($fullCheckboxEnabled == 1): ?>onClick="return opCimage<?php echo $_rand; ?>.checkConfirmBox(this);" <?php endif; ?>/>
            <?php if($fullCheckboxEnabled == 1): ?>
            <a href="#" onClick="return opCimage<?php echo $_rand; ?>.checkConfirmBox(this);"><?php echo Mage::getStoreConfig('catalog/aitcg/aitcg_confirm_text'); ?>
            <?php else: ?>
            <label for="<?php echo $_fileOption; ?>_checkbox"><?php echo Mage::getStoreConfig('catalog/aitcg/aitcg_confirm_text'); ?>
            <?php endif; ?>

        <?php endif; ?>

We have option of saving customized product image as single image from frontend. once we click on Save graphics & than save as PNG button we can save the image from frontend to customer's local system [computer] . but that image is not saving in server. in same way, once we click on "Save Design" button, we want to save the image in server:

A: Its a too lengthy question. You have to use lots of JS event and Magento event to event to create this.

*

*First You have to create a SVG product image with different Text on it as you want to show.

*You have to add a text box in frontend and on change event of that textbox you have to update the canvas of product image.

*On click add to cart you have to upload this image on certain place.

*Also you have to create a extra field in quote item table and order item table

*At add to cart after event you have to save this image path in quote item table and convert this image in order item.

*You also have to show this image in order view page (admin and frontend)

There is a extension available for the same process.
To Save that image on server side you have to create a form and on click to Add to Cart you have to submit a form with user text. And in that you have to create image at server end and save that image with text and put that image path in quote.

A: on product page after adding image and text when you save the design it converts it into svg
It calls the action svgtopng of indexcontroller of aitcg module.
I found something save to png and save as pdf in your DOM. So may be your extension provides the save to png functionality.
Go through extension documentation or code.


text:
Q: How do I implement this generic Java interface with a Clojure record? I'm trying to implement org.joda.time.ReadableInstant. It inherits from a generic interface, but apparently that shouldn't matter. The interface is:
public interface ReadableInstant extends Comparable<ReadableInstant> {
    long getMillis();
    Chronology getChronology();
    DateTimeZone getZone();
    int get(DateTimeFieldType type);
    boolean isSupported(DateTimeFieldType field);
    Instant toInstant();
    boolean isEqual(ReadableInstant instant);
    boolean isAfter(ReadableInstant instant);
    boolean isBefore(ReadableInstant instant);
    boolean equals(Object readableInstant);
    int hashCode();
    String toString();
}

My record:
(defrecord WeirdDate [year month day]
    ReadableInstant
    (^boolean equals  [this ^Object readableInstant] (.equals (as-date this) readableInstant))
    (^int get [this ^DateTimeFieldType type] (get (as-date this) type))
    (^Chronology getChronology [this] (.getChronology (as-date this)))
    (^long getMillis [this] (.getMillis (as-date this)))
    (^DateTimeZone getZone [this] (.getZone (as-date this)))
    (^int hashCode [this] (.hashCode (as-date this)))
    (^boolean isAfter [this ^ReadableInstant instant] (.isAfter (as-date this) instant))
    (^boolean isBefore [this ^ReadableInstant instant] (.isBefore (as-date this) instant))
    (^boolean isEqual [this ^ReadableInstant instant] (.isEqual (as-date this) instant))
    (^boolean isSupported [this ^DateTimeFieldType field] (.isSupported (as-date this) field))
    (^Instant.toInstant [this] (.toInstant (as-date this)))
    (^String toString [this] (.toString (as-date this))))

But I get the error:
java.lang.IllegalArgumentException: Must hint overloaded method: get

Are my type hints wrong? Is there something else wrong?
(Apologies for those of you on the Clojure mailing list where I've already asked a longer version of this question, I thought that a shorter question here might be easier to answer)

A: You can't use a defrecord to implement a type with a get method, because get is already defined on java.util.Map, which defrecord automatically implements for you. If you want to implement this interface, you will have to forego the niceties of mappiness and just use a plain deftype. Also, every type hint in your code is completely unnecessary: the compiler knows the types of the interface you're implementing, and doesn't need your help to figure them out.


text:
Q: How to retrieve IAM Entities limits and current usage via Powershell I need to retrieve the following current count and capacity(limit) for AWS account:

*

*users

*groups

*roles

*instance profiles

*server certificates per AWS account.

I have tried next commands:

*

*Get-EC2AccountAttributes,

*Describe methods of Ec2Client class
Thank you in advance

A: As outlined in Limitations on IAM Entities, the AWS Identity and Access Management (IAM) service limits can be retrieved by means of the GetAccountSummary API.
The respective AWS Tools for Windows PowerShell cmdlet is Get-IAMAccountSummary:

Retrieves account level information about account entity usage and IAM quotas. [...]


text:
Q: Decompressing a content of unknown length with python-lz4 I am trying to decompress a content of unknown size using python-lz4 using the following code
with open("compressed.msgpk", "rb") as f:
    content = f.read()
    if content[0] == 1:
        uncompressed = lz4.block.decompress(content[1:])

but it always fails with
LZ4BlockError: Decompression failed: corrupt input or insufficient space in destination buffer. Error code: 58

I even tried specifying different/bigger sizes as shown here https://python-lz4.readthedocs.io/en/stable/lz4.block.html but nothing worked.
And if it help the content I am trying to decompress is compressed using lz4net c# library using method LZ4Codec.WrapHC(content) https://github.com/MiloszKrajewski/lz4net/blob/201ed085fed299523616bfd08776694cb61ae6b3/src/LZ4/LZ4Codec.cs#L562

A: The unwrap method decodes a wrapped block, but the lz4.block.decompress method appears not to take wrapping into account.
I'm not 100% familiar with the python and c# libraries you are using but I wonder (from the docs) if the lz4.frame.decompress might be the method you are looking for?


text:
Q: java чтение объектов из файла. очередь с приоритетом Я считываю из текстового файла объекты. И всё бы ничего, но они не образуют очередь с приоритетом. Почему так происходит?(Пробовал создавать объекты для записи в файл - и там всё работало хорошо)
Подскажите, как это исправить?
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;

class Order {
    int Id;
    String name;
    String courier;
    String dateTime;
    int type;

    public Order(int Id, String name,String courier,String dateTime,int type ) {
        this.setId(Id);
        this.setName(name);
        this.setCourier(courier);
        this.setDateTime(dateTime);
        this.setType(type);
    }

    public int getId() {
        return Id;
    }
    public void setId(int Id) {
        this.Id = Id;
        }
    public String getName() {
    return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getCourier() {
    return courier;
    }
    public void setCourier(String courier) {
        this.courier = courier;
    }

    public String getDateTime() {
    return dateTime;
    }
    public void setDateTime(String dateTime) {
        this.dateTime = dateTime;
    }
    public int getType() {
    return type;
    }
    public void setType(int type) {
        this.type = type;
    }
    public String toString() {

        return "ID: "+ Id + " " +"Name of item: "+ name +" " + "Courier: "+ courier + " " +"dateTime: "+ dateTime + " "+"Type: "+ type + " "+"\n";
    }

}

public class Main {
    public static void main(String[] args) throws IOException{

                Scanner input = new Scanner(new File("Stock.txt"));
                input.useDelimiter("-|\n");

                Order[] products = new Order[0];
                while(input.hasNext()) {
                    int Id = input.nextInt();
                    String name = input.next();
                    String courier = input.next();
                    String dateTime = input.next();
                    int type = input.nextInt();

                    Order newProduct = new Order(Id, name,courier,dateTime,type );
                    products = addOrder(products, newProduct);
                }

                /*for (Order product : products) {
                    System.out.println(product);
                }*/

                PriorityQueue<Order> pq1 = new PriorityQueue<Order>(5, new OrderComparator());
                pq1.add(products[0]);
                pq1.add(products[1]);
                pq1.add(products[2]);
                pq1.add(products[3]);
                pq1.add(products[4]);

                System.out.println("ORDERS:\n");
                for(Order pq2: pq1)
                    System.out.println(pq2);
        }
    private static Order[] addOrder(Order[] products, Order productToAdd) {
        Order[] newProducts = new Order[products.length + 1];
        System.arraycopy(products, 0, newProducts, 0, products.length);
        newProducts[newProducts.length - 1] = productToAdd;

        return newProducts;
    }

    }

class OrderComparator implements Comparator<Order>{

            public int compare(Order o1, Order o2) {
                if (o1.type > o2.type)
                    return 1;
                else if (o1.type < o2.type)
                    return -1;
                return 0;
                }
        }

A: https://docs.oracle.com/javase/7/docs/api/java/util/PriorityQueue.html#iterator()

The iterator does not return the elements in any particular order.

Итератор возвращает элементы в произвольном порядке.

System.out.println("ORDERS:\n");
while (pq1.size() > 0)
  System.out.println(pq1.poll());


text:
Q: Moderator flags incorrectly displayed As you can see from this screenshot, the flag page indicates I have one flag to deal with, but the tab title says zero flags, and the page is empty of flags.
Just a caching/race condition that will clear up soon?

(and yes, when I took the screenshot it looked like the page was updating - it didn't change)

A: It's just caching, and only really noticeable on sites where there's only a few (less than page of) flags pending at any given time, you'll almost never notice this on Stack Overflow, or other sites that get a few flags every few minutes.
It'll normalize rather quickly.


text:
Q: how to pass a json object from html form submit I have a logging page and I wanted to send the logging details in json format to the checkuser.php file which is a other page in the web site.
checkUser.php file will create a new window.
 What is the best way to do this ? if possible please give me some example.

A: $("#myform").submit(function( e ) {
    e.preventDefault();

    $.ajax({
        url: "blabla.com/api",
        type: 'POST',
        contentType: 'application/json',
        data: JSON.stringify( { key: val } ) // <-------- HERE IS YOUR JSON
    }).done(function() {
        console.log('hooray!');
    });
});

A: Suppose you have a login form as login.php with html form controls txtLogin and txtPassword and a Submit button. Once the user submits the form it would post data onto checkuser.php
You can write the following code that can push data in JSON format
$login = $_POST['txtLogin'];
$password = $_POST['txtPassword'];

$userArray = array('login'=>$login,'password'=>$password);
$json_array = json_encode($userArray);


text:
Q: Sunspot - How to use StatsComponent with excluding filters? I have used Sunspot for my website searching and filtering. I have also price slider on my website. Sunspot provide me stats for price columns but with filters. I want to exclude the price filters from stats. Otherwise stats will generate on filtered results.
I have got same issue which was mentioned below JIRA link.
https://issues.apache.org/jira/browse/SOLR-3177
It would be useful to exclude the effects of some "fq" params from the set of documents used to compute stats – similar to
how you can exclude tagged filters when generating facet counts...
https://wiki.apache.org/solr/SimpleFacetParameters#Tagging_and_excluding_Filters
So this was already implemented into SOLR. But I am not able to understand, how I can do same with Sunspot. Can any one help me for same?
Thanks


text:
Q: Fonts problem in Google Chrome for Mac Sometimes I open up websites in Google chrome and the fonts look busted like this:
alt text http://dl.dropbox.com/u/324237/chrome-fonts.png
I've see a variety of fixes for this posted around forums, but none that reliably worked.  Has anyone solved this for good?

A: I suffered this same issue and nothing worked to resolve it. I recently used Chromatic to update to the very latest build, and the problem resolved itself.


text:
Q: What software should I use to make a copy of my hard drive in ISO format? I want to make a complete copy of my hard drive (and I have the capability to boot off external media to allow for unmounting of hard drive partitions).  However, the majority of "ghosting" software I find only allows me to make images that are not really mountable or explorable ... in other words, I want a complete and total copy of hard drive, but I want to be able to explore so that I can recover individual files or folders if need be, and the best solution I have found is to build an ISO from my hard drive and mount it whenever I feel like it.
My real question, though, is: which software would recommend for this purpose - and do you think this is even the best solution anyway?

A: Those are somewhat incompatible goals: either it's a completely accurate image of the filesystem, or it's reorganised to be an ISO.
Are you using Linux? What you could do then is burn an image of the filesystem as a file within an ISO, and then mount it as a loopback device.
If your hard drive fits on a DVD, it's a very small drive...

A: Using linux you can pull this off pretty easily with dd. dd is a Linux command line utility that allows you to mirror/copy a drive or a partition from a drive to either a file or another drive. It copies the partitions byte for byte, including any unused space on the filesystem.
Can I assume from your username and icon that you're using Ubuntu? :-) I'm assuming some knowledge here, so feel free to ask in the comments if you have any questions.
Note: If you're not using Linux and are on Windows, you have a few options. You can use dd for windows or boot from an Ubuntu disc/USB drive. You can then mount the file in Windows using one of the tools linked in the comments below.
Determine which partition you want to clone
So let's say the drive you want to copy is /dev/sda. (If it is an external drive, it might be /dev/sdb, /dev/sdc, etc...) For you to be able to mount it (the partition you're interested in) later, you'll want to copy the individual partitions, not the full drive image. If you already know which partition you want (ie. the 3rd partition, /dev/sda3), you can go ahead and skip this part. If you're not sure or want to check, use the fdisk tool to list out your partitions:
$ sudo fdisk -l /dev/sda

You're probably interested in the largest one, measured in blocks. Let's say it's /dev/sda3
Copy the partition to a file
Let's assume that you want to copy that drive's contents to /media/thumbdrive/backup.img
Check out the man dd manpage for details on what all the arguments to dd mean. I'll provide a working example here:
dd if=/dev/sda3 of=/mount/thumbdrive/backup.img bs=1M

Showing progress
dd does not normally give any output while it works, and it can take a long time. You can get dd to show its progress by sending it a USR1 signal. You do this with the kill command.
Open another terminal, and run
killall dd -USR1

dd will then output its progress in the other terminal.
Mounting the partition later
After the copy is done, you can mount that backup.img file as if it were a device, using the -o loop option to the mount command. Let's say you want to mount it onto /media/backup:
sudo mkdir -p /media/backup # create a directory for it to mount onto
sudo mount -o loop /media/thumbdrive/backup.img /media/backup
ls /media/backup # you will see the files that are on the drive you copied

You can unmount the file later:
sudo umount /media/backup

Note that you can edit or add files inside backup.img while it's mounted. Changes will be persisted as long as you unmount properly.

A:
I want a complete and total copy of hard drive, but I want to be able to explore so that I can recover individual files or ...

You can use some commercial software which supports this (e.g. Ghost and use ghostwalker to open an 'explorer window' to the inside of the image, or you could create a full backup with dd and mount that via loopback.
But as .iso? No, not quite the way.

A: If you are just backing up to another hard drive, and are on Windows, you can use RoboCopy to simple copy all the files themselves off to the other drive.  It doesn't need to be any more complicated than that.  I have 2 drives and I was going to RAID mirror them, but decided it was just easier to set up a scheduled task to copy all the files from one drive to the other every night. If you want compression, you can probably just put everything in a big 7-zip archive on the other hard drive.


text: Q: Notation Explanation Here, page $3$, there is this notation $\bar{P}^{\beta X}$. I know that $\beta X$ is the stone-Cech compactification of $X$, but authors do not define what is $\bar{P}^{\beta X}$. Is it the set of all functions from $\beta X$ to $\bar{P}$?


text:
Q: Multiple files process with different output names in R I have a number data set (say 50 files) of csv files: crasha, crashabd, crashd, …
I wrote a function to do some changes and analysis for a single data. I want to have a dynamic name for output. For example, I want to have newcrasha, newcrashabd, newcrashd, and … as output csv files. Indeed, I want to get names of imported files and use these as output filenames?
For example:
filenames <- list.files(path = "D:/health/car crash/", pattern = "csv",full.names = TRUE)

analyze <- function(filename) {

  # Input is character string of a csv file.
  crash <- read.csv(file = filename, header = TRUE)

    #merg and summation (crashcounter and NUMBER_INJURED)

newcrash<-crash %>% group_by(COLLISION_DATE) %>% summarise(crashcounter = sum(crashcounter), NUMBER_INJURED = sum(NUMBER_INJURED))
   write.csv( newcrash, "D://health//car crash// newcrash.csv", row.names = FALSE)
 }
filenames <- filenames[1:50]
for (f in filenames) {
  analyze(f)
}

Thank you for any help

A: try this, following the suggestion of @mhovd:
filename <- list.files(path = "D:/health/car crash/", pattern = "csv",full.names = TRUE)

analyze <- function(filename) {

  # Input is character string of a csv file.
  crash <- read.csv(file = filename, header = TRUE)

  #merg and summation (crashcounter and NUMBER_INJURED)
  newcrash<-crash %>% group_by(COLLISION_DATE) %>% summarise(crashcounter = sum(crashcounter), NUMBER_INJURED = sum(NUMBER_INJURED))
  new.name <- paste0("D:/health/car crash/new",basename(tools::file_path_sans_ext(filename)),".csv")
  write.csv( newcrash, file=new.name, row.names = FALSE)
}

lapply(filename[1:50], analyze)


text:
Q: stll no users table after migrating I'm working along with the book Service Oriented Design with Ruby and Rails. In the first chapter, it creates a service with a Sinatra application using active record. I created the active record migration (001_create_users.rb, see below), and ran the rake file to migrate it (using the command rake db:migrate), and it gave me output which seemed to indicate the users table was created (see the bottom of this post for the output after running rake db:migrate). However, when I ran the specs (rspec spec/service_spec.rb, see below), it gave me an error saying that it couldn't find the users table.
table_structure': Could not find table 'users' (ActiveRecord::StatementInvalid)

Can you tell me what I might be doing wrong? The source code for the first chapter of the book can also be found here https://github.com/pauldix/service-oriented-design-with-ruby/tree/master/chapter_01
spec/service_spec.rb
RSpec.configure do |conf|
  conf.include Rack::Test::Methods
end

def app
  Sinatra::Application
end

describe "service" do
  before(:each) do
    User.delete_all
  end

  describe "GET on /api/v1/users/:id" do
    before(:each) do
      User.create(
        :name => "paul",
        :email => "paul@pauldix.net",
        :password => "strongpass",
        :bio => "rubyist")
    end

    it "should return a user by name" do
      get '/api/v1/users/paul'
      last_response.should be_ok
      attributes = JSON.parse(last_response.body)["user"]
      attributes["name"].should == "paul"
    end

/db/migrate/001_create_users.rb
class CreateUsers < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string :name
      t.string :email
      t.string :password
      t.string :bio

      t.timestamps
    end
  end

  def self.down
    drop_table :users
  end
end

Rakefile
require 'rubygems'
require 'active_record'
require 'yaml'
require 'logger'

desc "Load the environment"
task :environment do
  env = ENV["SINATRA_ENV"] || "development"
  databases = YAML.load_file("config/database.yml")
  ActiveRecord::Base.establish_connection(databases[env])
end

namespace :db do
  desc "Migrate the database"
  task(:migrate => :environment) do
    ActiveRecord::Base.logger = Logger.new(STDOUT)
    ActiveRecord::Migration.verbose = true
    ActiveRecord::Migrator.migrate("db/migrate")
  end
end

After running rake db:migrate
D, [2013-03-08T20:11:55.490937 #3824] DEBUG -- :    (0.2ms)  select sqlite_version(*)
D, [2013-03-08T20:11:55.493906 #3824] DEBUG -- :    (2.1ms)  CREATE TABLE "schema_migrations" ("version" varchar(255) NOT NULL)
D, [2013-03-08T20:11:55.497176 #3824] DEBUG -- :    (2.6ms)  CREATE UNIQUE INDEX "unique_schema_migrations" ON "schema_migrations" ("version")
D, [2013-03-08T20:11:55.544128 #3824] DEBUG -- :    (44.9ms)  SELECT "schema_migrations"."version" FROM "schema_migrations"
I, [2013-03-08T20:11:55.544615 #3824]  INFO -- : Migrating to CreateUsers (1)
D, [2013-03-08T20:11:55.545263 #3824] DEBUG -- :    (0.1ms)  begin transaction
==  CreateUsers: migrating ====================================================
-- create_table(:users)
D, [2013-03-08T20:11:55.570509 #3824] DEBUG -- :    (0.6ms)  CREATE TABLE "users" ("id" INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, "name" varchar(255), "email" varchar(255), "password" varchar(255), "bio" varchar(255), "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL)
   -> 0.0018s
==  CreateUsers: migrated (0.0019s) ===========================================

D, [2013-03-08T20:11:55.571113 #3824] DEBUG -- :    (0.1ms)  INSERT INTO "schema_migrations" ("version") VALUES ('1')
D, [2013-03-08T20:11:55.576187 #3824] DEBUG -- :    (4.8ms)  commit transaction
michael$ rspec spec/service_spec.rb
D, [2013-03-08T20:12:57.812685 #3854] DEBUG -- : env: test
D, [2013-03-08T20:12:57.910829 #3854] DEBUG -- : db/test.sqlite3 database connection established...

A: The migrate task calls environment as prerequisite which sets the environment to "development" by default, unless there's an ENV variable saying something else.
What happens is that your dev DB gets migrated, but not your test DB.
Like the instructions for your book say, a little after, call
rake db:migrate SINATRA_ENV=test

And it'll be your test DB being migrated.


text:
Q: Grouping data in a certain way in mysql I have a query that fetches data from a table called supervisor_approvals, I want to group rows of a certain department together and leave the other department ungrouped for each labref
    say supervisor approval structure looks like this
    -------------------------------------------------
   labref   department
    ab        1
    ab        1
    ab        0
    ab        0
    ab        0
    xy        1
    xy        0
    xy        0

  After Query (Result should be)
labref     department

  ab          0
  ab          1
  ab          1
  xy          0
  xy          1

Instead it does not show other labref data just the first one as shown  a http://sqlfiddle.com/#!2/6fb86/9!
my sql
SELECT DISTINCT *
                FROM supervisor_approvals
                WHERE department = 0
                AND assign_status='0'
                GROUP BY department
                UNION ALL SELECT *
                FROM supervisor_approvals
                WHERE department = 1
                AND assign_status='0'
                ORDER BY department DESC

A: try:
SELECT * FROM supervisor_approvals group by labref,department


text:
Q: JDBC SQL prepared statement calling function but getting expression error I'm trying to insert a TIMESTAMP into a table, but the timestamp inserted will always be X days away from now. Here is my code:
ps = c.prepareStatement("INSERT INTO tablename (uuid, pool, expires) VALUES (?, ?, DATE_ADD(NOW(), INTERVAL ? DAY)");
ps.setString(1, player.getUniqueId().toString());
ps.setInt(2, plugin.s.DEFAULT_POOL);
ps.setInt(3, plugin.s.PAYMENT_DAYS);

But when this executes a syntax error occurs. If there is a better method for doing this, or a fix for this, I'd like to know. Thanks!

A: First of all note that your query is missing a closing ) at the end, the following:
VALUES (?, ?, DATE_ADD(NOW(), INTERVAL ? DAY)

Should be:
VALUES (?, ?, DATE_ADD(NOW(), INTERVAL ? DAY))

Then may be you need to use a new Date() and add to it the PAYMENT_DAYS for the date type, try the following:
public static Date addDaysToCurrentDate(int days) {
     SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
     Calendar c = Calendar.getInstance();
     c.setTime(new Date());
     c.add(Calendar.DATE, days);
     return sdf.parse(c.getTime());
}

ps = c.prepareStatement("INSERT INTO tablename (uuid, pool, expires) VALUES (?, ?, ?)");
ps.setString(1, player.getUniqueId().toString());
ps.setInt(2, plugin.s.DEFAULT_POOL);
ps.setInt(3, addDaysToCurrentDate(plugin.s.PAYMENT_DAYS));

A: try using select instead of values
insert into ... select ?,?, DATE_ADD(NOW(), INTERVAL ? DAY))

or replace with java code as suggested:
Calendar c = Calendar.getInstance();
c.setTime(new Date());
c.add(Calendar.DATE, days);
ps.setDate(3, new java.sql.Date(c.getTime().getTime()));

A: ps = c.prepareStatement("INSERT INTO tablename (uuid, pool, expires) VALUES (?, ?, DATE_ADD(NOW(), INTERVAL ? DAY)");

? DAY, this question mark needs to be an integer.
You need to calculate.


text:
Q: Incorrect displaying of icons in ModelBuilder? I'm using ArcGIS 10.1 for Desktop.
Something weird happened with icons in my model.
They are displaying incorrectly as you can see here
.
In other models all is just fine.

A: From our discussion (in comments) it looks like the solution is to:

*

*Create a New Model

*Edit the corrupt model and right-click within it to choose Select All followed by Copy from the context menu

*Edit new model and right-click within it to choose Paste from the context menu

If you have a reproducible procedure to corrupt a model, then I would strongly recommend that you report this as a bug to Esri or your local distributor.


text:
Q: Calculated column in Hive I am having this table and I want to make the calculated column form the far right.

My logic is the following:
For all IDs
   For all rows
     IF (delta <= 2 OR delta = NULL) { "Observation " + counter' }
     ELSE { counter +1; "Observation " + counter; }
   reset counter to 1

But I can translate it in SQL

A: You can do this with window functions:
select t.*,
       sum(case when delta > 2 then 1 else 0 end) over (partition by id order by time end) + 1
from t;

This produces a number.  You can construct the string however you like.


text:
Q: Eigenvectors choose intuitive ordering/sorting Starting from some symmetric $L\times L$ matrices $M$(see below), I want to compute the eigenvectors in Mathematica, in order to construct an orthogonal operator $U$ such that

$U^T.M.U=D$

yields a diagonal matrix. Now, I'm not really satisfied with the default ordering.
For constructing the matrices, I first define, with eg. $L=5,n=1;$ the vectors
 dmcos = Array[- Cos[-Pi + 2 Pi (# - 1)/L ] &, L];
 dn = ConstantArray[J, L - n];

*

*If the matrix is already diagonal (M0=DiagonalMatrix[dmcos]) the expected and orthogonal matrix of eigenvectors would be the identity-matrix of course(which is what I prefer), but the result of
U=N@Eigenvectors[M0]//Transpose

is a different one, although it consists only of 0's and 1's as well.

*If more diagonals have nonzero elements (M1=SparseArray[{Band[{1, 1}] -> dmcos, Band[{1, n + 1}] -> dn, Band[{n + 1, 1}] -> dn)]//Normal), I would like to have the eigenvectors sorted in the same way as M0, to be a bit more precise,
if we would vary J continuously from 0 to some finite value, every single column in the matrix U should change continuously as well.
I explicitly want to construct a matrix $U$ for a different number of $J$'s because I want to transform other matrices in the same way as $M_0$ changes to $M_1$ so I need to keep track of the correspondence of the eigenvectors with rows and columns in $M$. Intuitively, the ordering I prefer is what I expected from the beginning when diagonalizing $M_1$ but it turns out not to be true, as according to the documentation eigenvectors are sorted according to the absolute value of the corresponding eigenvalues.
I tried a generalized eigenvalue as well, which seemed to do slightly better(but I want to be sure I get the right results, not just think it) and a bunch of inverse transformations and so on, but the more I think about it, the more I seem to confuse myself. Nevertheless, what I want is just a simple thing, you could look at $U$ as a transformation matrix that transforms $M0$ to $M1$ and vice versa (which is the way I want it) so it would seem to me there's a short and easy way to do this?

A: As @Rahul pointed out in the comments, it is impossible to start from the unit matrix and change J such that the eigenvectors change continuously. However, I found a nice way to keep track of the correspondence of the eigenvectors when changing J, making use of the fact that values of eigenvalues don't cross as a function of J and in Eigensystem the eigenvalues and eigenvectors are in the same order. What I'm doing is relabeling all levels such that the one with lowes dmcos comes first
eig=Eigensystem[M];
perm=FindPermutation[eig[[1]],Sort[eig[[1]]];
perm2=FindPermutation[dmcos,Sort[dmcos]]
U=Permute[eig[[2]],perm] //Transpose; U=Permute[U,perm2];