Find the splitting field of $x^3-1$ over $\mathbb Q$. Express your answer in the form $\mathbb Q(a).$

Question:
Find the splitting field of $x^3-1$ over $\mathbb Q$. Express your answer in the form $\mathbb Q(a).$

Solution: Let $\mathbb E$ be a splitting field for $x^3-1$ over $\mathbb Q$. Then $x^3-1$ can be factored as a product of linear factors in  $\mathbb E[x]$.
$$x^3-1=(x-1)(x-\omega)(x-\omega^2)$$
where $\omega $ is the third root of unity.
We also know that splitting field of $f(x)$ (nonconstant) over a field $\mathbb F$ is the smallest field containing $\mathbb F$ and all of its roots.
Thus $\mathbb E=\mathbb Q(1,\omega,\omega^2)$.
Is it correct?
Need help in representing the splitting field in the form $\mathbb Q(a)$.
Also please explain the answer by David Wheeler in Find the splitting field of $x^3-1$ over $\mathbb{Q}$.
Comment: You have the correct field, but it's not expressed in the required form $\mathbb{Q}(a)$. However, since $1 \in \mathbb{Q}$, you don't need to adjoin $1$, and since $\omega^2 \in \mathbb{Q}(\omega)$, you don't need to adjoin $\omega^2$. Thus, you can express $E$ as just $\mathbb{Q}(\omega)$.
Comment: I removed the tag [tag:finite-fields]. Last time I checked $\Bbb{Q}$ had infinitely many elements :-)
Comment: About the last sentence of your question: since $2\omega=-1+\sqrt{-3}$, we have $\mathbb Q(\omega)=\mathbb Q(\sqrt{-3})$.
Comment: thanks a lot.You made my day@quasi &@Pierre-Yves Gaillard
Answer: It's correct, and $$\mathbb Q(1,\omega ,\omega ^2)=\mathbb Q(\omega )=\{a+b\omega +c\omega ^2\mid a,b,c\in \mathbb Q\}.$$


Carrying inequalities from derivatives to functions

Question: This question is related to this one. Given two functions $f,g\colon \mathbb{R}^n \to \mathbb{R}$, and given that at a certain point $x_0 \in \mathbb{R}^n$ we have $f(x_0) \geq g(x_0)$, and given an open subset $A \subseteq \mathbb{R}^n$ containing $x_0$, on what conditions on the partial derivatives of $f$ and $g$ on $A$ can I assure that $f(x) \geq g(x)$ for every $x \in A$? When is this inequality strict?
This question came when I was trying to prove that for all $(x,y) \in \mathbb{R}^2$ and $(x,y) \neq (0,0)$, it holds that $x^2 + y^2 > xy$. Somehow, it seemed visually obvious that the function $x^2 + y^2$ grew faster than $xy$, and so they could never catch up again after the origin, but I found difficulties when trying to formalize this thought.
Also, is there a name for this result/test/condition, even if only on the one variable case?
Comment: For part 2, note that $$x^2+y^2=\frac{x^2+y^2}2+\frac{(x-y)^2}2+xy\ge xy$$
Comment: My roommate just pointed out: the case where $xy < 0$ is trivial. For the other one, wlog, suppose $|x| \geq |y|$. Then, $x^2 \geq xy$, from which the inequality follows. I'm still curious about the derivative test, though.
Comment: Cant you simply use AM GM Inequality? Or more simply $ (x-y)^2$ is non negative
Comment: @GautamShenoy That would work for part 2, but doesn't answer part 1 :(
Answer: While dodging your actual question, I will provide you this explanation to prove that $x^2+y^2\ge xy$.
We know that the root-mean square is bigger than or equal to geometric mean.
$$\sqrt{\frac{x^2+y^2}{2}} \ge \sqrt{xy}$$
Clearly,
$$x^2+y^2\ge 2xy > xy$$
assuming $x$ and $y$ are positive.
To give a small idea for your question, I can say if $f$ is bigger than $g$ at a point and then if the derivative of $f$ is bigger than derivative of $g$ everywhere (actually, after that point is enough), then you can conclude $f$ is bigger than $g$ everywhere after that point.
Comment: Are you sure about your last statement ? Let $f(x)=x,g(x)=x/2$, then $f'>g'$ and $f(1)>g(1)$ but $f(x<0)<g(x<0)$
Comment: Because you started comparing them at $1$ and ensured that $f$ is bigger but at the end compared them for numbers smaller than $1$. Notice the last words: everywhere AFTER that point. I meant right side by "after". Sorry for lack of clarification


How is the file data in the database table file_usage created and managed?

Question: I am deleting orphaned image files in Drupal 7, but I have to first cross reference them to other tables that might be using the images. Given that I don't upload any images via the IMCE editor interface and mainly do uploads via the image module, would it be safe to say i can cross reference the table file_managed and image_dimensions to file_usage and delete what's not there?
Right now I'm just wondering how file_usage is populated. Is it populated every time I upload any file type?
Answer: The code used by Drupal to delete temporary files is the following one. (It runs during cron tasks.)
<code>  // Remove temporary files that are older than DRUPAL_MAXIMUM_TEMP_FILE_AGE.
  // Use separate placeholders for the status to avoid a bug in some versions
  // of PHP. See http://drupal.org/node/352956.
  $result = db_query('SELECT fid FROM {file_managed} WHERE status <> :permanent AND timestamp < :timestamp', array(
    ':permanent' => FILE_STATUS_PERMANENT,
    ':timestamp' => REQUEST_TIME - DRUPAL_MAXIMUM_TEMP_FILE_AGE,
  ));
  foreach ($result as $row) {
    if ($file = file_load($row->fid)) {
      $references = file_usage_list($file);
      if (empty($references)) {
        if (!file_delete($file)) {
          watchdog('file system', 'Could not delete temporary file "%path" during garbage collection', array('%path' => $file->uri), WATCHDOG_ERROR);
        }
      }
      else {
        watchdog('file system', 'Did not delete temporary file "%path" during garbage collection, because it is in use by the following modules: %modules.', array('%path' => $file->uri, '%modules' => implode(', ', array_keys($references))), WATCHDOG_INFO);
      }
    }
  }
</code>
file_usage_list() is the function that queries the "file_usage" table.
The function that adds a row in that table is file_usage_add(); looking at the functions/hooks that calls it, I conclude that the "file_usage" table is used for managed files. Since you are not deleting the files with a row in the "file_managed" table, I would say you can avoid checking the "file_usage" table.
Answer: The canonical way t do it, is to add usage mark when you use a picture, and remove it when you are no longer doing it. It means image with 3 references and one original upload will have 4 usage marks. When something reference it once more, it'll gets bumped to 5. If something unreference, one usage mark goes away. And if you only uploaded file with something like #managed_file file is NOT marked as used untill form is saved, and even then only if function handling submit decides it should be.
When invoking file_delete(), only if usage count 0, Drupal will delete a file - both file itself from hdd and all its metadata from tables. No tests on your side are needed, you can simply loop it over all files you want, or call it after each usage delete (that's usual practice).
The idea is - you should never interact with that table directly, only via file_usage_add(), file_usage_delete() and file_usage_list(). And you should never delete actual file or it's database record. Well, unless it's needed immediately due to content security issue or something like that. But otherwise, Drupal takes care.


Laravel - How to Clear cache of array language

Question: I have a laravel application and I have two different languages.
My problem is that I'm using queued emails and that just work with default language, so I try to add new keys and values to default language array to give me the possibility to use in both languages.
The problem is that don't recognise the new keys, makes me think that is a cache situation but I already clear the cache with artisan commands and continue the same.
Now I delete my messages.php inside my lang folder and It consider the older key yet. Is it cache? How can I solve that?
I put this in blade and works for default language:
@lang('messages.'. $months->month)

Next I add new keys to so I can translate to another language using the same default array language and do that:
@lang('messages.'. $months->month .'-en')

My array is like that:
'Março' => 'Março',
'Março-en' => 'March',

but it just recognise the first key.
Thank you
Comment: Did you restart the queue worker for it to pick up the code updates?
Comment: This is in a shared hosting so I have this : $schedule->command('queue:work --timeout=60 --tries=1')->everyMinute(); @user3242861
Comment: That will spawn an endless amount of queue workers with you having no chance to control them.
Comment: So what is the solution for that? @Namoshek
Comment: Except for the obvious _get a proper hosting solution_, I'm afraid I cannot really help you.
Comment: I'd wonder, who's brilliant idea was to put the languages into a queue. Nowadays many clients want to edit the translations themselves. And this gets us into trouble.
Answer: The language files cached in a queue, all you need is to restart queue like so:
php artisan queue:restart

Answer: I ran into a similar situation in a project I was working on.
The issue in my case was that I was assuming that the PHP localization definitions (ex: resources/lang/en/auth.php) were going to be used when performing translations using the __() function.
As it turns out though, when somebody set this project up, they did so in a way that would be able to share out the translations with the front-end.  In order to do so, this person had set up a new artisan command that would compile JSON equivalents of those PHP localization definitions.  Unfortunately, when they did that, they chose to use the same folder/filenames that Laravel will use too (ex: resources/lang/en.json).
Because of the fact that this had been done, Laravel was reading from these JSON files instead of the PHP files whenever I used the __() function.  This meant that changes would only ever be reflected if I first deleted those JSON files, and then rebuilt them.
Ultimately, I ended up updating the script that builds those JSON files.  Now they're created with different names so there is no conflict.


Model simplification

Question: I am currently looking at a linear mixed model of with the formula x ~ y * z
I'm struggling with simplifying the model.

When I run an ANOVA of my model it said there was no interaction so I reduced the model to remove the interaction term.
However when I simplify my model I find my $R^2$ value drops and the significance values change (e.g., stuff becomes significant that isn't significant in my full model). To add to my confusion there actually is an interaction between one of my z categories and one of my y values! Despite this, my AICc value states that the reduced model is better...!

I've been made aware of the issues in model simplification giving false effects and was wondering if it's best to just keep my full model?
Comment: Can you post the output from the two models to make the question more concrete?
Answer: A couple of points:

You have not stated what test exactly are you performing when you run ANOVA. I would suggest that you best fit your linear mixed model using restricted maximum likelihood (REML), which is the default in most software, and then you do an F-test for the interaction using the Satterthwaite's degrees of freedom. In R you can do this using the lmerTest package. This will work better especially if you have a relatively small sample size.
The coefficients for the variables y and z have a different interpretation when the interaction y:z is in or out of the model. Hence, it could be well the case that their statistical significance changes. Moreover, instead of looking only at statistical significance, you should also have a look at practical significance, and see what the two models say for your outcome. For example, doing an effects plots using the effects package in R.
The $R^2$ is a bit controversial outside the case of simple linear regression. There are several versions of it for (linear) mixed effects models, each one doing something different.
Likewise it is not clear which version of the AICc you are using. Note that the standard version of it only works for univariate normal data, and therefore is not directly appropriate for linear mixed models that are designed for multivariate normal data.
Moreover, in mixed models there are also different AICs depending on which version of the model you are interested in, namely, the marginal model in which your integrate the random effects out or the hierarchical model that is defined conditional on the random effects. For the latter you can have a look at the cAIC4 package.
Comment: I am confused as to how : is different from + and *. I can't find anything on google about it from a search just now
Comment: Regarding the interpretation, you may find my answer here useful: https://stats.stackexchange.com/q/420303
Answer: Dimitris comments are useful, but I think the fundamental issue here is the assumption that you have to simplify your model.
If your initial hypothesis was x ~ y * z, fit this model, check residuals, consider if you might be overfitting (i.e. do you have enough data to fit this model), and if everything is fine report the results and move on.
Removing predictors that are n.s., or model selection before significance testing is not helpful if you are interested in calibrated p-values and unbiased regression estimates.

Model simplification


Is there any space with normal structure but not uniform normal structure?

Question: It is clear that uniformly normal structure implies normal structure. But, is there any space that has normal structure but it doesnt have uniformly normal structure?? Would you mind to give me some example? thanks...
Answer: In example 4.1 of E. Maluta, Uniformly normal structure and related coefficients, Pac. J. Math, 111 (1984), No. 2, 357–369, it is shown that the $\ell_2$-sum $Y = \bigoplus_{n \geq 2} \ell_n$ is reflexive, has normal structure, but not uniformly normal structure.
In fact, Maluta investigates two numerical characteristics $D(X)$ and $\tilde{N}(X)$ of a Banach space $X$. The space $X$ has uniformly normal structure iff $\tilde{N}(X) \lt 1$. Her Theorem 4.2 shows that $D(X) \leq \tilde{N}(X)$ for all Banach spaces, and in her Example 4.1 she shows that $D(Y) = 1$ for the example above.
The main result of the paper is that a space having uniformly normal structure is necessarily reflexive.


Implied Meaning of "Original Arrangement"

Question: What is the implied meaning of "Original Arrangement" in the context of, say, a YouTube video – would the reader think that this is

(1) the arrangement of the piece of music when it was first released/performed by the original performer/composer, or
(2) a new arrangement of the piece, which has been arranged by the person who posted the video?

If the implication is (1), then what is the appropriate name for (2)?
Edited To Add
A term which is commonly used in popular but not classical music is "cover" or "cover version", which ties in with definition (2) above.
Comment: The composer's choice of song form and instrumentation is also an arrangement.
Comment: This seems to be a a contradiction in itself. Either it is the original (including instrumentation as writtten by composer) or an arrangement. Combining the words could therefore mean anything. Note, that there is one additional scenario:  the composer modifies a piece of his/her own e.g. for a different solo instrument.
Comment: @b3ko you wouldn't normally call a composer's original an arrangement, you would rather call it a composition, and then if you arrange it in another way you would usually apply the term "arrangement". At least that is a common way of using the term "arrangement".
Comment: @LarsPeterSchultz In certain contexts (e.g. big-band jazz) it's not unusual to use the term 'arrangement' for a piece as originally composed. Or the composer might be purely a songwriter who produces a lead sheet and has someone else 'arrange' the piece.
Comment: @PiedPiper Well, since the term "arrangement" refers to something you arrange you could strictly speaking call anything you arrange for an arrangement. So I suppose you could call a composition an arrangement. If that has become a tradition within certain contexts who am I to argue about that.
Answer: I would wager the actual distribution between meanings 1 & 2 is probably 50/50.
People failing to differentiate between
It's as the author intended, therefore 'original' &
It's brand new & made by me & no-one else… & therefore 'original'.
A better term would simply be "new", but that doesn't have the 'advertising-speak' of original.
Answer: This is an interesting question but may not be worth the time to track down.  I did a google search on the term after reading this question and found contradictory uses of the term.  On the one hand several academic sites refer to case (1) as the "original work" not an arrangement.  And they also refer to an arrangement as a variant of the original work by application of new or alternate harmonization, changes in tempo, style, rhythm, etc.  So it would seem that we are discussing "original work" (which by the way has an arrangement) rather than some sort of arrangement of the work after the fact.  On the other hand I find several examples of statements like "after much efforts we finally tracked down the original arrangement of Misty..." or some other tune.  I think in this case they are referring to the arrangement developed by the composer or the first recording of the song.  Sometimes composers do not do their own arranging.  They may work out a tune on the piano and hand it off to a partner to arrange for orchestra or band.
Based on my search I can add a third option to the mix, just to make it clearer?  Some may refer to an original arrangement of a piece by a particular artist or genre.  As an example (potentially a funny one to some) consider the orchestral arrangements of Metallica's work.  This is not the "original work" and it is a "first occurrence of such an arrangement", e.g. original.  Decades after the fact several variants of this arrangement may have been written and produced based on the creative decisions of different conductors etc.  Now "original arrangement" does not refer to Metallica's recorded albums.  I might refer to this as the "original arrangement for orchestra" as someone may produce an arrangement for big band, or a Latin percussion group.
And there may be a fourth case.  That of the original composer creating a NEW arrangement of their own tunes.  Miles did it.  Many people do it.  So then what is this?  Still a new, original arrangement of an original piece by the composer (not the original composer as that would be redundant, unless it's Stairway to Heaven (possibly)).
When someone makes their own arrangement of a piece I think it makes sense to call that an "original arrangement".  So if I saw that in a description I would think that I am about to hear a version of something created by the people who posted the video.  You cannot stop people form using terms out of common context and quite frankly "original" can apply to both cases.
In my opinion original work should be used for composer's first arrangement and original arrangement to refer to new arrangements of the piece by other artists.  It may be useful to use other adjectives such as first arrangement, composer's arrangement, etc.
Comment: What would we call an arrangement of a multi-composer composition done by only one of its composers? I run into this fairly often in video game music.
Comment: "Sometimes composers do not do their own arranging": this is usually the case in musical theater.  Regardless, it would be fairly unexceptional to use the term "original arrangement" for the arrangement from the first production of a show (revivals often use new orchestrations).  But I would find it slightly odd to differentiate Mozart's orchestration of *Messiah* from Handel's by calling Handel's the original arrangement.  "Original orchestration" might be better.
Comment: @phoog I would simply call Messiah Handel's work or Handels's composition and not use the term "original" neither the term "arrangement" nor the term "orchestration". It is self evident that Handel's own work is original so the term "original" is not needed and I don't need those other words either. The way he created Messiah is his work so why add any other word to it?
Comment: Any composer can rearrange their own music.   The term original arrangement is not without merit
Comment: @LarsPeterSchultz to differentiate it from [Mozart's version](https://en.wikipedia.org/wiki/Der_Messias).  For example: "I like that recording of Messiah, but where are the trombones?" "There aren't any; that's the original orchestration."
Answer: Wow lots of complex answers!
My take from personal experience is the answer is (1)
The appropriate name for (2) is simply "arrangement"
Example:
SATIN DOLL
original arrangement by Duke Ellington
arrangement by: John Doe


Why were there horse problems in Melbourne in 1956 but not in Sydney in 2000?

Question: This Wikipedia article on the 1956 Summer Olympics says

Although Melbourne was awarded the 1956 Olympic Games, Australia had a strict six-month pre-shipment quarantine on horses. A meeting in 1953 by Australian federal authorities ruled that they would not change the quarantine laws for the Olympic horses. Therefore, the equestrian competition would not be able to be held in Australia.

The 1956 equestrian events were held in Stockholm. I have a bunch of encyclopedias, but none of them describes anything similar from Sydney. Logically, 2000 equestrian had to be shifted somewhere as well. Why was a similar problem not identified in that year?
Comment: Why do you believe the answer is anything more than the obvious "Australia changed the regulations sometime in the intervening 44 years"?
Answer: It seems pretty obvious that they would have changed the law. And they actually did. According to the Department of Agriculture, Fisheries and Forestry:

Horses that meet Australia's strict import conditions can be imported into Australia from approved countries. A valid import permit is required, and all import conditions must be met before horses are eligible for import into Australia.
Pre-export quarantine takes place immediately prior to export and involves:

14 days isolation from other horses not of equivalent health status (or 21 days isolation for horses from the United Arab Emirates)
monitoring for signs of illness
testing for diseases of biosecurity concern (with acceptable results)
oversight and certification from an official government veterinarian in the exporting country.

On a personal note, in no way Australia would have been eligible for the Olympics if they still had that old law. And pretty sure the olympic commitee had checked stuff like that even before the country would file their application.
As we can read from this NY Times article, logistic has been a nightmare:

Between Sunday and Thursday, 266 horses from 35 countries are to board planes in Frankfurt, Amsterdam, New York, Los Angeles and London's Stansted Airport.
The flights mark the culmination of a logistical nightmare of quarantine and paperwork caused by Australia's animal import rules, the toughest on the planet.
Every horse going to Sydney has been at a pre-quarantine stable for 14 days and has a lengthy certificate detailing its exact whereabouts for the 46 days before that. Because Australia will only allow horses coming from Europe, North America, Japan and New Zealand to enter the country, horses from other places have to have stayed in one of the approved countries for still another 46 days.

The last update of this law was 2008/2010 but I can't find the year of this one as quoted here, and still running.
Comment: So tl;dr: there were problems, just smaller problems.
Comment: @PhilipKendall : 1956 : 180 days. 2000 : 46+14 = 60 days. I would say "*smaller problems by 2 thirds*" :D


Contact point VS boundary point

Question: What is the difference between a contact point and a boundary point on a metric space ?
In topology and mathematics in general, the boundary of a subset S of a topological space X is the set of points which can be approached both from S and from the outside of S. More precisely, it is the set of points in the closure of S not belonging to the interior of S. An element of the boundary of S is called a boundary point of S.
In mathematics, an adherent point (also closure point or point of closure or contact point)[1] of a subset A of a topological space X, is a point x in X such that every open set containing x contains at least one point of A. A point x is an adherent point for A if and only if x is in the closure of A.
Comment: Where have you come across these terms? It would be useful to work with _your_ definitions of contact and boundary point.
Comment: adherent point = contact point
Comment: That's ok, but can you write up the _definitions_ for these? It will make the difference clear, and if not, we can help you figure it out.
Answer: Well following your definitions you have that contact point equals closure point and boundary equals closure minus interior. So the difference between closure and boundary is as that the former includes the interior points.
For example the boundary of the interval $(0,1)$ is $\{0,1\}$ but the closure is $[0,1]$.
For a definable topological space $X$ and a subset $A\subseteq X$ let $cl(A)$ denote the closure of $A$ and $bd(A)$ its boundary. Then $bd(A)=cl(A)\cap cl(X\setminus A)$.

Contact point VS boundary point


jquery inside wordpress ACF custom block can't select element outside of block

Question: I have an advanced custom fields gutenberg block template like this:

On this site:

Registered using:
function register_on_this_site_block() {
    if ( function_exists( 'acf_register_block' ) ) {
        acf_register_block(array(
            'name'            => 'on-this-site-block',
            'title'           => __( 'On This Site Block', 'wds'),
            'description'     => __( 'Links to parts of current page.', 'wds'),
            'render_template' => get_template_directory() . '/template-parts/blocks/on_this_site.php',
            'category'        => 'layout',
            'icon'            => 'align-center',
            'mode'            => 'preview',
            'keywords'        => array('links'),
        ));
    }
}
add_action( 'acf/init', 'register_on_this_site_block' );

JQuery can select the '#anchor_list' seemingly because it is in the same template. But when selecting the '.anchor-block' it returns an object with length 0 and the 'each' function does nothing.
How can I access elements outside of this block? Actually it should be mentioned that the '.anchor-block' element resides in another custom ACF block.
Comment: `$('.anchor-block')` is performing a global selector on the entire document, as the document exists at that point in time.  If the selector is returning 0, no element exists matching that selector, at that point in time.
Comment: ACF loads fields via ajax, so you'll need to select the #anchor-block within a callback so it doesn't get called until the fields are present.
Answer: As Taplar said, the elements I was selecting did not exist at the time I was trying to select them. I thought my (function($) { })(jQuery) function was running after the page has been fully loaded but actually it does not. I changed the code to this and it works:
    var $ = (jQuery);
    $(window).bind("load", function() {
        var anchor_list = $('#anchor_list');
        $('.anchor-block').each(function() {
            var heading_text = $(this).html();
            var href = '#' + $(this).attr('id');
            var html = '
' + heading_text + '
';
            anchor_list.append(html);
        });
    });

Although you can see the empty list for a split second before it populates with the
 elements, but thats fine for me.


Include NuGet packages in TeamCity

Question: I recently started using NuGet to manage external packages. For now I have only needed it for NLog.
Everything works fine when I Build the project in VS 2012. However, I am trying out TeamCity as a CI server (I'm fairly new to CI) and it is giving me the following error:
[Csc] SomeNamespace\SomeClass.cs(10, 7): error CS0246:
The type or namespace name 'NLog' could not be found
(are you missing a using directive or an assembly reference?)

(this error is repeated throughout where ever I use NLog)
Now I did not include the 'packages/' folder in SVN, since I thought it was good practice not to include binaries and let MSBuild in TeamCity download these on its own. However it's clearly not doing that. I DO include the 'packages.xml' file in SVN.
What can I check to see what is going wrong?
Update
Thanks to @DavidBrabant I was nudged in the right direction. However, I now get the following error in TeamCity:
Package restore is disabled by default. To give consent, open the Visual Studio Options dialog,
click on Package Manager node and check 'Allow NuGet to download missing packages during build.'

However I'm not in Visual Studio but TeamCity, so I do not know how to set 'consent' to true! I tried to set RestorePackages to 'true' in the NuGet.targets file:
<RestorePackages Condition="  '$(RestorePackages)' == '' ">true</RestorePackages>

but this didn't work.
Update 2
To make it work I also set the following property NuGet.targets:
<RequireRestoreConsent Condition=" '$(RequireRestoreConsent)' != 'true' ">false</RequireRestoreConsent>

This made the build run succesfully!
Comment: Did you enable package restoration?
Comment: Mate, may be I am really stupid but it takes a lot of time for me to understod that last string must look like `false` I think it makes sense to specify the right string, not the inital version of it.
Comment: can you connect to Nuget repository from CI machine (can you ping it)?
Comment: Actually it is best practice to have everything you need to build your project in repository.
Comment: Thanks Seekeer, I changed it accordingly!
Answer: The enable package restore feature built into NuGet allows you to very easily set up the pre-build part of the workflow. To do so, right-click the solution node in Visual Studio's Solution Explorer, and click the Enable NuGet Package Restore option. Note that you need to have the NuGet Visual Studio Extension installed on your system. If you do, and you still don't see this menu item appear, you either already enabled this option, or you have a folder named .nuget in your solution directory.
After having set that option, you can now delete all sub-folders of your package installation directory, by default $(SolutionDir)\packages, except for the repositories.config file, and your solution should still compile properly. During compilation, you should see NuGet installation traces in the Visual Studio output window, and you should see the required NuGet packages reappear in the package installation directory as well.
Also see Using Nuget without committing packages.
Comment: This has now been superseded with automatic package restore integrated into MSBuild http://docs.nuget.org/docs/workflows/migrating-to-automatic-package-restore and http://www.xavierdecoster.com/migrate-away-from-msbuild-based-nuget-package-restore
Answer: Just to reiterate on update 2.  If you stumbled here looking for a quick fix to TeamCity not downloading NuGet packages, try changing this line
<RequireRestoreConsent Condition=" '$(RequireRestoreConsent)' != 'false' ">true</RequireRestoreConsent>

to this line
<RequireRestoreConsent Condition=" '$(RequireRestoreConsent)' != 'true' ">false</RequireRestoreConsent>

in your NuGet.targets file and it should work.
Comment: I don't have a nuget.target. It's not supposed to be there for package restore.
Answer: In TeamCity v8 I was able to solve the "restore package" error using an environment variable in TC.
See:
http://johanleino.wordpress.com/2013/03/19/using-teamcity-for-asp-net-development-part-2/
and
http://confluence.jetbrains.com/display/TCD7/Configuring+Build+Parameters#ConfiguringBuildParameters-SystemPropertiesandEnvironmentVariables
Setting env.EnableNuGetPackageRestore to "true" as an environment variable at the project level will fix the problem for all build configurations.  Feels a little bit better doing this than editing the NuGet.targets file imho.
Answer: Take a look at this post: http://johanleino.wordpress.com/2013/06/17/making-use-of-teamcitys-nuget-capabilities-part-2/
As described there I added first build step "NuGet Installer", made some coinfiguration and now packages are automatically restored.
Comment: I tried the environment variable fix above by Nate Rickard, but it didn't work. The fix here by @Bounz worked perfectly for me.
Comment: I agree. Similar info here: http://www.michael-whelan.net/restoring-nuget-packages-in-teamcity/

Include NuGet packages in TeamCity


Manually Calculate Youtube Video Bitrate

Question: I'm newbie to video processing world. My goal is to understand how YouTube posts 2,250-6,000 Kbps video bitrate for 720p @ 60fps video at https://support.google.com/youtube/answer/2853702?hl=en. I'm ignoring audio at the moment.
Here's my understanding:

Final Video Bitrate for 3x8bit* color depth = (Horizontal Length in pixels x Vertical Length in pixels) x (Frame rate in fps) x (3 * 8 bits encoding) x (Compression)

Therefore,
Final Video Bitrate for 1280x720p 60fps = (1280 * 720) x (60) x (24) x (compression factor)
= (921600) x (60) x (24) x (compression factor)
= 1.327Gbps x (compression factor)

Now, above result is same as what ToolStud.io** has. However, YouTube says that 720p60fps has maximum bitrate range of 6Mbps here. YouTube uses VP9 codec. I found this using debug info on YouTube video.
Question: If above calculation is correct, then the compression factor is about 216 1.3e9/6e6=216.66. Is that even possible? I think I'm missing something.
Can someone please guide me? I've spent about 2 hours on stackoverflow and found a few links (How to correctly estimate mp4 H.264 video size?, calculate bitrate from video video etc.), and I couldn't find any good explanation on this. Their focus is more on the size of the file rather than the video bit rate.
Thanks for your help.

*It seems YouTube recommends 3x8 bit = 24 bit color depth at https://support.google.com/youtube/answer/6039860?hl=en
**ToolStud.io provides a tool to compute uncompressed video bit rate.
Comment: What exactly is the question? Is it about bitrates, or is it about how that compression ratio is possible? Or is it something else?
Comment: Maybe start by reading this: https://github.com/leandromoreira/digital_video_introduction
Comment: @szatmary: We do know the bitrates from YouTube's site. So, the question is that if my calculation is correct, how does YouTube achieve such high compression rates. I'd appreciate your thoughts.
Comment: @szatmary: I've added "Question" in bold for clarity.
Answer: Yes, your numbers are correct. except the video is probably YUV420p, hence 12 bits per pixel. And yes this compression is very possible. Youtube is not doing anything special. You can set a bitrate of 2.5Mbps - 6Mbps with a tool like ffmpeg


Como ler o html de uma pagina que só carrega ao abrir no navegador em GOLANG

Question: Estou tentando ler o HTML da seguinte página (https://www.lojacorpoperfeito.com.br/pesquisa/?busca=suplemento&indice=0/), mas o problema é que o HTML dela só é carregado quando é aberto no navegador, ao entrar nela e apertar Ctrl + U você perceberá que há somente o javascript que carrega os produtos, mas no HTML ela fica como deveria ser para ser lida.
Atualmente estou abrindo as páginas com o "goquery".
Comment: Mostra o que você já tentou, pode ajudar...
Comment: tentei o de sempre, procurar por tags da página pra tentar ler o conteudo href, mas a página aberta no navegador é diferete da aberta pelo GO, assim não acho nenhuma tag que procuro
Answer: Você mesmo já responde a sua pergunta. Você diz "ao entrar nela e apertar Ctrl + U você perceberá que há somente o javascript que carrega os produtos".
O Golang, por padrão, não possui nenhum motor de Javascript e num contexto geral não há nenhum sentido em ter. Você provavelmente está obtendo o conteúdo da página usando a biblioteca de http, ela vai apenas obter o conteúdo daquela página, ou seja o mesmo HTML que você está vendo no CTRL + U. Se nele conter algum ,


Function to replace incorrectly spelled words with correctly spelled words in R?

Question: I've built a spell check function for a sample of 1000 rows to ensure its efficiency, using the 'hunspell' package and the Australian English dictionary. The spell-checker ignores abbreviations.
My actual data has close to 2 million lines, I therefore need to convert the 'for' loops into the 'apply' family functions.
I'm almost there I, but the last part isn't working.
Below are the original for loop functions:
for(i in 1:nrow(data_words))
{
  print(i)

  string1 <- data_words$title[i]
  string2 <- ""

  for(j in 1:sapply(strsplit(string1, " "), length))
  {
    w <- word(string1, j)

    # if word is not an abbreviation
    if (!isAbbreviation(w))
    {
      # correct word
      w <- correctText(w)
    }

    string2 <- paste0(string2, w, sep = " ")

    # add word in new column 'spell_check'
    data_words$spell_check[i] <- string2

  }
}

isAbbreviation <- function(x)
{
  abb = FALSE

  # all capitalised letters
  if(str_detect(x, "^[:upper:]+$"))
  {
    abb = TRUE
  }

  # dealing with abbs that end in an 's'
  b = str_extract_all(x, "(\\b[A-Z]+\\b)|\\b[A-Z]+s+\\b")
  list_empty = rlang::is_empty(unlist(b))

  if(!list_empty)
  {
    abb = TRUE
  }
  return(abb)
}

correctText = function(x)
{
  sapply(1:length(x), function(y)
  {
    # get misspelled words
    bad_words = hunspell(x[y], dict = "en_AU")[[1]]

    # if list of misspelled words is not empty
    if(length(bad_words))
    {
      for (i in 1:length(bad_words))
      {
        list_empty = rlang::is_empty(unlist(hunspell_suggest(bad_words[i],
                                                             dict = "en_AU")))
        # if suggestion list is not empty
        if(!list_empty)
        {
          # correct word
          good = unlist(lapply(hunspell_suggest(bad_words[i], dict = "en_AU"), `[[`, 1))
        }
        else
        {
          # else leave word is it is
          good = bad_words[i]
        }
        # replace mispelled words with corrected ones
        x[y] <<- gsub(bad_words[i], good, x[y])
      }
    }
  })
  x
}

Reproducible sample of phrases to be corrected:
library(dplyr)
library(stringr)
library(hunspell)
library(textclean)

sample <-
  c("Paaediatrics AsseSssing Febrile Infant Child", "Manuual Handling Traain Trainer", "Catheterise CTHs", "Labelinsfbsbinsajectables", "Mentouring", "techhnical", "Basic Life Support BSL", "BloodSafe cliniiical transfusion practice", "Astthma", "Zika virus preegnancy update")

data_words <- data.frame(matrix(nrow = length(sample), ncol = 1))
names(data_words) <- "title"
data_words$title <- sample
data_words <- as_tibble(data_words)

I had a go at it, please refer to the below functions:
# the abbreviation function remains the same

# function to correct a misspelled word
correctTheWord <- function(bad_word)
{
  # print(bad_word)

  if (!isAbbreviation(bad_word))
  {
    list_empty = rlang::is_empty(unlist(hunspell_suggest(bad_word,
                                                         dict = "en_AU")))

    if (!list_empty)
    {
      good = unlist(
        lapply(hunspell_suggest(bad_word, dict = "en_AU"),
               `[[`,
               1
        ))
    }
    else
    {
      good = bad_word
    }
  }

  else
  {
    good = bad_word
  }
}

# correct whole row function
correctText = function(x)
{
  sapply(1:length(x), function(y)
  {
    bad = hunspell(x[y], dict = "en_AU")[[1]]

    if (length(bad))
    {
      return(mgsub(x, bad, lapply(bad, correctTheWord)))
    }
    else
    {
      return(x)
    }
  })
}

# testing the first 2 titles
correctText("Paaediatrics AsseSssing Febrile Infant Child")
correctText("Manuual Handling Traain Trainer")

# this is not working
data_words$spell_check <-
  apply(data_words[, 1], 2,  correctText)

Also, can my functions can be simplified further?
Answer: This will identify and replace incorrectly spelt words with the correct spelling. Note that it will ignore abbreviations as desired, and it assumes all words are separated by a space.

# First, define isAbbreviation

isAbbreviation <- function(x)
{
  abb = FALSE

  # all capitalised letters
  if(str_detect(x, "^[:upper:]+$"))
  {
    abb = TRUE
  }

  # dealing with abbs that end in an 's'
  b = str_extract_all(x, "(\\b[A-Z]+\\b)|\\b[A-Z]+s+\\b")
  list_empty = rlang::is_empty(unlist(b))

  if(!list_empty)
  {
    abb = TRUE
  }
  return(abb)
}

sample <-
  c("Paaediatrics AsseSssing Febrile Infant Child", "Manuual Handling Traain Trainer",
    "Catheterise CTHs", "Labelinsfbsbinsajectables", "Mentouring", "techhnical",
    "Basic Life Support BSL", "BloodSafe cliniiical transfusion practice", "Astthma",
    "Zika virus preegnancy update", "Basic Labelinsfbsbinsajectables technical")

data_words <- data.frame(matrix(nrow = length(sample), ncol = 1))
names(data_words) <- "title"
data_words$title <- sample
data_words <- as_tibble(data_words)

correct_spelling <- function(text) {

  words <- text %>%
  str_split(" ") %>%
  .[[1]]

  abbreviation <- words %>% sapply(isAbbreviation) %>%
    unname

  # Abbreviations return false here, which is inconsequential since we don't replace them
  correct <- words %>%
    sapply(function(x) {hunspell_check(x, dict = dictionary("en_AU")) } ) %>%
    unname

  # Correct the word if incorrect and not abbreviation
  if(!any(!(!abbreviation) & (!correct))) {

    misspelled_and_not_abbreviation <- words[(!abbreviation) & (!correct)]

    suggestions <- misspelled_and_not_abbreviation %>%
      hunspell_suggest(dict = dictionary("en_AU"))

    suggested_words <- sapply(seq_along(suggestions), function(y, i)
      { ifelse(length(y[[1]]) == 0, misspelled_and_not_abbreviation[i], y[[i]][1]) },
      y=suggestions)

    words[as.logical((!abbreviation) * (!correct))] <- suggested_words

  }

  words %>% paste0(collapse = " ")

}

data_words$spell_check2 <- data_words$title %>% sapply(correct_spelling) %>% unname

which gives
data_words

#    title                                        spell_check2
#    <chr>                                        <chr>
#  1 Paaediatrics AsseSssing Febrile Infant Child Paediatrics Assessing Febrile Infant Child
#  2 Manuual Handling Traain Trainer              Manual Handling Train Trainer
#  3 Catheterise CTHs                             Catheterise CTHs
#  4 Labelinsfbsbinsajectables                    Labelinsfbsbinsajectables
#  5 Mentouring                                   Mentoring
#  6 techhnical                                   technical
#  7 Basic Life Support BSL                       Basic Life Support BSL
#  8 BloodSafe cliniiical transfusion practice    Blood Safe clinical transfusion practice
#  9 Astthma                                      Asthma
# 10 Zika virus preegnancy update                 Erika virus pregnancy update
# 11 Basic Labelinsfbsbinsajectables technical    Basic Labelinsfbsbinsajectables technical

Comment: Thank you! I think you skipped the part where, if hunspell suggestion list is empty for a misspelled word, skip correcting that word. Would you mind editing it please so I can accept your answer?
Comment: @Yeshyyy I will take a look. Do you have example input that I can test on?
Comment: I edited the sample. The 4th row word doesn't have a suggestion list. It should prompt an error there.
Comment: @Yeshyyy if the input was multiple words and hunspell had no suggestion for one of them, do you want the good words returned? E.g. "Basic Labelinsfbsbinsajectables technical" would return "Basic techincal" - is this correct?
Comment: Sorry forgot to precise that. I want the misspelled word returned too, therefore "Basic Labelinsfbsbinsajectables technical". If 'Basic' or 'technical' are mispelled, they should be corrected. E.g "Basic Labelinsfbsbinsajectables techhnical" returns "Basic Labelinsfbsbinsajectables technical"
Comment: @Yeshyyy I updated (using a technique [here](https://stackoverflow.com/questions/9950144/access-lapply-index-names-inside-fun) to access the index inside s/lapply)
Comment: @Yeshyyy yep, this `sapply(seq_along(suggestions), function(y, i) etc` allows us to access the index inside the `sapply` (index is `i`). I got curious to see if there's a better way, and it turns out there is. See [here](https://stackoverflow.com/a/62795861/5783745). I will use that way in the future!
Comment: thank you, did you say you've put the index counter in the function? Thanks for providing the link, I'll try adding it on my own.
Comment: @stevec, can you edit your code to include `isAbbreviation()`  custom function? I have similar situation but `isAbbreviation()` in the original function is not clear. Thanks.
Comment: @William no problems. Done
Comment: Hi @stevec, many thanks. However, there is an error message: `Error in if (str_detect(x, "^[:upper:]+$")) { :
  missing value where TRUE/FALSE needed`, due to NA. What I did was to remove `NA`, and it was fine, but that is not what I want. But, is it possible for `if (str_detect(x, "^[:upper:]+$"))` to skip `NA` values? I want to keep the `NA` because it is linked to other columns.


Resharper code annotations don't work when referencing the compiled dll

Question: Let's say I have the following class
public class MyClass
{
    [NotifyPropertyChangedInvocator("propertyName")]
    public void RespondToProperty(string propertyName)
    {
        //Some code here...
    }
}

When another project in the solution uses this class the annotations work. Resharper does auto-complete the caller class properties (as it should).
But when I reference the compiled dll, resharper doesn't auto-complete the property names as it should.
I also tried defining the following external annotation, but no luck:
<assembly name="MyAssembly">
    <member name="M:MyAssembly.MyClass.RespondToProperty(System.String,System.String)">
        <attribute ctor="M:JetBrains.Annotations.NotifyPropertyChangedInvocatorAttribute.#ctor" />
    </member>
</assembly>

Can the annotation work without referencing the project code, but using only the compiled dll?
Comment: Although this does not answer your question, if you are using a somewhat recent version of .NET, you should not have to pass the caller name as string. That's just going to be a chance to introduce errors without any gain. Look [here](http://stackoverflow.com/questions/25447549/using-string-constant-for-notify-property-changed/25447623#25447623) to see how to do this without passing the propertyname yourself as a string.
Comment: I know that. Also, I don't want it to behave like change notification. This attribute fits my needs, because I want to pass property name, but actualy it will never be the name of the "current" property
Answer: If you're using a recent version of the annotations - such as the default source implementation copied from the ReSharper 9 settings, or referencing the official nuget package - then they are not compiled into the resulting dll, by default.
The attributes are defined with [Conditional("JETBRAINS_ANNOTATIONS")] applied. This means that unless the JETBRAINS_ANNOTATIONS symbol is defined, the attributes don't get compiled in, but ReSharper can still use the attributes for analysis. If you define JETBRAINS_ANNOTATIONS, the attributes are compiled in to the resulting dll, and ReSharper will now be able to use the attributes when the resulting dll is used as a reference.
One thing to be aware of - if you're referencing the dll via the nuget package and you define JETBRAINS_ANNOTATIONS, then the resulting dll will now have a direct reference to JetBrains.Annotations.dll, and you'll need to ship JetBrains.Annotations.dll with your resulting dll. If you include the annotations via source, they're compiled into your resulting dll, and you don't have any extra binary references.


Find one set of solutions for the following system:

Question: Find one set of solutions for the following system:
\begin{cases}
1+a^2+d^2=3+b^2+e^2=3+c^2+f^2 \\
1+ab+de=0 \\
ac+df=0 \\
bc+ef=0 \\
\end{cases}
Answer: One way is to follow the mathematics of wishful thinking. Here, I wishfully think that I can choose many things to be zero. For instance, if $d = e = c = 0$, then the last two equations hold trivially and we are instead left with the system
$$\begin{cases} 1 + a^2 = 3 + b^2 = 3 + f^2 \\
1 + ab = 0
\end{cases}$$
If $f = b$, then $f$ is covered. So really, we just have the pair $1 + ab = 0$ and $1 + a^2 = 3 + b^2$. Fortunately, the first means that $a = -1/b$. Plugging into the other gives
$$1 + \frac{1}{b^2} = 3 + b^2.$$
Rearranging and calling $B = b^2$ gives
$$B^2 + 2B - 1 = 0,$$
with solutions $B = -1 \pm \sqrt 2$. Let's choose the positive square root, $B = 1 + \sqrt 2$. Then $b = \sqrt{1 + \sqrt 2}$, and $a = -1/b$.
So in total,
$$\begin{cases}
a = \frac{-1}{\sqrt{1 + \sqrt 2}}\\
b = \sqrt{1 + \sqrt{2}} \\
c = 0 \\
d = 0 \\
e = 0 \\
f = \sqrt{1 + \sqrt{2}}
\end{cases}$$
is a solution. Of course, this is not linear-algebra, nor algebra-precalculus, but I liked the challenge of finding a single solution to an otherwise untenable problem.
Answer: Setting $a = -d$ and $c = f$ and $ b = -e $, we are left with the top 2 equations.
Subbing in some values, these equations become,
$1 + 2d^2 = 3 + 2e^2 = 3 + 2c^2$ and $1 + 2de = 0$.
From this, $2de = -1 \iff d = \frac{-1}{2e}$.
Thus, we have $1 + \frac{1}{2e^2} = 3 + 2e^2 = 3 + 2c^2$.
Then, $1 = 4e^2 + 4e^4 \iff e^2 = \frac{1}{\sqrt{2}} - \frac{1}{2} \iff e = \pm\sqrt{\frac{1}{\sqrt{2}} - \frac{1}{2}}$.
Now we can solve for $d$ and $c$. But we already have $d$ and $c = e$ from inspection.
We have $$\begin{equation} \begin{aligned} e = \pm\sqrt{\frac{1}{\sqrt{2}} - \frac{1}{2}} \\ d = \frac{-1}{2e} \\ b = -e \\ a = -d \\ c = f = e\end{aligned} \end{equation} .$$


Is sequel pro available for AWS RDS with a private subnet?

Question: I create MariaDB on AWS RDS. At this time, I put the RDS on the private subnet, and the connection was successful in phpmyadmin on ec2.
And I create an instance that Bastion host Instance, and install MariaDB. So I can manage DB on terminal(mac).
And now I want to manage my DB easily with sequel pro, but of course I could not connect to RDS with endpoint/user/password.
What I hava to do for access RDS using Sequel pro?
Answer: You can connect the RDS using Sequel pro via an SSH tunnel through your Bastion host.


How to fill a dataset after getting a gridview?

Question: I have a gridview which has many columns.. the columns are got separately and displayed in a gridview.
now i need to sort this gridview but i cannot do that.... i have found a way but i will need to get the gridview in a datatable or a dataset.... is there a a way to do this?
DataSet ds= new DataSet();
ds = Gridview1.????

please help..
Answer: One way to do this would be to use a DataGridView and use the DataSource property of this control:
OleDbConnection conn = new OleDbConnection(connection);

OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = new OleDbCommand("select * from my_table", conn);
DataSet dataset = new DataSet();

// fill the data set using the query defined in the adapter
adapter.Fill(dataset);

// fill the grid with the data set
DataGridView1.DataSource = dataset.Tables[0];

Answer: You can create a new class to represent each row in the table, and bind to a list of objects of that class. Then to fix the sorting you can wrap your data source in a SortableBindingList. You can use the files PropertyComparer.cs and SortableBindingList.cs from this zip file and use it like this:
gridView1.DataSource = new SortableBindingList<cLineItem>(list);

I've tested this with a DataGridView. I assume it also works with a GridView.
Answer: How are you populating the GridView, with a SqlDataSource (or similar) in the ASPX or with code in the .cs codebehind?
It is possible to iterate through the child controls and cast objects if you know the exact make-up but that is not fun. If there is any way to copy the data before binding it to the GridView that would be more typical.
Answer: I would create a shared method or maybe even a class (depending on how often you would need this functionality) that would be responsible fore receiving a set of data collections (however you are retrieving these columns of data), and compiling it into a coherent typed datatable. This would add all of the built-in sorting features you would get and would also give you the ability to have a singular compiled source for your total data. Then you could use the DefaultView to sort/mix/filter this data without affecting its original nature.


Generate PDF and send mail

Question: I have need to send pdf via drupal mail. I want to use tcpdf library but when im trying to use example i have error:
http: //..../tcpdf_example/download/simple
Fatal error: Call to a member function DrupalInitialize() on a non-object in C:\xampp\htdocs\drupalac_gw\sites\all\modules\tcpdf\tcpdf_example\tcpdf_example.pages.inc on line 55
  $html = theme('tcpdf_example_basic_html');

  // Never make an instance of TCPDF or TCPDFDrupal classes manually.
  // Use tcpdf_get_instance() instead.
  $tcpdf = tcpdf_get_instance();
  /* DrupalInitialize() is an extra method added to TCPDFDrupal that initializes
  *  some TCPDF variables (like font types), and makes possible to change the
  *  default header or footer without creating a new class.
  */
  $tcpdf->DrupalInitialize(array(
    'footer' => array(
      'html' => 'This is a test!! Bottom of the page',
    ),
    'header' => array(
      'callback' => array(
        'function' => 'tcpdf_example_default_header',
        // You can pass extra data to your callback.
        'context' => array(
          'welcome_message' => 'Hello, context array!',
        ),
      ),
    ),
  ));

then somehow...
  ...
  $attachment = array(
  'filecontent' => $tcpdf->Output('', 'E');
  'filename' => 'test.txt',
  'filemime' => 'text/plain',
  );

  switch($key) {
  case 'notice':
  $langcode = $message['language']->language;
  $message['subject'] = 'example submission from' . $account;
  $message['body'][] =''. $account .' has submitted an example.';
  $message['params']['attachments'][] = $attachment;
  break;
  ...

What i need to correct to get rid of error?
Answer: Ok First off all Installing drupal TCPDF module is not enough to have working pdf-s. We are also obligated to download TCPDF libray from http //www.tcpdf.org/ and place it to drupal files so that library will be avaible like this

C:\xampp\htdocs\drupalac_gw\sites\all\libraries\tcpdf\tcpdf.php

above will solve:

Fatal error: Call to a member function DrupalInitialize()

With working pdf library sending emails with attachments is easy i have like this:
drupal_mail('module', 'notice', "to@mail","", array(), "from@mail");

where:
function module_mail($key, &$message, $params) {
  $attachment = array(
    'filecontent' => generatePdf("S"),
    'filename' => 'example-filename',
    'filemime' => 'application/pdf',
  );

  switch($key) {
    case 'notice':
      $langcode = $message['language']->language;
      $message['subject'] = 'example submission from ';
      $message['body'][] ='my example.';
      $message['params']['attachments'][] = $attachment;
      break;
  }
}

And where:
function generatePdf($where="S") {
  $pdf = tcpdf_get_instance();

  $pdf->setFontSubsetting(true);

  // set font
  $pdf->SetFont('freeserif', '', 12);

  $pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 008', PDF_HEADER_STRING);

  // set header and footer fonts
  $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
  $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));

  // set default monospaced font
  $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);

  // set margins
  $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP+10, PDF_MARGIN_RIGHT);
  $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
  $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);

  // set auto page breaks
  $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);

  // set image scale factor
  $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
  return $pdf->Output('example_008.pdf', $where);
}

Above is now my working example :)

Generate PDF and send mail


SQLSTATE[42S22]: Column not found: 1054 Unknown column in laravel

Question: I'm trying to make a shopping cart with laravel and am having trouble with one of the methods
this is the error:

SQLSTATE[42S22]: Column not found: 1054 Unknown column 'pedidos__produtos.pedidos_id' in 'where clause' (SQL: select id_produto, sum(total) as Total, count(1) as qtd from pedidos__produtos where pedidos__produtos.pedidos_id = 1 and pedidos__produtos.pedidos_id is not null group by id_produto order by id_produto desc)

I searched the entire code, but I did not refer this field "pedidos_id" anywhere
This error happens when I call "$pedidos[0]->pedido_produtos," in Carrinhocontroller.php
These are the related methods and migrations:
CarrinhoController.php
<?php

 namespace App\Http\Controllers;

 use Illuminate\Http\Request;
 use App\Pedidos;
 use Illuminate\Support\Facades\Auth;

 class CarrinhoController extends Controller
 {
    function __construct(){
    $this->middleware('auth');
}

public function index(){

    $pedidos = Pedidos::where([
        'id_user' => Auth::id()
    ])->get();

    dd([
        $pedidos,
        $pedidos[0]->pedido_produtos,
        //$pedidos[0]->pedidos_produtos[0]->produto
    ]);
    return view('carrinho.index', compact('pedidos'));

 }
}

Pedidos.php
<?php

 namespace App;
 use Illuminate\Database\Eloquent\Model;

 class Pedidos extends Model
 {
    public function pedido_produtos(){
    return $this->hasMany('App\Pedidos_Produtos')
    ->select( \DB::raw('id_produto, sum(total) as Total, count(1) as qtd'))
    ->groupBy('id_produto')
    ->orderBy('id_produto', 'desc');
 }
}

Pedidos_Produtos.php
<?php

  namespace App;

  use Illuminate\Database\Eloquent\Model;

  class Pedidos_Produtos extends Model
   {
     public function produto(){
       return $this->belongsTo('App\Produtos', 'id_produto', 'id');
     }
 }

Migration from Pedidos:
<?php

 use Illuminate\Support\Facades\Schema;
 use Illuminate\Database\Schema\Blueprint;
 use Illuminate\Database\Migrations\Migration;

 class CreatePedidosTable extends Migration
 {
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('pedidos', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('id_user')->unsigned();
        $table->foreign('id_user')->references('id')->on('users');
        $table->timestamps();
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('pedidos');
 }
}

and from pedidos_produtos
<?php

 use Illuminate\Support\Facades\Schema;
 use Illuminate\Database\Schema\Blueprint;
 use Illuminate\Database\Migrations\Migration;

 class CreatePedidosProdutosTable extends Migration
 {
/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('pedidos__produtos', function (Blueprint $table) {
        $table->increments('id');
        $table->integer('id_pedido')->unsigned();
        $table->integer('id_produto')->unsigned();
        $table->decimal('total', 6, 2)->default(0);
        $table->timestamps();

        $table->foreign('id_pedido')->references('id')->on('pedidos');
        $table->foreign('id_produto')->references('id')->on('produtos');
    });
}

/**
 * Reverse the migrations.
 *
 * @return void
 */
public function down()
{
    Schema::dropIfExists('pedidos__produtos');
 }
}

Can Anyone help me with that?
Answer: The problem you are experiencing is probably to do with this line:
return $this->hasMany('App\Pedidos_Produtos')

If you do not explicitly tell Laravel what the IDs are called on each table when defining a hasMany relationship, it will assume that the id is {table_name}_id which is where the pedidos_id is coming from.
Try adding the foreign and local keys to the hasMany, something like this:
return $this->hasMany('App\Pedidos_Produtos', 'id_pedido', 'id')

Answer: It generates automatically if foreignKey attribute is not defined on hasMany method.
it generates field name from classname_id pattern. Also localKey default value is class PK.
public function hasMany($related, $foreignKey = null, $localKey = null)

You can use like this.
 return $this->hasMany('App\Pedidos_Produtos','id_pedido')


Use views to display not voted polls

Question: I'm using polls (from core) to make some enquetes.
Is there a way to use views to display only the polls that a user has not voted yet?
I didn't find anything on google. The only solutions where for Drupal 6. And I'm using drupal 7.
Thanks in advance =)
Comment: Have you actually tried? Can you, for example, create a view that simply shows all the pools?
Comment: Yes. But it shows the polls as full nodes. It does not give any field that I could test if the user has voted or not. The only filter that I see is if the poll is open or closed.
I've used views with relationships before, and with the poll module I am really lost. =P
Answer: First I tried to use the hook_views_pre_execute.
<?php
function hook_views_pre_execute(&$view) {
    $uid = $GLOBALS['user']->uid;

    //gets one the poll and return it
        $query = db_select('node', 'n');
        $query->fields('n');

        $subquery = db_select('poll_vote', '');
        $subquery->fields('poll_vote', array('nid'));
        $subquery->condition('poll_vote.uid', $uid);

        $query->condition('n.nid', $subquery, 'NOT IN');
        $query->condition('type', 'poll');
        $query->condition('status', 1);
        $query->range(0, 1);

    $view->build_info['query'] = $query;
    $view->build_info['count_query'] = $query;
}

But when I tried to use the pager, it had too many bugs. It felt like a hack. So in the end I used:
<?php
/**
 * Returns a page with one not voted poll
 * @return [array] [drupal page array]
 */
function one_poll_page(){

    $page[] = "";
    $uid = $GLOBALS['user']->uid;

    //gets one the poll and return it
        $query = db_select('node', 'n');
        $query->fields('n');

        $subquery = db_select('poll_vote', '');
        $subquery->fields('poll_vote', array('nid'));
        $subquery->condition('poll_vote.uid', $uid);

        $query->condition('n.nid', $subquery, 'NOT IN');
        $query->condition('type', 'poll');
        $query->condition('status', 1);
        $query->range(0, 1);

        $result = $query->execute();

    foreach ($result as $record) {
      //saves the rendered poll node to the array
      $node = node_load($record->nid);
      $view = node_view($node, 'full');
      $rendered = drupal_render($view);
      $page['#markup'] .= $rendered;
    }

    return $page;
}

Because I can then control exactly what the page does.

Use views to display not voted polls


Render headline of first content element in Grid Container different

Question: Is it possible to render the headline of the first content element within a Grid Elements container different in the fluid_styled_content template or via TypoScript?
Comment: You mean with a different HTML? Maybe you could simply solve it with CSS?
Comment: That's how I did it now, but the possibility to have different markup would be appreciated.
Answer: There are several virtual fields within cObj->data that are created during the rendering process of Gridelements. So you might want to check for keys with the prefix parentgrid_
Additionally you can use
<code>data = cObj:parentRecordNumber
</code>
to get the position of an element within the rendering order. Since Gridelements uses the sorting field of tt_content for the rendering of children and the parentRecordNumbers are handled correctly between different container columns, you should get the correct value - 1 - for the first element of each column there.


Are post-hoc adjusted analyses more valid than initial analyses?

Question: Many papers design a methodology to detect a difference between $2$ groups regarding a primary outcome. This result is then given a $p$ value to denote statistical significance. Some papers then go on to adjust their analysis for age, sex, weight, height etc., and report a statistically non-significant difference between the $2$ groups for the same primary outcome.
Does the statistically non-significant value from the post-hoc adjusted analysis supersede the initial analysis of the primary outcome which isn't adjusted for confounders?
Comment: Deciding to control or adjust for these factors is better done before collecting or analysing the data.
Comment: The difference between "significant" and "not significant" is not itself statistically significant http://www.stat.columbia.edu/~gelman/research/published/signif4.pdf
Answer:
Does the statistically insignificant value from the post-hoc adjusted analysis supercede the initial analysis of the primary outcome which isn't adjusted for confounders?

What I assume you're trying to ask is "which outcome do I believe?  Should I believe that there is a difference between groups larger than what sampling variation could explain under the null?".  The answer is "it depends on what is being conditioned on".
If:

Adjustment factors satisfy the back door criterion under your causal model, and/or
The exposure is independent of adjustment factors, but adjustment factors are possible causes of the outcome

then the adjusted analyses is likely a better analyses.  Adjusting for confounders will remove any confounding in the estimate, and adjusting for covariates which are unrelated to the exposure but causes of the outcome can reduce variance in the estimate.
You have to be careful here though, because careless adjustment can open backdoors and introduce bias by conditioning on a collider in the causal diagram.  This is why I say "it depends".
Consider an extreme cases where the unadjusted estimate might be preferable to the adjusted estimate.  A randomized experiment is run, but the investigators condition on a collider thereby introducing a spurious correlation between exposure and outcome.
In general, adjustment should be preferred to unadjusted but only if the adjustment makes sense.  Else, you get what Richard McElrath calls "causal salad".
Answer: I think Demetri's answer hits the nail on the head, but I would like to add that how this is accomplished is also very important. If the scientists pre-specified that there would be differences between groups, but then post-hoc explain their results in terms of other confounders/colliders, then there need to be one of two conditions met:

If they hypothesized this in advance, they need to state this explicitly. This is really the only way this sort of analysis can be considered confirmatory, as they are not jumping on chance findings after rummaging through the data.
If they did not hypothesize this in advance, they need to state that this was an exploratory finding. There is nothing wrong with this and should honestly be more commonplace anyway (see Tong, 2019 for a useful discussion on how most science is actually exploratory anyway).

Reference
Tong, C. (2019). Statistical inference enables bad science; statistical thinking enables good science. The American Statistician, 73(sup1), 246–261. https://doi.org/10.1080/00031305.2018.1518264
Comment: Good points ! (+1)
Answer: Yes.  The results of the new model will override any prior results where we did not control for confounders or other relevant predictors.  Each variable will explain some portion of the variance in the outcome.  However these variances will often overlap. The effect of one variable may be better explained by the effect of another variable.  I've seen this occur very frequently in studies looking at health or race.  When we do not account for these confounding variables, we will often get type 2 errors.


Twitter Typeahead Ajax results undefined

Question: I'm building a autocomplete with Twitter typeahead using an ajax JSON call to my PHP file to get some data but it keeps displaying the following in the dropdown result list:
undefined
undefined
undefined
but when i do:
alert(data);

I get the right data displayed but somehow the autocomplete list keeps displaying undefined, I've read and tried multiple things by some articles here on StackOverflow, but I can't seem to get it to work.
I have to following jquery code:
      $('.item-name .typeahead').typeahead(null,{
      source: function (query, process) {
        $.ajax({
          url: 'ajaxItems.php',
          type: 'POST',
          dataType: 'JSON',
          data: 'query=' + query,
          success: function(data) {
            // alert(data);
            process(data);
          }
        });
      }
    });

And my ajaxItems.php has the following code for testing purpose:
<?PHP
$results = array();

$results[] = 'jeans';
$results[] = 'sweater';

$json =  json_encode($results);
print_r($json);
?>

The JSON output is as follows:
["jeans","sweater"]

I hope someone can shine some light on what I'm doing wrong or point me in the right direction.
edit
I am using the following typeahead file:
http://twitter.github.io/typeahead.js/releases/latest/typeahead.bundle.js
Comment: Where can i find this? This is just the typeahead or bootstrap process function to display the results.
Comment: @Rikesh, process() is a part of the typehead code
Comment: Sorry, then im stucked :( It **is** the typeahead originating from twitter bootstrap?
Comment: Yes its the twitter typeahead.
Comment: Is it bootstrap 2.x, 3.x or is it https://blog.twitter.com/2013/twitter-typeaheadjs-you-autocomplete-me ?? Was assuming it was one of the BS version :(
Comment: Its bootstrap 3x and just the official twitter typeahead plugin from twitter.
Comment: I think typehead.js is a mess. Why not take out the small piece of code from a bootstrap 2.3.x that actually was logic an useable and working, and use that instead? Have done that myself several times, when I didnt needed bootstrap but just wanted the typeahead. I have really tried to solve your problem, but I guess you have to create a "bloodHound" and so on, the code and docs is very unclear (to mee). @Amit Joki is quite right that it is failing in the $.map attempt, the code expects some very specific input. Another solution, rewrite _render in typeahead.js
Answer: I had the exact same problem. To fix it I had to return an array containing key/value pairs with the key 'value' like this:
[{'value': 'first', 'value': 'second', 'value': 'third'}]

I don't think the typeahead docs make it clear enough but I believe it is the displayKey option which is set to 'value' by default.
Comment: THANK YOU!  I had the same issue.  ASP.Net MVC application returning an array of strings from a LINQ query: "return Json((from i in elementArray select i.StringProperty), JsonRequestBehavior.AllowGet);"  This returns: ["A String", "Another String", "Other String"].  Typehead has only accepted the format: [{Name: "A String"}, {Name: "Another String"}]  This is achieved by changing the LINQ select to an anonymous type: "... select new {Name = i.StringProperty}" and then specifying a displayKey on the typehead declaration: ".typehead({displayKey: 'Name', source: ..."
Comment: This answer has fixed my issue, as well.
Answer: The closest answer is ian's though it does not really work (only returns last value). Working answer is :
[{'value': 'first'}, {'value': 'second'}, {'value': 'third'}]

Answer: I had similar problems using source: and I ended up using remote:.
In your case, it would be something like this:
$('.item-name .typeahead').typeahead({
    remote: 'ajaxItems.php?query=%QUERY'
  });

Note that I deleted null on typeahead(null,{ since I think it's not necessary but I might be wrong. Obviously, you'll have to use $_GET instead of $_POST but I think it's much easier this way.
Answer: The problem is the typeahead is expecting a array with suggestions. Not the JSON !
use $.makeArray() like this:
success: function(data){
     process($.makeArray(data));
}

if it doesn't , may be JSON.parse() should help ?
Mark it as answer if helpful :)
Comment: It does not work, but you are right - it is there it goes wrong. I have failed to solve the problem with a JSON from $.ajax
Comment: I tried that, didn't made any different, still undefined undefined.
Comment: @Adriaan did you try JSON.parse() ?
Comment: @davidkonrad did you try JSON.parse() ?


DJANGO PYINSTALLER ISSUE

Question: I'm trying to compile a Django (3) applications that uses pymongo and channels. I followed steps in a ticket in stackoverflow, I got the .exe file but when I try tu run it using app.exe runserver I got this error :
\AppData\Local\Temp\_MEI149762\Test_Project\settings.pyc'
Failed to execute script manage
I've found nothing on the net discussing this issues.
HELP PLEASE.
Answer: Did you try to add --onefile parameter ?
Comment: Thanks for your reply, Yes I just did it but it does not work neither :/ , still same issue. Would you need my manage.spec and the tree structure of my project?
Comment: Hey! Not working neither. The problem was that django 3.** is not fully supported by pyinstaller so I downgrade and it works.

DJANGO PYINSTALLER ISSUE


Can MySQL 5.6 be used with Drupal 6 and php 5.2.17

Question: A server admin is looking to update the production mysql from the latest version 5.0 to latest 5.6. We are running a Drupal/Pressflow 6.22 and php 5.2.17. I believe this is going to bring on the apocalypse when it comes to things not working, but I need some concrete reasons on what may break and why.
Do anyone have any experience running a drupal 6 on mysql 5.6? Or PHP 5.2 with MySQL 5.6?
I know mysql 5.1 in acted strict mode in MySQL.
Anyone have any insight into if these will play nice with Drupal 6 and it's modules?
Comment: Is there anything in particular you are worried about in 5.6?  All of my Drupal 6 sites work fine with 5.5.
Comment: Isisgate the time it took to get a single comment in your questions you could have tested it yourself. No matter what answers you're gonna get from DSE, aren't you gonna test it first?
Comment: What version of PHP are you using in conjunction? The sites use a lot of contributed modules and I am worried that this update would cause issues. As well if the stuff that uses mysql_connect would continue to work or mysqli would be required? There are also some legacy custom applications that are existing. So I am wanting to make sure this goes smoothly as there aren't enough developer cycles to handle massive reworks right now.
Comment: I am trying to find out if anyone knows of compatibility issues or things to look out for ahead of this. I have 15 different apps using that server, some drupal some not. I am a consultant brought in to help fix their broken development process and environments. We are working to restructure the environments in a controlled manner, as right now they are making changes to production with no dev or test servers working. So in a meeting today a server admin was looking to make the update in the next couple days like it's no big deal, and I am trying to put the breaks on it for proper testing
Comment: So I'm not in a position to quickly test it across all applications as we are just starting to learn a what projects are where, get code version controlled, and building new server environments.
Comment: @Isisagate But you surely only need to test this against Drupal, not "all applications"? This is something you need to test yourself, taking the word of a random stranger on the internet is equally as bad as not bothering to think about testing at all if you think about it
Comment: @Isisagate - in your comment on mikeytown2's answer, you mentioned coming back to post your findings - did you end up going further down the path of moving to 5.6?  If so, were there any issues / solutions you found with regards to compatibility?
Answer: MySQL 5.6 works fine; using the mysqli driver. PHP 5.4 works after fixing a couple of notices, and php 5.2 works without any modifications.
In your settings.php file change $db_url = 'mysql://...' to $db_url = 'mysqli://...' to use the mysqli driver; it's that simple.
Comment: Epitaph: I was able to dig up enough information online to present a compelling case for not trying to rush out an update the all the servers without testing but to plan it into the current upgrade project. So I won't know for a few months when we get to that phase of the project for sure if your answer is correct, but when I get there I will post a definitive.
Comment: @ScottBonner have enough months passed yet? Anything to report?


Pivotal HAWQ pg_restore :unexpected end of file

Question: When  trying to restore backup in Hawq database first time. Getting this error.
Input command
I tried running this command
<code>[gpadmin@mdsby backup]$ pg_restore -d gpadminrestore gpadmin_10-01-2017
</code>
Error :
pg_restore: [custom archiver] unexpected end of file
Answer: probably wrong format.
try to cat the backup file. if it is all sql statement, you need to use psql -f to load the data.
BTW, if the data size is big, don't use pg_backup and pg_restore. Those backup and restore go through master and will be slow.


É possível programar usando a API WinRT sem recorrer ao XAML?

Question: Há algum tempo linguagens declarativas tomaram conta do desenvolvimento de softwares para criação de interfaces gráficas com o usuário. Os exemplos mais óbvios são o framework WPF que usa a XAML (eXtensible Application Markup Language) como linguagem declarativa e a biblioteca Qt framework com sua QML (Qt Markup Language).
Ao contrário da Qt que não expõe publicamente o código (classes) responsável pela efetiva execução da interface, obrigando o uso do QML no novo estilo de GUI (QtWidgets é o oposto) e não permite um modo de programação imperativa ao invés de declarativa (pelo menos não permite fazer 100% em código), o WPF permite dois modos de programação: 1) declarativamente através do XAML, que é o modo mais utilizado e 2) programação imperativa/orientada a objeto com código através das classes expostas, afinal a XAML é toda construída em cima das classes existentes, contando até com classes auxiliares para converter valores de XAML para código. Grosso modo, há uma relação 1:1 entre classes e seus membros e as marcações do código XAML e seus atributos.
Apesar de ostensivamente demonstrado que a XAML deve ser utilizada prioritariamente - isto ter várias vantagens - e até mesmo algumas pessoas acreditarem que é a única forma, a documentação, livros sobre o WPF, e alguns sites até específicos sobre o assunto(en) (também aqui(en) e no SO original(en)) indicam claramente a possibilidade de usar apenas a programação não declarativa.
Eu tenho um software que gera todas as telas on-the-fly, através de código. Adaptando este software para o Windows 8, seria até um absurdo em tempo de execução eu gerar o XAML para depois o framework "converter em código" para ser executado.
Não conheço bem a tecnologia e não sei se valeria aprender para muito mais tarde descobrir se não atenderá minha necessidade.
Já procurei exaustivamente na internet de forma geral e em sites específicos se isso também é possível e nada encontrei. Não consegui achar nada que indicasse que é possível ou mesmo que não é. Não fui capaz de achar um exemplo sequer mostrando apenas código. Certamente achei muito código que auxilia o XAML da WinRT mas nada que indique que 100% da interface pode ser feita sem XAML.
Minha dúvida é se há possibilidade de usar a WinRT para construção de GUI sem usar nada de XAML, só com código, e é claro, onde posso achar informações/documentação a respeito, se possível com exemplos. Em outras palavras, 100% do código responsável pela construção e interação da GUI está exposta ao programador? Algum exemplo aqui seria muito bem-vindo.
Não está em debate a utilidade da XAML. Para esse caso específico seria um exagero.
Pra mim vale o mesmo para a WinUI.
Comment: Para WinRT é possível usar HTML em vez de XAML. Se você só criar objetos via javascript, acredito que isso responde a sua pergunta (sem XAML e só via código). Mas acredito que essa não é a resposta que você está procurando, se for, irei transferir para a seção de respostas.
Comment: @MarcosZolnowski Você até tem razão que não é bem isso que procuro, mas não deixa de ser uma resposta que pode ajudar quem pode usar dessa forma e isso é importante também. Não aceitaria como **A** resposta, mas é uma possível. Você tem conhecimento se essa é a única forma, ou não arriscaria dizer isso?
Comment: Segue a url de um video, que apesar de antigo, trata sobre o que seria o passado, presente e futuro do XAML:
http://channel9.msdn.com/Shows/Going+Deep/Rob-Relyea-Theres-Something-About-XAML
Answer: WPF não tem nada a ver com HTML!
É possível utilizar WPF sem XAML (XAML na verdade sempre é traduzido para C#).
É tão simples quanto Windows Forms:
Ex.: Vamos supor que eu queira fazer uma página (não confundir com página web) para um app Windows 8 com um label e um botão, com binding:
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Data;

namespace App1
{
public class TestPage : Windows.UI.Xaml.Controls.Page
{

    public TestPage()
    {
        var stackPanel = new StackPanel();
        var label = new TextBlock { Text = "Hello World" };
        var button = new Button();
        var buttonCaption = new TextBlock();

        buttonCaption.SetBinding(TextBlock.TextProperty, new Binding { Path = new Windows.UI.Xaml.PropertyPath("Text"), Source = label });
        button.Content = buttonCaption;

        stackPanel.Children.Add(label);
        stackPanel.Children.Add(button);

        var layoutRoot = new Grid
        {
            HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center,
            VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center,
        };

        layoutRoot.Children.Add(stackPanel);
        Content = layoutRoot;
        }

        }

}
Respondendo as dúvidas do comentário:
Isso é WinRT (ou seja, Silverlight para Windows Store Apps).
Não tenho referências além da documentação do XAML. Tudo o que o XAML faz, existe uma classe correspondente. Se você tem Grid, StackPanel, Button, etc. no XAML, fatalmente as terá no namespace do WPF (seja ele qual versão for). Isso inclui até recursos como binding e static resources.
Não há "lugar com autoridade que afirme...", mas isso é intrínseco. C# não compila nem roda XAML, ele no máximo interpreta e monta a tela com os objetos contidos no namespace Windows.UI.Xaml. Não há nada que exista em XAML que não exista neste namespace (afinal, no final das contas, não existe XAML).
Você pode realizar qualquer tarefa desta forma, embora isso seja bem ruim. XAML facilita a escrita e realiza alguns atalhos que, para fazer manualmente, você deverá recorrer à documentação. Um exemplo disto é colocar um texto dentro de um botão. No XAML, é simples. Em código você deve explicitamente especificar que o conteúdo do botão é um TextBlock (algo como um Label).
Você está confundindo um pouco as coisas. XAML é apenas o nome do markup (ele nunca é executado de fato, sempre é convertido ou interpretado). O fato de o namespace se chamar XAML é porque a MS intencionou o WPF para ser utilizado com um auxílio da linguagem de markup e não existe absolutamente nenhum motivo para não se utilizar isso, pelo menos em parte. O binding do WPF é suficientemente poderoso para evitar criar componentes na mão. Mas, claro, .net é um framework que te dá liberdade pra fazer o que quiser.
Comment: Muito interessante. Acho que está chegando onde quero. Vamos à algumas dúvidas: você disse "É possível utilizar WPF sem XAML". Você entendeu que eu sei disso e que a minha dúvida é sobre fazer o mesmo com a WinRT? Esse seu exemplo foi tirado de onde? Tem alguma referência onde posso achar mais exemplos? Tem algum lugar com autoridade que afirme que dá para usar WinRT 100% com código e zero XAML? Coisas mais complexas podem ser feitas desta forma também? Tem alguma ideia porque isso tudo está em namespace Xaml quando ele não está sendo usado? Se puder editar para colocar essas dúvidas...
Comment: Tem algum link para documentação que mostre alguns exemplos como o que você postou para eu poder fazer alguns estudos? Tenho visto só XAML. Por isso fiquei achando que só o XAML era possível. Parece que escondem que pode usar código. Ao contrário do WPF que a documentação frequentemente mostra as duas formas.
Answer: Segundo o Marcos Zolnowski:
Para WinRT é possível usar HTML em vez de XAML. Se você só criar objetos via javascript, acredito que isso responde a sua pergunta (sem XAML e só via código). Mas acredito que essa não é a resposta que você está procurando, se for, irei transferir para a seção de respostas.

Eu acrescentaria que é possível fazer a criação dinâmica de elementos assim:
        // Popula contatos do XElement com informações de Contacts.
        XElement contacts =
            new XElement("Contacts",
                new XElement("Contact1",
                    new XElement("Name", "Patrick Hines"),
                    new XElement("Phone", "206-555-0144"),
                    new XElement("Address",
                        new XElement("Street1", "123 Main St"),
                        new XElement("City", "Mercer Island"),
                        new XElement("State", "WA"),
                        new XElement("Postal", "68042")
                    )
                ),
                new XElement("Contact2",
                    new XElement("Name", "Yoshi Latime"),
                    new XElement("Phone", "503-555-6874"),
                    new XElement("Address",
                        new XElement("Street1", "City Center Plaza 516 Main St."),
                        new XElement("City", "Elgin"),
                        new XElement("State", "OR"),
                        new XElement("Postal", "97827")
                    )
                )
            );

        // Cria o primeiro controle TextBlock.
        // Note que o elemento precisa declarar dois namespaces XAML.
        XElement textBlock1 = XElement.Parse(
                @"<TextBlock
    xmlns='http://schemas.microsoft.com/client/2007'
    xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml'
    TextWrapping= 'Wrap'
    Width = '400'
    Canvas.Top = '10'
    Text=''/>");

        // Pega o primeiro elemento filho da árvore de contatos do xml.
        XElement contact1 = contacts.Element("Contact1");

        // Ajusta o valor do último atributo "Text"
        // com o conteúdo dos contatos da árvore do xml.
        textBlock1.LastAttribute.SetValue(contact1.ToString());

        // Pega o segundo elemento filho da árvore de contatos do xml.
        XElement contact2 = contacts.Element("Contact2");

        // Cria o segundo controle TextBlock.
        // Note que o elemento precisa declarar dois namespaces XAML.
        XNamespace xmlns = "http://schemas.microsoft.com/client/2007";
        XElement textBlock2 = new XElement(xmlns + "TextBlock",
            new XAttribute(XNamespace.Xmlns + "x", "http://schemas.microsoft.com/winfx/2006/xaml"),
            new XAttribute("Canvas.Top", 250),
            new XAttribute("Width", "600"),
            new XAttribute("Text", contact2.ToString())
            );

        // Adiciona o controle TextBlock à página
        LayoutRoot.Children.Add(XamlReader.Load(textBlock1.ToString()) as UIElement);
        // Adiciona o controle TextBlock à página
        LayoutRoot.Children.Add(XamlReader.Load(textBlock2.ToString()) as UIElement);

Comment: Agradeço o exemplo, mas realmente ainda não é o que eu estou procurando. Eu gostaria de evitar criar tudo isso. Talvez não tenha jeito. Depois preciso perguntar sobre como é feito no iOS e Android usando Xamarin.
Comment: @bigown Explique um pouco melhor o que você precisa então, por favor. Eu tinha entendido que você queria poder criar os componentes todos dinamicamente sem o XAML. Isso é bem verboso mesmo quando é feito tudo programaticamente.
Comment: Quando ao Xamarin.iOS e o Xamarin.Android abra uma pergunta lá que eu respondo. Esses eu uso sempre e com alguma frequencia preciso criar na mão os componentes.
Comment: Essa perguntas eu vou fazer depois com calma. O que eu queria é programar como no WPF, onde você acessa diretamente as classes que vão executar o código. O XAML é uma camada sobre essas classes. No caso que você mostrou o XAML está sendo usado. Indiretamente, mas é ele que está comandando a execução. Eu não sei se é possível. Mas nunca encontrei alguém dizendo claramente que não é. A sua solução pode até ser usada se não houver outra forma, mas ela é mais ou menos o que eu sabia que dava pra fazer. Pode ser um pouco difícil entender porque quase ninguém usa o WPF programaticamente.
Comment: Eu acho que isso é o mais programaticamente que tem como fazer. Até onde eu sei o WPF foi construído para ter uma camada de abstração da View que é o HTML ou XAML. Creio não ser possível fazer com ele. Mas se vai fazer tudo programaticamente por que usar o WPF, por que não usar o WinForms ou outro Framework?
Comment: Posso afirmar por experiência que dá para fazer 100% programaticamente em WPF e é quase igual fazer para WinForms que é uma tecnologia que não atendia bem as necessidades. Agora há a necessidade de criar uma camada de apresentação para outros dispositivos onde nem o WinForms, nem o WPF funcionam. E de qualquer forma seria melhor usar sempre algo nativo. Há muita desinformação sobre o WPF. E descobri que falta informação sobre o WinRT. Espero que não falte sobre o Xamarin. Mas isso é assunto para mais tarde :)
Comment: No Xamarin você vai usar as APIs nativas, então a informação que vai precisar é como criar Views no Android e no iOS e depois só portar a linguagem. As  bibliotecas são as mesmas e mapeadas 1-1. Você já pensou em coisas mais multiplataforma tipo o GTK ou outras parecidas?
Comment: Prefiro as APIs nativas. Na prática o GTK só é bom no Linux. E a maioria dos bindings dele estão defasados. Mas não estou tão preocupado agora porque é um produto que está parado por enquanto.


MVC Update Model Properties Using JQuery

Question: It's been a while since I did any MVC/JQuery. I'm looking for a solution or a better way of achieving this.
To simplify things, I have a Model with the following properties:
public IEnumerable<XmlInputFieldModel> XmlFields { get; set; }
public IEnumerable<string> BusinessObjectFields { get; set; }
public IEnumerable<XmlSchemaField> MappedFields { get; set; }

public class XmlInputFieldModel
{
    public string XmlElement { get; set;}

    public string XmlValue { get; set; }
}

public class XmlSchemaField
{
    public string XmlElement { get; set; }

    public string BusinessObjectField { get; set; }
}

In my View, I'm providing a list of the XmlField Elements and their Values, and for each XmlField I have a dropdown to select a BusinessObjectField, shown below:
@foreach(var item in Model.XmlFields)
{

            @Html.DisplayFor(i => item.XmlElement)

            @Html.DisplayFor(i => item.XmlValue)

            @Html.DropDownListFor(m => m.BusinessObjectFields, new SelectList(Model.BusinessObjectFields, item.XmlElement))

}

    <input type="button" name="Save" id="Save" />

What I want to happen when I click Save is to populate my MappedFields property with the values from the given Element and the chosen dropdown Field value.  I've attempted this through the script below, but I can't work out how to get from the Key/Value array into my Model.

[HttpPost]
public ActionResult SetMappedFields(string Val)
{
    string newVal = Val;
    return this.RedirectToAction(x => x.Index());
}

I explored the Ajax route (commented code), but can't seem to get this to find the controller action.  The above view and script sits in a partial view, where other properties of the base Model are populated.
@CSharper - I've updated the code above, and it's still not hitting the controller :( (I'm using the default HomeController from a starting MVC4 application).  My Error function on the script returns "Error: Not Found".
Answer: Ajax isn't finding the controller because your not defining Ajax data: and giving it the correct parameters. So which in turn
url: "Home/SetMappedFields" + "?model=" + model + "&fields=" + mappedFields,
is not right. If you wanted to call that method from the address bar or using window.open() that would work but ajax expects the parameters differently
(Inside the event that you want to fire the Ajax call.)
var dataToSend = {
        Val : "Working"
    };

    $.ajax({
        url: "/Home/AjaxCall",
        type: "POST",
        data: dataToSend,
        success: function (result) {

        },
    });
})

    [HttpPost]
    public ActionResult AjaxCall(string Val)
    {
        return View("Index");
    }

var dataToSend = {
            param1: value,
            param2: value
        };

This is how you can reference multiple parameters
Comment: I've marked your answer, as you have been the most helpful. I have however completely re-written everything to simplify it greatly and use editor templates.
Comment: Hi @CSharper, I just tried your Ajax call above, and it's still not finding it. [HttpPost]
        public ActionResult SetMappedFields(XmlSchemaModel model, Array fields)
Comment: Ok it's because it's expecting an entire model class and an array. Do me a favor and just remove the "complex" parameters, replace it with a simple string, and hardcode the dataToSend param, just so we can see it work.
Comment: I just tried it with a string, and it's still not getting to the controller. Does it work properly in a partial view?
Comment: It doesn't matter whether it is in a partial view or not. Are you referencing JQuery correctly?
Comment: Not sure what you mean.  My _Layout page has references to jquery-2.0.3.js and min, but in case my partial wasn't loading the layout, I added references there too.
Comment: I'm gonna copy and paste the exact code I'm using, and it is calling the controller action
Comment: I've updated my original post, unfortunately it's still not working.  I appreciate your patience and suggestions so far.  I've worked with ajax before and never had many problems, I'm sure it's something simple I'm missing
Comment: I would also do an alert after your "buslist" each function and make sure their is no errors there and the js is getting passed that point. I don't know why else the Ajax won't work
Comment: I've tried that already, as I put an alert on dataToSend to make sure it was being populated. I'm all out of ideas too. I'll keep plugging away at it
Comment: Is your save button causing a form submit?? Maybe the form submit and ajax are getting hung up for some reason
Comment: Doesn't appear so.  I copied the Ajax call into a function for .busoblist on change, and this also fires the Error: Not Found.  I'll have a look at the routing now, to make sure that Home/SetMappedFields is sufficient to find the method.
Comment: Ok, I setup a javascript debugger and followed it through the whole AJAX call, and found the problem.  It didn't like Home/SetMappedFields, as the resulting URL was Home/Home/SetMappedFields.  I removed the Home from my url and it now hits the controller.  Never seen that before... :)


Removing Duplicate DataTrigger Code from XAML

Question: I am creating a lot of DataGrids in my WPF Application in the XAML file.
Generally, each DataGrid I make look like this:
<DataGrid x:Name="DamageTakenData" HorizontalAlignment="Left" VerticalAlignment="Top" Width="506" Height="172" Canvas.Left="30" Canvas.Top="228">
                <DataGrid.CellStyle>

                    </Style>
                </DataGrid.CellStyle>
         </DataGrid>

I have about 6 or 7 of those DataGrids, each of them in a different tab. Each DataGrid has the same DataGrid.CellStyle
<DataGrid x:Name="PlayerDeathData" HorizontalAlignment="Left" Margin="27,35,0,0" VerticalAlignment="Top" Height="155" Width="626" Grid.ColumnSpan="2">
                <DataGrid.CellStyle>

                    </Style>
                </DataGrid.CellStyle>
            </DataGrid>

How would I go about eliminating the duplicate code for specifying DataGrid.CellStyle?
Attempts
Looking at this question: Prevent Duplicate Code In XAML, I've tried something similar. I made a static resource:
<Window.Resources>

    </Style>
</Window.Resources>

And then, I use the static resource like this:
<DataGrid x:Name="DamageDealtData" HorizontalAlignment="Left" VerticalAlignment="Top" Width="506" Height="163" Canvas.Left="30" Canvas.Top="35">
                <DataGridCell Style="{StaticResource DataGridStyle}"/>
            </DataGrid>

This approach doesn't work either. Because it seems to be creating only 1 DataGridCell and styling it.
How would I go about doing that?
Answer: You have the resource correct, you are just applying it incorrectly.
It should be done like this:
<DataGrid x:Name="DamageDealtData" HorizontalAlignment="Left"
VerticalAlignment="Top" Width="506" Height="163" Canvas.Left="30"
Canvas.Top="35" DataGrid.CellStyle="{StaticResource DataGridStyle}">
    ...
</DataGrid>

When you used <DataGridCell Style="{StaticResource DataGridStyle}"/> you were creating a single DataGridCell and setting its style to the style you created. By setting DataGrid.CellStyle instead, you apply that style to ALL cells of the grid.
Comment: Always glad to help!


services display for search index based view

Question: I am building a search page using view. the view get results from search index created and have indexed nodes and it works fine and display results as expected
the problem comes when trying to add services display for the same view it only display as in the picture
please help to make services display from views based on search api
Answer: You may use the "block" display on your view instead of "services" display to avoid this issue as the views has many issues with search api and services views


Every linear application is sum of linear applications of rank 1

Question: Let $V$ and $W$ finite dimensional vectorial spaces over a field $\mathbb{K}$. I must prove that every linear application from $V$ to $W$ is sum of linear applications of rank $1$.
The suggestion given states that just fixed a basis of the image and we consider the projections on the lines generated by a single basis element.
I can't understand how this is true, could someone explain it to me? Thanks
Answer: Let $\{e_i\}$ be a basis of $V$ and let $T$ be a linear application $T:V\to W$.  Then for any $v=x_1e_1+\dots x_ne_n$ you have
$$
Tv=x_1T(e_1)+\dots x_nT(e_n).
$$
The applications $T_i$ that send $v$ to $x_iT(e_i)$ have rank one, since their images are the spans of $T(e_i)$. So you have $T=T_1+T_2+\dots +T_n$ where each $T_i$ has rank one.
Another way to look at this: every matrix is the sum of matrices containing one of the columns of the original and zeroes in the remaining positions. These clearly have rank one.
Comment: Thanks for the answer. But in this case you have not chosen a basis for the image, but only a system of generators for the image, is that okay?