text:
Q: CSRF Failed 403 when authenticated to admin, but same works fine when not authenticated Another newbie type of an issue, I guess.
AngularJS using PATCH method raises:
"CSRF Failed: CSRF token missing or incorrect."

Cookies:
Cookie:arp_scroll_position=0; sessionid=ix36xi2u9bijih2x1npswjlranfm7wjy; csrftoken=w54t2iWlU6oYBoYpeoZtkeWHluAgFmZOIbNeVsfo9pGgCD8OnPzoCdxJNmbfl2aM

But only when I'm authenticated in another tab into Admin panel.
Same request works fine if I'm not logged in.
Cookie:arp_scroll_position=0; csrftoken=w54t2iWlU6oYBoYpeoZtkeWHluAgFmZOIbNeVsfo9pGgCD8OnPzoCdxJNmbfl2aM

This is very simple JSON push:
.factory('MyName', function($resource) {
  return $resource('/api/resource/:pk/', {'pk': '@pk'}, {
      'update': {
        method: 'PATCH' // this method issues a PUT request
      },
    });
});

With JSON content such as {"pk":3,"gt":"angularjs-auth"}
At the same time, another "html" with separate AngularJS app defined works fine for both situations when authenticated and when not authenticated, but this time I'm using dropzone which probably does workaround the problem transparently for me.
.factory('UploadFile', function($resource) {
  return $resource('/api/files/:pk', {'pk': '@pk'}, {
        'save': {
            method: 'POST',
              transformRequest: transformImageRequest,
            headers: {'Content-Type':undefined}
        },
    });
});

Not Authenticade POST (not PATCH, but probably this doesn't make a difference):
Cookie:arp_scroll_position=0; csrftoken=w54t2iWlU6oYBoYpeoZtkeWHluAgFmZOIbNeVsfo9pGgCD8OnPzoCdxJNmbfl2aM

What I'm seeing here is that content is multipart/form-data which itself includes also CSRF (is this the trick fixing the issue?)
------WebKitFormBoundaryXUBwTTaSIiKwTvyx
Content-Disposition: form-data; name="csrfmiddlewaretoken"

And authenticated:
Cookie:sessionid=kaw00iaxwpq3puxcc94dy9v8yxf7rfyh; csrftoken=49KSaqsZykxuYRvJsEhpKlCyqP1ZnVQAubO4bPKs0u2qEcm0hpVvutMoIdUW9gV6; arp_scroll_position=0

------WebKitFormBoundaryelub0ZsHFENNbUmp
Content-Disposition: form-data; name="csrfmiddlewaretoken"

dqeieK1GdnYD9QTVRbt4ibQ6q0u8o8mkDsiuf9j9FxtzPbKcGW7a2j0WIon5atrQ

Looking for help and suggestions what to change as I'm certainly missing some tiny part to get it fixed.
{% csrf_token %} is part of html and tried to include it in  section  too.
At the same time, Postman works fine using "No auth" and "Basic Auth". Certainly it is not mirror situation as AngularJS PATCH, but it seems like I'm doing some silly mistake as only my AngularJS PATCH doesn't work.
EDIT 1
Following default elements, including authentication are part of settings.py
MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

A: With requests to Django REST Framework views, you don't usually need CSRF token...
Unless you're authenticated using session/cookie based authentication (doesn't matter if it's in admin or not).
You can get around it in two ways other than sending multipart/form-data with your CSRF token.
First way is to use X-CSRFToken header to pass your token in request (your JS logic must set that header when making requests)
Second way is to use another authentication method. It can be used together with cookie/session based one if it's higher on list of authentication backends in your settings file. REST Framework will pick first one from the list that is valid and discard others, so session/cookie based one won't get a chance to enable CSRF verification.

A: Thanks GwynBleidD for help and hints provided.
Dunno how it works, that I can be pulling my hair for hours trying to fix issue and once question posted/asked I'm finding solution.
In this case, all what I needed to do is following in my AngularJS code:
myApp.config(['$httpProvider', function($httpProvider) {
    $httpProvider.defaults.xsrfCookieName = 'csrftoken';
    $httpProvider.defaults.xsrfHeaderName = 'X-CSRFToken';
}]);

This fixed issue completely and works perfectly fine.
@GwynBleidD, I'd be glad to hear which authentication methods are recommended.


text:
Q: New ways to transfer data between view controllers I have a problem with transferring data between UIViewController and I don't find answers in former questions.
Situation : I have a first viewController ('CalViewController') which allows users to input data. Then I calculate with those datas a number (named 'calories' for example). The next views are two UIViewController (DrinksViewController & FoodViewController)displayed in a TabBarControllerand I need value of 'calories'.
What I've tried :
-prepareForSegue method : It doesn't work because segues (symbol in storyboard is a link between two points) in a TabBarControllerare not as others (symbol in storyboard is arrow through a door).
-'didSelectViewController' method : This method is not "activated" to display the first view of a TabBarController. So I succeed to transfer Calories to my second ViewController in the TabBarController (ie FoodViewController) but not to my first viewController in the TabBarController (ie DrinksViewController).
-call the "original" value : Here what I've done in CalViewController (after imported DrinksViewController.h)
DrinksViewController *dvc = [[DrinksViewController alloc] init];
dvc.caloriesImported = 456;

I don't know why this third way is not working.
Problem : My value of Caloriesis not transferred from CalViewController to DrinksViewControlller. Any ideas ?

A: If I understand your problem correctly, the following should work in the first
view controller CalViewController:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([[segue identifier] isEqualToString:@"yourSegueToTabBarIdentifier"]) {
        UITabBarController *tbc = [segue destinationViewController];
        DrinksViewController *dvc = tbc.viewControllers[0];
        dvc.caloriesImported = 456;
        FoodViewController *fvc = tbc.viewControllers[1];
        fvc.someProperty = someValue;
    }
}

Note that
DrinksViewController *dvc = [[DrinksViewController alloc] init];
dvc.caloriesImported = 456;

cannot work because it allocates a new instance of DrinksViewController that
is completely unrelated to the instance used by the tab bar controller.

A: You need to get the instances that are already in the tab bar controller. You do that with self.tabBarController.viewControllers[n], where n would be 0,1, or 2 depending on which controller you're trying to access.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Change the error site for previously existing SE-1.0 site that will probably be replaced by an Area 51 proposal Or: What will happen to the questions at SE-1.0 physics.SO?
The site http://physics.stackexchange.com is no longer available, will its contents be migrated to the Physics proposal when it gets started? In any case, the error message should be changed into some thing like

The Q&A site physics.stackexchange.com will restart soon, please support it's relaunch: http://area51.stackexchange.com/proposals/1908/physics


text:
Q: LIKE is faster than FULLTEXT search in MySQL I have a table called documents that have around 30 columns, around 3.5 million rows at a size of about 10GB. The most important columns are:
system_id, archive_id, content, barcodes, status and notes.
As you can see this is a multi-tenant application where each tenant is a system and references through system_id.
I have 2 indexes on this table where the first one is a BTREE and have the columns system_id, archive_id and status in it's index.
The other one is a FULLTEXT index containing the columns content, barcodes and notes.
I have two different tenants that I want to highlight. The first one (Customer A) has system_id = 1 and have say 1000 records in the documents table. The second one (Customer B) have system_id = 2 and say 400 000 records in this table.
The LIKE query for Customer A is:
SELECT *
FROM documents
WHERE system_id = 1 AND
      CONCAT_WS(' ',content,barcodes,notes) LIKE '%office%' AND
      status = 100

The above query will run in about 0.02 seconds. If I run a similar query but with the FULLTEXT search like
SELECT *
FROM documents
WHERE system_id = 1 AND
      MATCH(content,barcodes,notes) AGAINST ('office' IN BOOLEAN MODE) AND
      status = 100

This operation takes around 4 seconds?! I have read that the FULLTEXT search index should be a lot quicker than LIKE.
If I run the same queries but for Customer B (that has 400 000 records in the documents table) the LIKE search is a little bit slower than FULLTEXT but not with a lot.

*

*What can the reason for this be?

*Should I go with LIKE or FULLTEXT search in above situation (8GB RAM database server)?

I'm a little bit confused of why my queries with FULLTEXT search is taking so long. The text in content is probably not just words that a normal person would use because it's OCR-read from the document so there will be a lot of different words that might blow up the index?

A: The EXPLAINs will show that the fast query is using your index on system_id and status, not the LIKE.  It was fast, not because of LIKE, but because of that filtering.
And the slow query decided to use the FULLTEXT index because the Optimizer is too dumb to realize that lots of rows contain "office".
LIKE, especially in conjunction with CONCAT_WS is not faster than FULLTEXT.


text:
Q: Is there a benefit to using LoadLibrary instead of linking? Using dependency walker I noticed some apps that definitely use Direct3D 11, but only link to Direct3D 9's library dll.
Do I gain something by linking? Would there be any benefit in using LoadLibrary?
Why might I choose one method over the other?

A: As I think, if you link DLL statically to your application you will not be able to even start the application if any DLL is missing. In case of manual LoadLibrary the application can start, check DLL availability and write message to log, show a good error description to user or even use another DLL set, e.g. another version of DLLs with different names instead of newest ones.


text:
Q: A double sum and its relation to a simple sum, is this an identity for any complex number $S=a+i b$ and any integers n and t? Does:
$$\sum _{m=1}^t \lim_{s\to \text{S}} \, \zeta (s) \sum _{k=(m-1) n+1}^{m n} \frac{1-\text{If}[k \bmod n=0,n,0]}{k^{s-1}}$$
equal:
$$\lim_{s\to \text{S}} \, \zeta (s) \sum _{k=1}^{n t} \frac{1-\text{If}[k \bmod n=0,n,0]}{k^{s-1}}$$
for any complex number $S$ and any integers $n$ and $t$?
Which as a Mathematica program is:
S = 1.23456789 + I*9.87654321
Monitor[Table[
  Chop[N[Table[
      Sum[Limit[
        Zeta[s]*Sum[(1 - If[Mod[k, n] == 0, n, 0])/
           k^(s - 1), {k, (m - 1)*n + 1, m*n}], s -> S], {m, 1,
        t}], {n, 1, 12}]] -
       Table[
     Limit[Zeta[s]*
       Sum[(1 - If[Mod[k, n] == 0, n, 0])/k^(s - 1), {k, 1, t*n}],
      s -> S], {n, 1, 12}]], {t, 1, 6}], t]

Some background information on the problem.
Mathematica knows that logarithms can be calculated as:
$\log(n) = \lim_{s\to 1} \, \left(1-\frac{1}{n^{s-1}}\right) \zeta (s)$
Logarithms can be added to give the logarithm of the product of their argument,
$\lim_{s\to 1} \, \left(1-\frac{1}{6^{s-1}}\right) \zeta (s) = \lim_{s\to 1} \, \left(1-\frac{1}{2^{s-1}}\right) \zeta (s) + \lim_{s\to 1} \, \left(1-\frac{1}{3^{s-1}}\right) \zeta$
$\log(6) = \log(2) + \log(3)$
This works only when the limits lets $s \to 1$.
Trying the same for example with the limit letting $s \to 2$, it fails, as can be seen in this example:
$\lim_{s\to 2} \, \left(1-\frac{1}{6^{s-1}}\right) \zeta (s) = \lim_{s\to 2} \, \left(1-\frac{1}{2^{s-1}}\right) \zeta (s) + \lim_{s\to 2} \, \left(1-\frac{1}{3^{s-1}}\right) \zeta$
which gives us:
$\lim_{s\to 2} \, \left(1-\frac{1}{6^{s-1}}\right) \zeta (s) = \lim_{s\to 2} \, \left(1-\frac{1}{2^{s-1}}\right) \zeta (s) + \lim_{s\to 2} \, \left(1-\frac{1}{3^{s-1}}\right) \zeta (s)$
which evaluated is:
$\frac{5 \pi ^2}{36} = \frac{\pi ^2}{12} + \frac{\pi ^2}{9}$
but then we would have:
$\frac{5 \pi ^2}{36} = \frac{7 \pi ^2}{36}$
which is not true.
Looking at the logarithm above again, as a zeta function limit, we have:
$\log(n) = \lim_{s\to 1} \, \left(1-\frac{1}{n^{s-1}}\right) \zeta (s)$
In this question it was shown in the answer that logarithms have these numerators in their Dirichlet series:
$$1-\text{If}[k \bmod n=0,n,0]$$
which as a matrix is:
$$\begin{bmatrix} 0&0&0&0&0&0&0 \\ 1&-1&1&-1&1&-1&1 \\ 1&1&-2&1&1&-2&1 \\ 1&1&1&-3&1&1&1 \\ 1&1&1&1&-4&1&1 \\ 1&1&1&1&1&-5&1 \\ 1&1&1&1&1&1&-6 \end{bmatrix}$$
which is an infinite matrix where each row is the numerators in the Dirichlet series that converges to $\log(n)$ for $s=1$.
In the zeta function limit for logarithms the part within the parentheses $\left(1-\frac{1}{n^{s-1}}\right)$ in $\log(n) = \lim_{s\to 1} \, \left(1-\frac{1}{n^{s-1}}\right) \zeta (s)$ will go towards zero in the limit:
$\lim_{s\to 1} \, \left(1-\frac{1}{n^{s-1}}\right) = 0$
In a different matrix:
$$\displaystyle T = \begin{bmatrix} +1&+1&+1&+1&+1&+1&+1 \\ +1&-1&+1&-1&+1&-1&+1 \\ +1&+1&-2&+1&+1&-2&+1 \\ +1&-1&+1&-1&+1&-1&+1 \\ +1&+1&+1&+1&-4&+1&+1 \\ +1&-1&-2&-1&+1&+2&+1 \\ +1&+1&+1&+1&+1&+1&-6 \end{bmatrix}$$
where $\Lambda(n) = \displaystyle \sum\limits_{k=1}^{\infty}\frac{T(n,k)}{k}$,
and where $\Lambda(n)$ is the von Mangoldt function as proven in the answer to this question, we have the triangle:
$$\displaystyle \begin{bmatrix} +1 \\ +1&-1&=0 \\ +1&+1&-2&=0 \\ +1&-1&+1&-1&=0 \\ +1&+1&+1&+1&-4&=0 \\ +1&-1&-2&-1&+1&+2&=0 \\ +1&+1&+1&+1&+1&+1&-6&=0 \end{bmatrix}$$
where we see that the row sums are also zero.
Looking again at the earlier matrix we see the same thing (with exception of the first row, but $\Lambda(0) = 0$ anyways):
$$\displaystyle \begin{bmatrix} 0=0 \\ 1&-1=0 \\ 1&1&-2=0 \\ 1&1&1&-3=0 \\ 1&1&1&1&-4=0 \\ 1&1&1&1&1&-5=0 \\ 1&1&1&1&1&1&-6=0 \end{bmatrix}$$
writing zeta function limits of this latter matrix, and we have:
$$\lim_{s\to 1} \, \left(\frac{1}{1^{s-1}}-\frac{1}{2^{s-1}}\right) \zeta (s) = \log (2)$$
$$\lim_{s\to 1} \, \left(\frac{1}{1^{s-1}}+\frac{1}{2^{s-1}}-\frac{2}{3^{s-1}}\right) \zeta (s) = \log \left(\frac{9}{2}\right)$$
$$\lim_{s\to 1} \, \left(\frac{1}{1^{s-1}}+\frac{1}{2^{s-1}}+\frac{1}{3^{s-1}}-\frac{3}{4^{s-1}}\right) \zeta (s) = \log \left(\frac{32}{3}\right)$$
$$\lim_{s\to 1} \, \left(\frac{1}{1^{s-1}}+\frac{1}{2^{s-1}}+\frac{1}{3^{s-1}}+\frac{1}{4^{s-1}}-\frac{4}{5^{s-1}}\right) \zeta (s) = \log \left(\frac{625}{24}\right)$$
$$\lim_{s\to 1} \, \left(\frac{1}{1^{s-1}}+\frac{1}{2^{s-1}}+\frac{1}{3^{s-1}}+\frac{1}{4^{s-1}}+\frac{1}{5^{s-1}}-\frac{5}{6^{s-1}}\right) \zeta (s) = \log \left(\frac{324}{5}\right)$$
$$\lim_{s\to 1} \, \left(\frac{1}{1^{s-1}}+\frac{1}{2^{s-1}}+\frac{1}{3^{s-1}}+\frac{1}{4^{s-1}}+\frac{1}{5^{s-1}}+\frac{1}{6^{s-1}}-\frac{6}{7^{s-1}}\right) \zeta (s) = \log \left(\frac{117649}{720}\right)$$
with the sequence: $1, 2, 9/2, 32/3, 625/24, 324/5, 117649/720...$ looking up numerators and denominators in the oeis we find sequences: http://oeis.org/A036505 and: http://oeis.org/A095996
Multiplying by $n!$ and searching for the sequence:
$1, 4, 27, 256, 3125, 46656, 823543...$
we find when we scroll down to sequence https://oeis.org/A177885 the following formula:
$$\frac{1}{2}+\frac{2 \pi  i \exp (1) \left(n-\frac{11}{8}\right)}{\exp (1) W\left(\frac{n-\frac{11}{8}}{\exp (1)}\right)}$$
involving the Lambert_W function for a good approximation of the n-th Riemann zeta zero.
$W(x)$ or LambertW is undocumented in Mathematica as said in Mathworld, and the ProductLog[x] command is used instead. There is also a functional relation between the sequence from the zeta limits and the $1, 4, 27, 256, 3125, 46656, 823543...$ sequence which is as follows:
$$\frac{x}{W(-x)} = x \sum _{n=1}^{\infty } \frac{1}{(W(-x)+1)^n}$$
Changing the argument $-x$ to $x$ we have the function used in the zeta zero approximation formula.
This warrants some further investigation of the sequence $1, 2, 9/2, 32/3, 625/24, 324/5, 117649/720...$  from the zeta function limits.
Setting the denominators equal to $\exp(n)^{s-1}$:
$$\lim_{s\to 1} \, \left(\frac{1}{\exp ^{s-1}(1)}-\frac{1}{\exp ^{s-1}(2)}\right) \zeta (s) =1$$
$$\lim_{s\to 1} \, \left(\frac{1}{\exp ^{s-1}(1)}+\frac{1}{\exp ^{s-1}(2)}-\frac{2}{\exp ^{s-1}(3)}\right) \zeta (s)=3$$
$$\lim_{s\to 1} \, \left(\frac{1}{\exp ^{s-1}(1)}+\frac{1}{\exp ^{s-1}(2)}+\frac{1}{\exp ^{s-1}(3)}-\frac{3}{\exp ^{s-1}(4)}\right) \zeta (s)=6$$
$$\lim_{s\to 1} \, \left(\frac{1}{\exp ^{s-1}(1)}+\frac{1}{\exp ^{s-1}(2)}+\frac{1}{\exp ^{s-1}(3)}+\frac{1}{\exp ^{s-1}(4)}-\frac{4}{\exp ^{s-1}(5)}\right) \zeta (s)=10$$
$$\lim_{s\to 1} \, \left(\frac{1}{\exp ^{s-1}(1)}+\frac{1}{\exp ^{s-1}(2)}+\frac{1}{\exp ^{s-1}(3)}+\frac{1}{\exp ^{s-1}(4)}+\frac{1}{\exp ^{s-1}(5)}-\frac{5}{\exp ^{s-1}(6)}\right) \zeta (s)=15$$
$$\lim_{s\to 1} \, \left(\frac{1}{\exp ^{s-1}(1)}+\frac{1}{\exp ^{s-1}(2)}+\frac{1}{\exp ^{s-1}(3)}+\frac{1}{\exp ^{s-1}(4)}+\frac{1}{\exp ^{s-1}(5)}+\frac{1}{\exp ^{s-1}(6)}-\frac{6}{\exp ^{s-1}(7)}\right) \zeta (s)=21$$
which appear to be the triangular numbers, $\frac{n(n+1)}{2}$.
Reversing the triangular matrix:
$$\displaystyle \begin{bmatrix} 0=0 \\ 1&-1=0 \\ 1&1&-2=0 \\ 1&1&1&-3=0 \\ 1&1&1&1&-4=0 \\ 1&1&1&1&1&-5=0 \\ 1&1&1&1&1&1&-6=0 \end{bmatrix}$$
into:
$$\displaystyle \begin{bmatrix} 0=0 \\ -1&1=0 \\ -2&1&1=0 \\ -3&1&1&1=0 \\ -4&1&1&1&1=0 \\ -5&1&1&1&1&1=0 \\ -6&1&1&1&1&1&1=0 \end{bmatrix}$$
which is the triangle https://oeis.org/A167407 in the OEIS.
Taking successive matrix powers of this triangle and reversing back we seem to get the whole Pascal triangle as zeta function limits.
$$\lim_{s\to 1} \, \left(\frac{1}{\exp ^{s-1}(1)}-\frac{1}{\exp ^{s-1}(2)}\right) \zeta (s)=1$$
$$\lim_{s\to 1} \, \left(\frac{1}{\exp ^{s-1}(1)}+\frac{2}{\exp ^{s-1}(2)}-\frac{3}{\exp ^{s-1}(3)}\right) \zeta (s)=4$$
$$\lim_{s\to 1} \, \left(\frac{1}{\exp ^{s-1}(1)}+\frac{2}{\exp ^{s-1}(2)}+\frac{3}{\exp ^{s-1}(3)}-\frac{6}{\exp ^{s-1}(4)}\right) \zeta (s)=10$$
$$\lim_{s\to 1} \, \left(\frac{1}{\exp ^{s-1}(1)}+\frac{2}{\exp ^{s-1}(2)}+\frac{3}{\exp ^{s-1}(3)}+\frac{4}{\exp ^{s-1}(4)}-\frac{10}{\exp ^{s-1}(5)}\right) \zeta (s)=20$$
$$\lim_{s\to 1} \, \left(\frac{1}{\exp ^{s-1}(1)}+\frac{2}{\exp ^{s-1}(2)}+\frac{3}{\exp ^{s-1}(3)}+\frac{4}{\exp ^{s-1}(4)}+\frac{5}{\exp ^{s-1}(5)}-\frac{15}{\exp ^{s-1}(6)}\right) \zeta (s)=35$$
$$\lim_{s\to 1} \, \left(\frac{1}{\exp ^{s-1}(1)}+\frac{2}{\exp ^{s-1}(2)}+\frac{3}{\exp ^{s-1}(3)}+\frac{4}{\exp ^{s-1}(4)}+\frac{5}{\exp ^{s-1}(5)}+\frac{6}{\exp ^{s-1}(6)}-\frac{21}{\exp ^{s-1}(7)}\right) \zeta (s)=56$$
More in line with logarithms of $n=1,2,3,4,5...$ is to consider the following zeta function limits:
$$\lim_{s\to 1} \, \left(\frac{1}{\exp ^{s-1}(1+2)}-\frac{1}{\exp ^{s-1}(2+2)}\right) \zeta (s)=1$$
$$\lim_{s\to 1} \, \left(\frac{1}{\exp ^{s-1}(1+3)}+\frac{1}{\exp ^{s-1}(2+3)}-\frac{2}{\exp ^{s-1}(3+3)}\right) \zeta (s)=3$$
$$\lim_{s\to 1} \, \left(\frac{1}{\exp ^{s-1}(1+4)}+\frac{1}{\exp ^{s-1}(2+4)}+\frac{1}{\exp ^{s-1}(3+4)}-\frac{3}{\exp ^{s-1}(4+4)}\right) \zeta (s)=6$$
$$\lim_{s\to 1} \, \left(\frac{1}{\exp ^{s-1}(1+5)}+\frac{1}{\exp ^{s-1}(2+5)}+\frac{1}{\exp ^{s-1}(3+5)}+\frac{1}{\exp ^{s-1}(4+5)}-\frac{4}{\exp ^{s-1}(5+5)}\right) \zeta (s)=10$$
$$\lim_{s\to 1} \, \left(\frac{1}{\exp ^{s-1}(1+6)}+\frac{1}{\exp ^{s-1}(2+6)}+\frac{1}{\exp ^{s-1}(3+6)}+\frac{1}{\exp ^{s-1}(4+6)}+\frac{1}{\exp ^{s-1}(5+6)}-\frac{5}{\exp ^{s-1}(6+6)}\right) \zeta (s)=15$$
$$\lim_{s\to 1} \, \left(\frac{1}{\exp ^{s-1}(1+7)}+\frac{1}{\exp ^{s-1}(2+7)}+\frac{1}{\exp ^{s-1}(3+7)}+\frac{1}{\exp ^{s-1}(4+7)}+\frac{1}{\exp ^{s-1}(5+7)}+\frac{1}{\exp ^{s-1}(6+7)}-\frac{6}{\exp ^{s-1}(7+7)}\right) \zeta (s)=21$$
where we get the triangular numbers again. In other words there seems to be an invariance property.
Converting back to unexponentiated denominators:
$$\lim_{s\to 1} \, \left(\frac{1}{(1+2)^{s-1}}-\frac{1}{(2+2)^{s-1}}\right) \zeta (s)=\log \left(\frac{4}{3}\right)$$
$$\lim_{s\to 1} \, \left(\frac{1}{(1+3)^{s-1}}+\frac{1}{(2+3)^{s-1}}-\frac{2}{(3+3)^{s-1}}\right) \zeta (s)=\log \left(\frac{9}{5}\right)$$
$$\lim_{s\to 1} \, \left(\frac{1}{(1+4)^{s-1}}+\frac{1}{(2+4)^{s-1}}+\frac{1}{(3+4)^{s-1}}-\frac{3}{(4+4)^{s-1}}\right) \zeta (s)=\log \left(\frac{256}{105}\right)$$
$$\lim_{s\to 1} \, \left(\frac{1}{(1+5)^{s-1}}+\frac{1}{(2+5)^{s-1}}+\frac{1}{(3+5)^{s-1}}+\frac{1}{(4+5)^{s-1}}-\frac{4}{(5+5)^{s-1}}\right) \zeta (s)=\log \left(\frac{625}{189}\right)$$
$$\lim_{s\to 1} \, \left(\frac{1}{(1+6)^{s-1}}+\frac{1}{(2+6)^{s-1}}+\frac{1}{(3+6)^{s-1}}+\frac{1}{(4+6)^{s-1}}+\frac{1}{(5+6)^{s-1}}-\frac{5}{(6+6)^{s-1}}\right) \zeta (s)=\log \left(\frac{1728}{385}\right)$$
$$\lim_{s\to 1} \, \left(\frac{1}{(1+7)^{s-1}}+\frac{1}{(2+7)^{s-1}}+\frac{1}{(3+7)^{s-1}}+\frac{1}{(4+7)^{s-1}}+\frac{1}{(5+7)^{s-1}}+\frac{1}{(6+7)^{s-1}}-\frac{6}{(7+7)^{s-1}}\right) \zeta (s)=\log \left(\frac{117649}{19305}\right)$$
where we have:
$1,4/3, 9/5, 256/105, 625/189, 1728/385, 117649/19305,...$
compared to the earlier:
$1, 2, 9/2, 32/3, 625/24, 324/5, 117649/720...$
in other words, no invariance like with the triangular numbers.
Drawing this further we generalize and write:
$$\lim_{s\to 1} \, \zeta (s) \sum _{k=1}^n \frac{1-\text{If}[k \bmod n=0,n,0]}{k^{s-1}}$$
$$\lim_{s\to 1} \, \zeta (s) \sum _{k=n+1}^{n+n} \frac{1-\text{If}[k \bmod n=0,n,0]}{k^{s-1}}$$
$$\lim_{s\to 1} \, \zeta (s) \sum _{k=n+n+1}^{n+n+n} \frac{1-\text{If}[k \bmod n=0,n,0]}{k^{s-1}}$$
$$\lim_{s\to 1} \, \zeta (s) \sum _{k=n+n+n+1}^{n+n+n+n} \frac{1-\text{If}[k \bmod n=0,n,0]}{k^{s-1}}$$
$$\lim_{s\to 1} \, \zeta (s) \sum _{k=n+n+n+n+1}^{n+n+n+n+n} \frac{1-\text{If}[k \bmod n=0,n,0]}{k^{s-1}}$$
for which we get the sequences for $n=1,2,3,4,5,6,7,...$:
$$\left\{0,\log (2),\log \left(\frac{9}{2}\right),\log \left(\frac{32}{3}\right),\log \left(\frac{625}{24}\right),\log \left(\frac{324}{5}\right),\log \left(\frac{117649}{720}\right),...\right\}$$
$$\left\{0,\log \left(\frac{4}{3}\right),\log \left(\frac{9}{5}\right),\log \left(\frac{256}{105}\right),\log \left(\frac{625}{189}\right),\log \left(\frac{1728}{385}\right),\log \left(\frac{117649}{19305}\right),...\right\}$$
$$\left\{0,\log \left(\frac{6}{5}\right),\log \left(\frac{81}{56}\right),\log \left(\frac{96}{55}\right),\log \left(\frac{16875}{8008}\right),\log \left(\frac{19683}{7735}\right),\log \left(\frac{3176523}{1033600}\right),...\right\}$$
$$\left\{0,\log \left(\frac{8}{7}\right),\log \left(\frac{72}{55}\right),\log \left(\frac{2048}{1365}\right),\log \left(\frac{5000}{2907}\right),\log \left(\frac{331776}{168245}\right),\log \left(\frac{15059072}{6660225}\right),...\right\}$$
$$\left\{0,\log \left(\frac{10}{9}\right),\log \left(\frac{225}{182}\right),\log \left(\frac{4000}{2907}\right),\log \left(\frac{390625}{255024}\right),\log \left(\frac{4500}{2639}\right),\log \left(\frac{367653125}{193666176}\right),...\right\}$$
What is the relationship between these numbers? Trying to describe the fractions within the logarithms I wrote:
$$\frac{((j+1) n)^j}{\prod _{k=1}^j ((j+1) (n-1)+k)}$$
$$n=1,2,3,4,5$$
$$j=0,1,2,3,4,5,6$$
which gives:
$$\left(
\begin{array}{ccccc}
 1 & 1 & 1 & 1 & 1 \\
 2 & \frac{4}{3} & \frac{6}{5} & \frac{8}{7} & \frac{10}{9} \\
 \frac{9}{2} & \frac{9}{5} & \frac{81}{56} & \frac{72}{55} & \frac{225}{182} \\
 \frac{32}{3} & \frac{256}{105} & \frac{96}{55} & \frac{2048}{1365} & \frac{4000}{2907} \\
 \frac{625}{24} & \frac{625}{189} & \frac{16875}{8008} & \frac{5000}{2907} & \frac{390625}{255024} \\
 \frac{324}{5} & \frac{1728}{385} & \frac{19683}{7735} & \frac{331776}{168245} & \frac{4500}{2639} \\
 \frac{117649}{720} & \frac{117649}{19305} & \frac{3176523}{1033600} & \frac{15059072}{6660225} & \frac{367653125}{193666176}
\end{array}
\right)$$
which are the sequences within the logarithms above but transposed. Here
I tried to permute indexes $j$,$n$ and $k$ in an attempt to transpose the matrix but I did not succeed.
In addition to the known (conjectured):
$$\lim_{s\to 1} \, \zeta (s) \sum _{k=1}^n \frac{1-\text{If}[k \bmod n=0,n,0]}{k^{s-1}}=\frac{n^{n-1}}{(n-1)!}$$
a oeis search and some manipulation gives the following:
$$\lim_{s\to 1} \, \zeta (s) \sum _{k=n+1}^{n+n} \frac{1-\text{If}[k \bmod n=0,n,0]}{k^{s-1}}=\frac{n^{n-1}}{\frac{(n-1)! (2 n-1)\text{!!}}{n!}}$$
The following appears to be an example of a relationship:
$$\lim_{s\to 1} \, \zeta (s) \sum _{k=1}^n \frac{1-\text{If}[k \bmod n=0,n,0]}{k^{s-1}}=\lim_{s\to 1} \, \zeta (s) \sum _{k=1}^{n+n+n+n} \frac{1-\text{If}[k \bmod n=0,n,0]}{k^{s-1}}+\lim_{s\to 1} \, \zeta (s) \sum _{k=n+1}^{n+n} \frac{1-\text{If}[k \bmod n=0,n,0]}{k^{s-1}}+\lim_{s\to 1} \, \zeta (s) \sum _{k=n+n+1}^{n+n+n} \frac{1-\text{If}[k \bmod n=0,n,0]}{k^{s-1}}+\lim_{s\to 1} \, \zeta (s) \sum _{k=n+n+n+1}^{n+n+n+n} \frac{1-\text{If}[k \bmod n=0,n,0]}{k^{s-1}}$$
for $n$ an integer $\geq 1$. Also the limit $s \to 1$ seems be possible to put to any complex number $S=a+i b$, $s \to S$.
So the question repeated is:
Does:
$$\sum _{m=1}^t \lim_{s\to \text{S}} \, \zeta (s) \sum _{k=(m-1) n+1}^{m n} \frac{1-\text{If}[k \bmod n=0,n,0]}{k^{s-1}}$$
equal:
$$\lim_{s\to \text{S}} \, \zeta (s) \sum _{k=1}^{n t} \frac{1-\text{If}[k \bmod n=0,n,0]}{k^{s-1}}$$
for any complex number $S=a+i b$ and integer values of $n \geq 1$ and $t \geq 1 $?

The question seems to simplify to the following identity
$$\sum _{m=1}^t \lim_{s\to \text{S}} \, \zeta (s) \sum _{k=(m-1) n+1}^{m n} \frac{1}{k^{s-1}}=\lim_{s\to \text{S}} \, \zeta (s) \sum _{k=1}^{n t} \frac{1}{k^{s-1}}$$
for $S$ a complex number not equal to $1$ and $n=1,2,3,4,5,...$ and $t=1,2,3,4,5,...$
S = 1.23456789 + I*9.87654321
Monitor[Table[
  Chop[N[Table[
      Sum[Limit[Zeta[s]*Sum[1/k^(s - 1), {k, (m - 1)*n + 1, m*n}],
        s -> S], {m, 1, t}], {n, 1, 12}]] -
    Table[Limit[Zeta[s]*Sum[1/k^(s - 1), {k, 1, t*n}], s -> S], {n, 1,
       12}]], {t, 1, 6}], t]

Simpler still:
$$\sum _{m=1}^t \left(\sum _{k=(m-1) n+1}^{m n} \frac{1}{k^{s-1}}\right)=\sum _{k=1}^{n t} \frac{1}{k^{s-1}}$$
for $S=a+i b$ and $n=1,2,3,4,5,..$ $t=1,2,3,4,5,..$
Can anyone simplify the indexes in the double sum?

A: Starting from $$\sum _{m=1}^t \lim_{s\to \text{S}} \, \zeta (s) \sum _{k=(m-1) n+1}^{m n} \frac{1}{k^{s-1}}=\lim_{s\to \text{S}} \, \zeta (s) \sum _{k=1}^{n t} \frac{1}{k^{s-1}}$$
you don't need to use limits, since $\lim_{s \to S} \zeta (s) = \zeta (S)$ and you can divide by $\zeta(S)$ on both sides.
This leads to
$$\sum _{m=1}^t \sum _{k=(m-1) n+1}^{m n} \frac{1}{k^{S-1}}=\sum _{k=1}^{n t} \frac{1}{k^{S-1}}$$
Now, the inner summation of the left-hand side goes from $1$ to $n$, then from $n+1$ to $2n$, then from $2n+1$ to $3n$ and so on up to $(t-1)n+1$ to $nt$. Since the indices are non-overlapping and consecutive you can conclude that equality holds.


text:
Q: What could this REDIS StackExchange.Redis exception mean Am trying to understand what could the REDIS error mean. we have a master and a localhost as slave. from time to time we receive such an error which we think that it's produced from a call to big cache.but as i said it does not happen all the time

Exception message: Timeout performing EVAL, inst: 2, mgr: ExecuteSelect, err: never, queue: 0, qu: 0, qs: 0, qc: 0, wr: 0, wq: 0, in: 0, ar: 0, IOCP: (Busy=0,Free=1000,Min=32,Max=1000), WORKER: (Busy=5,Free=32762,Min=32,Max=32767), clientName: BSKKAYSIS-IIS01


text:
Q: Django passing JSON data to static getJSON/Javascript I am trying to grab data from my models.py and serialize it into a JSON object within my views.py.
Models.py:
class Platform(models.Model):
     platformtype = models.CharField(max_length=25)

Views.py:
def startpage(request):
   return render_to_response('Main.html');

def index(request):
   platforms_as_json = serializers.serialize('json', Platform.objects.all())
   return HttpResponse(platforms_as_json, content_type='json')

After doing this I want to pass this object into my static javascript file which is using getJSON to populate my drop down list for my template(Main.html).
JavaScript:
$.getJSON("{{platforms_as_json}}", function (data) {
 $.each(data, function (index, item) {
     $('#platformList').append(
          $('<option></option>').val(item).html(item.platformtype)
);
 });
});

I have looked at many other threads within SO, but all of them are for those using embedded JS within their template and/or not using getJSON. As of right now, data is not being displayed in the list when I run my Django development server. What am I doing wrong? Thank you.
UPDATE:
 <!DOCTYPE html>

{% load static from staticfiles %}

<select id = "platformList"></select>

platformddown_script.js:
$.each(platformsjson, function (index, item) {
   $('#platformList').append(
           $('<option></option>').val(item.platformtype).html(item.platformtype)
   )
   });

After this update it still doesn't work.

A: Main html render + json data
import json
from django.shortcuts import render

def startpage(request):
    platforms = Platform.objects.select_related().values('platformtype')
    return render(request, 'Main.html', {'platforms_as_json': json.dumps(list(platforms)),})

in template
{{ platforms_as_json }}

html and js
<select id="platformList"></select>

Old example
https://gist.github.com/leotop/014a38bd97407a6380f2526f11d17977


text:
Q: graph is not showing in screen I followed one tutorial to create a graph. Here is that Part 3 tutorial, but while I run my graph line is not showing up. Here is my code:
Gridview.h
#import <UIKit/UIKit.h>
#define kGraphHeight 300
#define kDefaultGraphWidth 900
#define kOffsetX 0
#define kStepX 50
#define kGraphBottom 300
#define kGraphTop 0
#define kStepY 50
#define kOffsetY 10

@interface GridView : UIView

@end

**GridView.m**

    #import "GridView.h"

    @implementation GridView

    - (void)drawLineGraphWithContext:(CGContextRef)ctx
    {
        //float data[] = {0.7, 0.4, 0.9, 1.0, 0.2, 0.85, 0.11, 0.75, 0.53, 0.44, 0.88, 0.77, 0.99, 0.55};
         float data[] = {0.7, 0.4, 0.9, 1.0, 0.2, 0.85, 0.11, 0.75, 0.53, 0.44, 0.88, 0.77, 0.99, 0.55};

        CGContextSetLineWidth(ctx, 2.0);
        CGContextSetStrokeColorWithColor(ctx, [[UIColor colorWithRed:1.0 green:0.5 blue:0 alpha:1.0] CGColor]);

        int maxGraphHeight = kGraphHeight - kOffsetY;
        CGContextBeginPath(ctx);
        CGContextMoveToPoint(ctx, kOffsetX, kGraphHeight - maxGraphHeight * data[0]);

        for (int i = 1; i < sizeof(data); i++)
        {
            CGContextAddLineToPoint(ctx, kOffsetX + i * kStepX, kGraphHeight - maxGraphHeight * data[i]);
        }

        CGContextDrawPath(ctx, kCGPathStroke);

    }

- (void)drawRect:(CGRect)rect

{

    CGContextRef context = UIGraphicsGetCurrentContext();
    [self drawLineGraphWithContext:context];

    // Draw the background image
    UIImage *image = [UIImage imageNamed:@"background.png"];
    CGRect imageRect = CGRectMake(0, 0, image.size.width, image.size.height);
    CGContextDrawImage(context, imageRect, image.CGImage);

    CGContextSetLineWidth(context, 0.6);
    CGContextSetStrokeColorWithColor(context, [[UIColor lightGrayColor] CGColor]);
    CGFloat dash[] = {2.0, 2.0};
    CGContextSetLineDash(context, 0.0, dash, 2);

    // How many lines?
    int howMany = (kDefaultGraphWidth - kOffsetX) / kStepX;

    // Here the lines go
    for (int i = 0; i <= howMany; i++)
    {
        CGContextMoveToPoint(context, kOffsetX + i * kStepX, kGraphTop);
        CGContextAddLineToPoint(context, kOffsetX + i * kStepX, kGraphBottom);
    }

    int howManyHorizontal = (kGraphBottom - kGraphTop - kOffsetY) / kStepY;
    for (int i = 0; i <= howManyHorizontal; i++)
    {
        CGContextMoveToPoint(context, kOffsetX, kGraphBottom - kOffsetY - i * kStepY);
        CGContextAddLineToPoint(context, kDefaultGraphWidth, kGraphBottom - kOffsetY - i * kStepY);
    }

    CGContextStrokePath(context);
    CGContextSetLineDash(context, 0, NULL, 0); // Remove the dash
}

viewcontroller.h
#import <UIKit/UIKit.h>

@interface ViewController : UIViewController
{

    UIScrollView *scroller;
}

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;

@end

viewcontroller.m
#import "ViewController.h"
#import "GridView.h"

@interface ViewController ()

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    scroller.contentSize = CGSizeMake(kDefaultGraphWidth, kGraphHeight);

}

Why am I not able to generate the graph to display. Please help me to solve. Thanks

A: Try adding this method in your view controller.m
-(void)viewDidAppear:(BOOL)animated{

    [super viewDidAppear:animated];

   GridView *gv=[GridView alloc]initWithFrame:CGRectMake(0,0,100,100)];

   [ self.view addSubView:gv];

}


text:
Q: Loading custom u-boot script I've created an image (with Yocto and meta-tegra) and got a Jetson Nano devkit running with two rootfs that RAUC updating uses. I am currently (temporarily during testing) using the Jetson Nano devkit SPI flash to store the u-boot environment.
I have a script that I successfully got running on my device with tftp. I've also manually typed in every line of my script to an environment variable, saved it and set bootcmd to run it. But if i want more than one device with this u-boot, i wouldn't want to manually type in the script for every device i make. But I also don't want a tftp server to be running at the side to be able to boot.
I want to run my script completely independent and automatically. So I've been thinking about having the script on a partition on it's own and get u-boot to load the script from there. But how do i tell u-boot to look for at script in the specific partition? Can i use source SCRIPT_PARTITION_OFFSET?
I've also seen that the standard boot.scr can be run from the u-boot shell. Where is this boot.scr located? I can't seem to find where it is created or where it is stored.
*****************************************************EDIT:*****************************************************
As a temporary solution I have put the boot script image into /boot/ folder and set the u-boot to scan for scripts in the that folder on both rootfs and then run it if it can find it.
For this solution i still have to edit the u-boot env to make u-boot boot this custom way, so it is not a solution i can use in the long run. I might as well make a script to run once via tftp that will set bootcmd to be the entire boot script content.
Can i edit the u-boot source code with a patch that has my script in it's environment? - if so, how?

A: As said in the comments, i was able to make a patch for u-boot-tegra/include/config_distro_bootcmd.h that has the variable distro_bootcmd set to my script content. When i then build my yocto image and boot up my Jetson Nano, i can see that the variable is in fact set.
This way should work for any u-boot and not just for Jetson Nano. Just find the bootcmd variable in the u-boot that runs at default boot and patch it.


text:
Q: What determines the set of fonts that can be set in Equation Tools in MS Word 2007 and newer? In Microsoft Word 2007 and newer, if you enter Equation Tools and then click on the Equation Options buttons (the very small button in the lower right corner of the Tools group in the Design tab), the first setting in the window that opens is "Default font for math regions". I suppose it normally contains Cambria Math only. It sets the overall font used, the font used for everything but such "Normal Text" (i.e., text formatted as "Normal Text" with the Equation tools—for such text, normal font setting commands of Word are available).
The question is: How can the repertoire of fonts there be expanded? In my computer, the menu (dropdown) has Cambria Math, XITS Math, Asana Math, and STIX Math. Does this mean that Word constructs the menu by looking at the names of installed fonts and picks up those that have names ending with the word "Math"? Is this documented somewhere?
For example, if I wanted to use FreeSerif in equations, would I thus need to create a version of it with a name (internal name) that ends with "Math"?
This is the settings window that the question is about:

A: I'd guess that Word looks for fonts that have the appropriate OpenType Math tables. Unlike the old equation editor, which could use any font and the result would be horrible regardless, Word requires the font to be properly set up for math, which includes lots of fun things, like e.g.  kerning at corners of symbols, not usually required for text.


text:
Q: PostgreSQL is skipping indexes when using `order by` + `limit` I have a postgreSQL database with two big tables, connections and sessions
select "c"."id" "id", "ch"."title" "channel", "ch"."name" "channel_name", "c"."nickname", "c"."duration", "c"."status", "c"."start_time", "c"."stop_time", "u"."nickname" "user", "u"."username" "username"
from "connections" "c"
left join "sessions" "sh" on "session_id" = "sh"."id"
left join "customers" "cs" on "sh"."customer_id" = "cs"."id"
left join "channels" "ch" on "channel_id" = "ch"."id"
left join "clients" "cl" on "client_id" = "cl"."id"
left join "users" "u" on "c"."user_id" = "u"."id"
where ("sh"."customer_id" = 13598)
order by "id" desc
limit 10 offset 0

When running this query without limit, execution takes about 800ms. But with limit 10 it takes 16000ms!!!
It seems that when limit added, Postgre skips indexes. How can I change that?
This is the explain result of this query with and without the limit:
With limit:
Limit  (cost=30.93..30.94 rows=1 width=1202) (actual time=0.017..0.017 rows=0 loops=1)
  ->  Sort  (cost=30.93..30.94 rows=1 width=1202) (actual time=0.015..0.015 rows=0 loops=1)
        Sort Key: c.id DESC
        Sort Method: quicksort  Memory: 25kB
        ->  Nested Loop Left Join  (cost=14.02..30.92 rows=1 width=1202) (actual time=0.009..0.009 rows=0 loops=1)
              ->  Nested Loop Left Join  (cost=13.88..30.49 rows=1 width=850) (actual time=0.008..0.008 rows=0 loops=1)
                    ->  Hash Join  (cost=13.74..26.14 rows=1 width=306) (actual time=0.008..0.008 rows=0 loops=1)
                          Hash Cond: (c.session_id = sh.id)
                          ->  Seq Scan on skyroom_connections c  (cost=0.00..11.90 rows=190 width=310) (actual time=0.007..0.007 rows=0 loops=1)
                          ->  Hash  (cost=13.67..13.67 rows=6 width=12) (never executed)
                                ->  Bitmap Heap Scan on skyroom_sessions sh  (cost=4.20..13.67 rows=6 width=12) (never executed)
                                      Recheck Cond: (customer_id = 13598)
                                      ->  Bitmap Index Scan on skyroom_sessions_customer_idx  (cost=0.00..4.20 rows=6 width=0) (never executed)
                                            Index Cond: (customer_id = 13598)
                    ->  Index Scan using skyroom_channels_pkey on skyroom_channels ch  (cost=0.14..4.16 rows=1 width=552) (never executed)
                          Index Cond: (id = sh.channel_id)
              ->  Index Scan using users_pkey on users u  (cost=0.14..0.38 rows=1 width=360) (never executed)
                    Index Cond: (id = c.user_id)
Planning Time: 0.978 ms
Execution Time: 0.147 ms

Without Limit:
Sort  (cost=30.93..30.94 rows=1 width=1202) (actual time=0.010..0.010 rows=0 loops=1)
  Sort Key: c.id DESC
  Sort Method: quicksort  Memory: 25kB
  ->  Nested Loop Left Join  (cost=14.02..30.92 rows=1 width=1202) (actual time=0.004..0.004 rows=0 loops=1)
        ->  Nested Loop Left Join  (cost=13.88..30.49 rows=1 width=850) (actual time=0.004..0.004 rows=0 loops=1)
              ->  Hash Join  (cost=13.74..26.14 rows=1 width=306) (actual time=0.004..0.004 rows=0 loops=1)
                    Hash Cond: (c.session_id = sh.id)
                    ->  Seq Scan on skyroom_connections c  (cost=0.00..11.90 rows=190 width=310) (actual time=0.003..0.003 rows=0 loops=1)
                    ->  Hash  (cost=13.67..13.67 rows=6 width=12) (never executed)
                          ->  Bitmap Heap Scan on skyroom_sessions sh  (cost=4.20..13.67 rows=6 width=12) (never executed)
                                Recheck Cond: (customer_id = 13598)
                                ->  Bitmap Index Scan on skyroom_sessions_customer_idx  (cost=0.00..4.20 rows=6 width=0) (never executed)
                                      Index Cond: (customer_id = 13598)
              ->  Index Scan using skyroom_channels_pkey on skyroom_channels ch  (cost=0.14..4.16 rows=1 width=552) (never executed)
                    Index Cond: (id = sh.channel_id)
        ->  Index Scan using users_pkey on users u  (cost=0.14..0.38 rows=1 width=360) (never executed)
              Index Cond: (id = c.user_id)
Planning Time: 0.425 ms
Execution Time: 0.097 ms

A: The Postgres 12 documentation states that offset 0 is the same as omitting the offset clause. However, it also states that: "If both OFFSET and LIMIT appear, then OFFSET rows are skipped before starting to count the LIMIT rows that are returned". Therefore, it might be case that the presence of the limit clause causes offset 0 to be computed despite it being a noop, but the absence causes the query planner to omit the offset 0 hence being much faster.


text:
Q: Google MDL Checkbox not showing the check on JQuery modal dialog box I'm using JQuery to provide a modal dialog box on an MDL Page. That dialog box includes two checkboxes. When I set the dialog box to modal, the checkboxes stop working, when the dialog box is not modal the checkboxes work.
The Header of the page is as follows;

    <title>Service Routing</title>
    <meta charset="utf-8" />
    <meta HTTP-EQUIV="CACHE-CONTROL" CONTENT="NO-CACHE">
    <meta http-equiv="X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE" />
    <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
    <link rel="stylesheet" href="https://code.getmdl.io/1.3.0/material.lime-orange.min.css">
    <link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons" />
    <link rel="stylesheet" href="Styles/toastr.css" />

<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.16/themes/base/jquery-ui.css" />
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

<meta name="viewport" content="width=device-width, initial-scale=1.0" />

The dialog is defined as follows;

                                    <input class="mdl-textfield__input" type="text" id="txtServiceId" readonly>

                                    Service Id

                                    <input class="mdl-textfield__input" type="text" id="txtSpecialityCode" readonly>

                                    Speciality Id.

                                    <input class="mdl-textfield__input" type="text" id="txtConsultant">

                                    Consultant

                                    Unknown Consultant Code

                                    <input class="mdl-textfield__input" type="text" id="txtGPCode" />

                                    GP Code

                                    <input class="mdl-textfield__input" type="text" id="txtRouting" >

                                    Routing

                                    <input class="mdl-textfield__input" type="text" id="txtDocumentName" >

                                    Cerner Document Name

                                    <input class="mdl-textfield__input" type="text" id="txtEmailAlert" >

                                    Email Alert

                                    <input type="checkbox" id="chkProcess" class="mdl-checkbox__input">

                                    Process

                                    <input type="checkbox" id="chkShowConsultant" class="mdl-checkbox__input">

                                    Show Consultant

                            Save

The Dialog is initialised with the following code.
        $("#editDialog").dialog({

            autoOpen: false,

            modal: true,

            width: 1100,

            height: 560,

            resizable: false,

            open: function () { $(".ui-dialog").css("box-shadow", "#CCC 15px 15px 15px"); }

        });

it is this code which  if I set modal:false then the checkboxes work, but if it set to true then they don't.
Last but not least the dialog is shown by running the following line
 $("#editDialog").dialog("open");

Anyone know what I can do to make the checkboxes work.

A: By adding the following code to the page the checkbox now works
$("#lblProcess").click(function() {
    if($('#lblProcess').is('.is-checked')) {
    document.querySelector('#lblProcess').MaterialCheckbox.uncheck();
  }
  else {
    document.querySelector('#check').MaterialCheckbox.check();
  }
});

and then repeating it for the other checkbox.


text:
Q: Remote devcontainer, inherit SSH of parent host I am trying to use VSCode dev containers under a remote machine which is authenticated with git, without re-authenticating from the dev container.
Is it possible for a dev container to use the SSH agent of the parent host?
[  Client  ] -> [  Host ->  [  Dev Container  ]  ]
  Can auth        Can auth     Needs to use
  with Host       with git     Host's auth
                  via SSH

The host is opaque in it's authentication mechanisms, so simply copying id_rsa doesn't work. The SSH agent needs to be forwarded.


text:
Q: Error with sending PushNotifications with OneSignal android I am working on a Messaging Android App. Users should be notified with a push notification.
At the time I have this code:
public void notifyUser(String user_id, String message) {
        try {
            OneSignal.postNotification(new JSONObject("{'contents': {'en':['" + message + "']}, " +
                            "'include_player_ids': ['" + user_id + "'], " +
                            "'headings': {'en': 'Tag sub Title HI {{user_name}}'}, " +
                            "'data': {'openURL': 'https://imgur.com'}," +
                            "'buttons':[{'id': 'id1', 'text': 'Go to GreenActivity'}, {'id':'id2', 'text': 'Go to MainActivity'}]}"),
                    new OneSignal.PostNotificationResponseHandler() {
                        @Override
                        public void onSuccess(JSONObject response) {
                            Log.d("LOL", "postNotification Success: " + response.toString());
                        }

                        @Override
                        public void onFailure(JSONObject response) {
                            Log.d("LOL", "postNotification Failure: " + response.toString());
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
}

But I get an Error in Log:
D/LOL: postNotification Failure: {"errors":["Notification contents for each language must be a string"]}

I searched threw the Internet but didn't find a solution for my Problem.
I hope you can help me...
Thanks in advance.

A: I believe the error you're seeing is because you're sending up the message inside an array when it should just be a string.
"{'contents': {'en':['" + message + "']} should be "{'contents': {'en':'" + message + "'} (removed the brackets).


text:
Q: how to work with excel file columns i am stuck in one problem.. i am trying to write to excel file what i do in my app.
studium = unt_stelle.objects.all().order_by("stand__nick")

    formatter = ExcelFormatter()
    simpleStyle = ExcelStyle(vert=2,wrap=1)
    formatter.addBodyStyle(simpleStyle)
    formatter.setWidth('name,clicks,stand.nick,berufsfelder,bereich',3000)
    formatter.setWidth('erfahrung',1000)
    formatter.setWidth('studiengaenge',1000)
    formatter.setWidth('status',1000)
    formatter.setWidth('id',500)

    simple_report = ExcelReport()
    simple_report.addSheet("TestSimple")
    filter = ExcelFilter(order='id,name,clicks,status,stand.nick,erfahrung,studiengaenge,berufsfelder,bereich')
    simple_report.addQuerySet(studium,REPORT_HORZ,formatter,filter)

    response = HttpResponse(simple_report.writeReport(),mimetype='application/ms-excel')
    response['Content-Disposition'] = 'attachment; filename=stellen_dump.xls'
    return response

my problem is that if i give 'studiengaenge' as a column, i get weird queryset in this column, not a normal string, studiengaenge is a ManyToManyField. how can i manage this so that i have only 3 items from 'studiengaenge' field with some small design like with "-" in between of each items...?
Thanks

A: From what I remember, the "weird queryset" you get from the many-to-many can be accessed as an array. You can iterate through it and build a string.


text:
Q: iOS App rejection with a reason - ' The Auto Screen lock feature of your app functions with or without the featured enabled within the app settings' I have submitted an iOS timer based app for review last week and today Apple rejected it saying the following reason,
2.2 - Apps that exhibit bugs will be rejected
2.2 Details
We discovered one or more bugs in your app when reviewed on iPad running iOS 9.0.2 and iPhone running iOS 9.0.2 on both Wi-Fi and cellular networks.

*

*The Auto Screen lock feature of your app functions with or without the featured enabled within the app settings.

Like many other timer based apps (or pomodoro apps) available in the app store, I have included toggle function in my application whether a user can enable or disable auto screen lock when the app is on foreground. It works as intended, prevent screen locks only when the app is in the foreground. All other time screen lock is working based on Auto-Lock status in the settings App.
These are the code I have used, In the Main view controller, when the view loads,
- (void)viewDidLoad
{
//...
    NSNumber *screenLockStatus = [[NSUserDefaults standardUserDefaults] objectForKey:kFLScreenLockKey];

    if (!screenLockStatus) {
        [[UIApplication sharedApplication] setIdleTimerDisabled:NO];
    } else {
        [[UIApplication sharedApplication] setIdleTimerDisabled:[screenLockStatus boolValue]];
    }
}

Then in the settings view controller of the app,
- (void)viewDidLoad
{ //....
    self.preventScreenLockSwitch.on = [UIApplication sharedApplication].idleTimerDisabled;
}

- (IBAction)preventScreenLock:(UISwitch *)sender
{
    // Disable idle timer to prevent screen lock while app is on foreground.
    [[UIApplication sharedApplication] setIdleTimerDisabled:self.preventScreenLockSwitch.isOn];

    // Save Screenlock prevent switch status.
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:[NSNumber numberWithBool:self.preventScreenLockSwitch.isOn] forKey:kFLScreenLockKey];
    [userDefaults synchronize];
}

I have tested it on many devices and it works as intended. I am not really sure whether the reviewer got it wrong or is there something wrong with this approach.
Has anyone faced this situation earlier? If so what is the recommended solution?
Appreciate any help on this matter.
Thanks.


text: Q: How to Search in Repos of Most copied/pasted Functions between multiple repos? Is there a way to find most copied/pasted functions or bulk of codes between multiple repos? For example, in react I'd rather make a component out of stuff copied around too many times and share between so when I update the component this copied function will take an impact everywhere. Otherwise function updated at one location will not be updated in an another location.


text:
Q: Entity Framework - how to avoid query recompilation? I am working on optimization of our Entity Framework code, and currently I am facing an issue I'm not sure how to solve.
We are using Azure SQL + Code-First Entity Framework 6.1.3 + Asp.net Web Api v2. Endpoint is hosted in the cloud and I'm using it for testing.
I have an API action, that is used for getting filtered, sorted and paged data. Here's a simplified code of what I do with data:
var entities = DbContext.Services
        .Include(q => q.Consumer.Building.Address.Country)
        .Include(q => q.Consumer.Building.Address.State);

entities = entities.OrderBy(x => x.Consumer.RegisteredAt);

entities = entities.Where(x => x.IsDeleted == false);
entities = entities.Where(x => userId.HasValue ? x.Owner.Id == userId ? true); //this part comes from deep internals, so I cannot change it quickly
var page = entities = entities.Skip(skip).Take(take).ToList();
var count = entities.Count();

var dtoPage = Mapper.Map<IEnumerable<ServiceDto>>(page);

return Page<ServiceDto>(dtoPage, count);

So the code does nothing exceptional - does not use IN clause, etc.., just simple filter, sorting and paging.
The problem:
Calling this method has unstable execution time. I used a simple script to call API endpoint that calls this code with different params: it gets pages 0..5 consequently 200 times, one after another. For each call (except for the first) I expected the call to take less than 300 ms. BUT: from 1200 overall calls, 36 call times exceeded 1 second - like the query was re-compiled again during this time. Average time for calls was 250ms, but it spiked sometimes to 1000ms, it's 4 times difference.
Common behavior for tests is:

*

*First query is slow

*Second query is faster, but still slower then rest

*Rest queries are pretty stable fast, except for some spikes every now and then.
No one used testing environment except for me, so it's not load issue, I can reproduce it on any environment, even on fast local PC - i5 + 8gb RAM + SSD.
Also even small delay between tests -
So my question in short is:
What does this issue come from?

*

*Is this really recompilation issue, if not, what is the possible source of the issue?

*Is there a document about query cache invalidation for Entity Framework 6?

*Is there a way to keep a query in the cache for longer time, so that if I query the method now and in 30 minutes, it would not have to re-compile it?

A:
Is this really recompilation issue,

I don't think it is a recompilation issue. But you can mitigate recompilations by passing lambdas in your Skip and Take calls. See 4.2 Using functions that produce queries with constants

if not, what is the possible source of the issue?

AFAIK SqlAzure is shared environment. It may be the cause of your problem.

Is there a document about query cache invalidation for Entity Framework 6 ?
  Is there a way to keep a query in the cache for longer time, so that if I query the method now and in 30 minutes, it would not have to re-compile it?

Your Entity Framework query will stay in memory as long as the AppDomain, the sql query plan will stay in Sql Server memory as long as the server isn't in need of memory. The Skip and Take with lambdas will also help on that matter.
See on the same page :

"In EF6 these methods have a lambda overload that effectively makes the
cached query plan reusable because EF can capture variables passed to
these methods and translate them to SQLparameters. This also helps
keep the cache cleaner since otherwise each query with a different
constant for Skip and Take would get its own query plan cache entry"


text:
Q: How to preform shapiro test with group by function Type <- c("Bark", "Redwood", "Oak")
size <- c(10,15,13)
width <- c(3,4,5)
Ratio <- size/width
df <- data.frame(Type, size, width, Ratio)
mutate(df, ratio_log = log10(Ratio))
df %>% group_by(Type) %>% shapiro.test(ratio_log)

Error in shapiro.test(., ratio_log) : unused argument (ratio_log)

I am attempting to apply the Shapiro test for all of the types, e.g, bark, redwood, oak. not all the ratios combined. I have a larger data set that consists of more ratios.

A: You need tidyverse for purrr and dplyr at least.
And I made more samples in the example since you need a vector for shapiro.test and not a single ratio. So here is 100 samples from a normal, a binomial and a uniform distribution.
library(tidyverse)

Type <- c("Bark", "Redwood", "Oak")
size <- c(10,15,13)
width <- c(3,4,5)
Ratio <- c(rnorm(100),
           rbinom(100, size = 2, prob = 0.2),
           runif(100))

Put these in a data.frame
# Need minimum sample size for shapiro test
df <- data.frame(Type = rep(Type, each = 100),
                 Size = rep(size, each = 100),
                 width = rep(size, each = 100),
                 Ratio)

Then you can use the ratio_log, in this case I took the liberty of just using the same ratio. You can group by Type and use nest to nest a data.frame of the data per group.
df %>%
  mutate(ratio_log = Ratio) %>%
  group_by(Type) %>%
  mutate(N_Samples = n()) %>%
  nest()

# A tibble: 3 x 2
  Type    data
  <fct>   <list>
1 Bark    <tibble [100 x 5]>
2 Redwood <tibble [100 x 5]>
3 Oak     <tibble [100 x 5]>

You can then use the map function together with mutate to basically do lapply applied to the nested data.frames (or tibbles, same thing essentially here.) To each data.frame per group we apply the shapiro.test function to the values in the ratio_log column.
# Use purrr::nest and purrr::map to do shapiro tests per group
df.shapiro <- df %>%
  mutate(ratio_log = Ratio) %>%
  group_by(Type) %>%
  mutate(N_Samples = n()) %>%
  nest() %>%
  mutate(Shapiro = map(data, ~ shapiro.test(.x$ratio_log)))

# A tibble: 3 x 3
  Type    data               Shapiro
  <fct>   <list>             <list>
1 Bark    <tibble [100 x 5]> <S3: htest>
2 Redwood <tibble [100 x 5]> <S3: htest>
3 Oak     <tibble [100 x 5]> <S3: htest>

Now you have nested shapiro.test results, applied to each group.
To get the relevant parameters you can use glance from the broom package. Then unnest the result from the glance function.
# Use broom::glance and purrr::unnest to get all relevant statistics
library(broom)
df.shapiro.glance <- df.shapiro %>%
  mutate(glance_shapiro = Shapiro %>% map(glance)) %>%
  unnest(glance_shapiro)

 Type    data               Shapiro     statistic  p.value method
  <fct>   <list>             <list>          <dbl>    <dbl> <fct>
1 Bark    <tibble [100 x 5]> <S3: htest>     0.967 1.30e- 2 Shapiro-Wilk normality test
2 Redwood <tibble [100 x 5]> <S3: htest>     0.638 2.45e-14 Shapiro-Wilk normality test
3 Oak     <tibble [100 x 5]> <S3: htest>     0.937 1.31e- 4 Shapiro-Wilk normality test

A: library(dplyr)

Type <- c("Bark", "Redwood", "Oak")
size <- c(10,15,13)
width <- c(3,4,5)
Ratio <- size/width
df <- data.frame(Type, size, width, Ratio)

df %>%
  mutate(ratio_log = log10(Ratio)) %>%
  group_by(Type) %>%
  summarise(results = data_frame(shapiro.test(.$ratio_log)))

You an also see other solutions here: purrr map a t.test onto a split df


text:
Q: Loading socket.io/socket.io.js into html head returning "ReferenceError: io is not defined" I am working on a simple socket.io project, and have hit a wall. When I added the script  into the head, I was expecting the application to recognize this, but instead I got the error message GET http://localhost:5678/socket.io/socket.io.js and Uncaught ReferenceError: io is not defined in my console. I am using the express framework.
var express = require('express');
var router = express.Router();
var http = require('http').Server(express);
var io = require('socket.io')(http);

/* GET home page. */
router.get('/', function(req, res) {
  res.render('index', { title: 'NodeIM' });
});

io.on('connection', function(socket){
  console.log('a user connected');
  socket.on('disconnect', function(){
    console.log('user disconnected');
  });
});

server = http.listen(3000, function() {
    console.log('Listening on port %d', server.address().port);
});

module.exports = router;

HTML:

      <title>NodeIM</title>
      <link rel="stylesheet" href="/stylesheets/style.css">

NodeIM

Welcome to NodeIM

      <form id="im_form" action=""><input id="m" autocomplete="off"><button>Send</button></form>

NOTE: I've also tried to follow socket.io - ReferenceError: io is not defined and changed my src to src="http://localhost:5678/socket.io/socket.io.js", but it did not fix the issue. I've also tried to use Node.js socket.io.js not found or io not defined, which just showed me another way of requiring socket.io, but doesn't fix the ReferenceError problem I am having

A: Your usage of /socket.io/socket.io.js for src is correct. However, your setting up of the http server has a typo: var http = require('http').Server(express); should probably be var http = require('http').Server(router);.

A: As stated in the chat-demo on Socket.io you should put the


text:
Q: Sort by date with null first I'm trying to find documents in a collection, ordered by their date. This works, but I get the documents with null in the date field at the bottom, I want these first.
MyModel.find({ }, null, { sort: { date: -1 } }, function(err, models) {
    // Models sorted with the "largest" date first and models with null dates last
});

If I change the sorting to { date: 1 } I do get the documents with null at first, but the order otherwise is reverse, which I do not want.
How can I achieve the desired behaviour?

A: Unfortunately it appears there's no trivial way to do this, akin to SQL's "nulls first" / "nulls last" syntax.  This feature is mentioned in this Mongo bug:
https://jira.mongodb.org/browse/SERVER-153
Where it's looped in with the larger feature of custom sorting functions.  (I really wish this were broken out into a separate feature request because I would think implementing only the nulls first/last bit should be much easier than custom sorting functions and still provide a lot of value.)
Anyway, the work-around for the time being is to just query separately for the null values in addition to your existing query:
How are null values in a MongoDB index sorted?
MyModel.find({ date: null });
MyModel.find({ date: { $ne: null } }).sort({ date: -1 } });


text:
Q: Django wizard: Form instantiated and clean called multiple times I have a form wizard with 3 forms. The first form has only one field and uses that field to do a lookup in an external API to validate the data.
I noticed that the requests were taking unusually long, so I just added a print statement to
the form's init method and to the external API client call.
It seems that my first form is being initialized and cleaned exactly 28 times every time I execute that step in the form wizard.
My first form looks like this:
forms.py
class MyForm1(forms.Form):

    issue_id = forms.CharField()

    def __init__(self, *args, **kwargs):
        print "init form 1"
        super(MyForm1, self).__init__(*args, **kwargs)

    def clean(self):
        cleaned_data = super(MyForm1, self).clean()
        print "clean issue id"
        issue_id = cleaned_data.get("issue_id")

        if issue_id is not None:
            try:
                issue = ApiCLient.get_issue(issue_id)
            except APIError:
                raise forms.ValidationError("Issue not found. Try again!")
            else:
                return cleaned_data

        raise forms.ValidationError("Issue not found. Try again!")

The wizard stuff is pretty standard from the Django Docs, but here it goes:
views.py
class MyWizard(SessionWizardView):
    def done(self, form_list, **kwargs):
        # some logic at the end of the wizard

urls.py
wizard_forms = [MyForm1, MyForm2, MyForm3]
...
url(r'wizard/$', login_required(views.MyWizard.as_view(wizard_forms))),

As I said before, executing the first step results in
init form 1
clean issue id

Being printed to console exactly 28 times.
Any ideas? Is this a feature or a bug in the Django Form Wizard?


text: Q: Распаковка сжатой библиотеки в оперативную память? Есть браузерное SPA приложение, оно использует библиотеку(шифрования пароля), для использования библиотека загружается на сторону клиента. Проблема в том что библиотека весит 5мб но zip библиотеки весит 600кб.  Как загружать на сторону клиента zip библиотеку и распаковывать её в оперативную память добавляя к содержимому SPA?


text:
Q: Aksing about pygame background How do you make a white background in pygame? I am having an issue figuring out the correct code to make the background white and where exactly to put it in my code.

A:
How do you make a white background in pygame?

When pygame.display.set_mode() is called, a pygame.Surface is associated to the display. Everything that is drawn on this Surface is visible on the display after the update. fill the display Surface with a white color:
screen = pygame.display.set_mode((500, 500))

# [...]

screen.fill("white")

# [...]

pygame.display.flip()

where exactly to put it in my code.

The typical PyGame application loop has to:

*

*handle the events by either pygame.event.pump() or pygame.event.get().

*update the game states and positions of objects dependent on the input events and time (respectively frames)

*clear the entire display or draw the background

*draw the entire scene (blit all the objects)

*update the display by either pygame.display.update() or pygame.display.flip()
Example:
import pygame

pygame.init()
screen = pygame.display.set_mode((500, 500))
clock = pygame.time.Clock()

run = True
while run:
    clock.tick(60)

    # handel events
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            run = False

    # update game

    # clear screen with white color
    screen.fill("white")

    # draw scene
    # [...]

    # update diesplay
    pygame.display.flip()

pygame.quit()
exit()


text:
Q: How to hide all command output with zsh and bash How can I hide all output that is written and outputted in a terminal?
In other words, I am looking to add the string
>/dev/null 2&>1

to every command I write.

*

*How would you do it with bash?

*How would you do it with zsh?

*Ideally how to have a configuration that take into account any terminal.

A: zsh:
You can redirect stdout and stderr of any following command to /dev/null by running these two command:
exec >/dev/null
exec 2>/dev/null

Note: This will still show the prompt and anything you type on the command line, but not much else.
bash:
You can redirect stdout and stderr with the following command
exec >/dev/null 2>&1

Note

*

*This may suppress any output, including the prompt and what you type on the command line. (This was the case for me with zsh 5.2 and bash 4.4, when I first created this answer in 2016. While it seems to still be the case with bash 5.1.8, it looks like with zsh this is no longer the case since at least version 5.8)

*To enable the output again, run
  exec >/dev/tty
  exec 2>/dev/tty


text:
Q: What is a propper way to implement MKAnnotation I'm getting crashes while working with MKAnnotation implementation
*** Terminating app due to uncaught exception NSRangeException, reason: Cannot remove an observer MKMapAnnotationManager for the key path "coordinate" from DevicesGroupAnnotation because it is not registered as an observer.
I've implemented coordinate property in following way
@synthesize coordinate = _coordinate;
@synthesize deviceInfos = _deviceInfos;

- (void)setDeviceInfos:(NSArray *)deviceInfos {
    _deviceInfos = deviceInfos;
    self.coordinate = [[self class] coordinateFromDeviceInfosGroup:self.deviceInfos];
}

- (void)setCoordinate:(CLLocationCoordinate2D)newCoordinate {
    _coordinate = newCoordinate;
}

What am I doing wrong? What requirements exists on coordinate property implementation?


text:
Q: Последовательный обход TreeSet Java Как реализовать последовательный обход дерева на Java?
(TreeSet)

A: Вам правильно сказали по поводу итераторов. Множества Set (TreeSet) реализуют базовый интерфейс Collection, который в свою очередь реализует Iterable. Это значит что перебирать можно for each
Set<String> ts = new TreeSet<>();
        ts.add("s1");
        ts.add("s0");
        for (String s : ts) {
            System.out.println(s);
        }


text:
Q: SQLSTATE[HY000] [2002] Not a directory when doctrine:schema:create I'm currently programming in Symfony2 (following this tutorial: tutorial.symblog.co.uk, and when I execute a:
php app/console doctrine:schema:create

I get:
[PDOException]
SQLSTATE[HY000] [2002] Not a directory

Here is my parameters.yml file:
parameters:
    database_driver: pdo_mysql
    database_host: localhost
    database_port: '3306'
    database_name: symblog
    database_user: root
    database_password: ~
    database_path: /Applications/MAMP/tmp/mysql/mysql.sock
    mailer_transport: gmail
    mailer_host: smtp.gmail.com
    mailer_user: ~
    mailer_password: ~
    locale: en
    secret: ~

I know the username and password are correct for the database, and for the mailer.
As you can see, I'm using MAMP, and my phpMyAdmin is able to connect, and everything else is fine. Please help.
Thanks in advance!

A: Create symlink from local mysql.sock to MAMP:
sudo mkdir /var/mysql
sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock
sudo chown _mysql /var/mysql/mysql.sock
sudo chmod 777 /var/mysql/mysql.sock


text:
Q: How to call multiple actions in View in ASP.NET MVC? Problem is:
I am using a textbox to get a string q and want to pass it to 3 different actions in search controller. i.e. action1(string q), action2(string q) and so on
Now syntax of my action:
 public ActionResult action1(string q)
  {
   var mydata = from p in fab //LINQ logic
                select new action1class
                { data1=p //assignment };
   return View("_partialAction1", mydata);
  }

Similarly there are two other actions.
I am using 3 different actions because my LINQ logic gets data from 3 different sources so there different mydata needs to be created.
My problem is: I am trying that when I click on 'search' Button of textbox then all the 3 actions should run and generate partial view one below other in some
 tags.
I tried to use ajax.BeginForm but it can only call one action at a time
@using (Ajax.BeginForm("action1", "Search", new AjaxOptions
{
    HttpMethod = "GET",
    InsertionMode = InsertionMode.Replace,
    UpdateTargetId = "action1",
    LoadingElementId="progress"
}))

Also I tried to use ViewModel but the problem is that I was unable to pass a bigger model to the view along with these mydata kind of data obtained in LINQ's in the action. I have no clear idea of how to use viewmodel in this case.
Is the approach that I am using correct? Or can there be any other way? I want to show result of all actions with button click.

A: There are two types of actions are in MVC framework. The first ones are the main actions and they are invoked from the browser one at a time. The second type are called as Child Actions and these actions can't be invoked from the browser but from the views returned by the main actions. Multiple child actions can be called under a main action. So you have to look into child actions whether they help or not.
Ex.
// main action that returns a view
public ViewResult Index()
{
   var model = ...
   return View(model);
}

// couple of child actions each returns a partial view
// which will be called from the index view
[ChildActionOnly]
public PartialViewResult ChildAction1()
{
  var model = ...
  return PartialView(model);
}

[ChildActionOnly]
public PartialViewResult ChildAction2()
{
  var model = ...
  return PartialView(model);
}

// index view
Index.cshtml
@model ...

@Html.Action("ChildAction1");
@Html.Action("ChildAction2");

...

http://msdn.microsoft.com/en-us/library/ee839451.aspx

A: You can only have one action per request. If you want to have 3 different partial views for a singular click, you will need to construct a layout page that includes the 3 partial views how you want them and make sure that your action receives the proper parameters to perform all of the partial view rendering.

A: Why not pass the ViewModel to the partialViews. Make sure you have different properties in the ViewModel to hold the PartialView Specific data plus the search text. Here is an example:
Model
public class Product
{
    public string Name { get; set; }
    public string Type { get; set; }
    public string Class { get; set; }
}

ViewModel
public class ProductSearch
{
    public ProductSearch()
    {
        q = string.Empty;
        Product1 = new Product();
        Product2 = new Product();
    }
    public string q { get; set; }
    public Product Product1 { get; set; }
    public Product Product2 { get; set; }
}

_Partial1.cshtml
@model Test1.Models.ProductSearch

Product1

@Html.TextBoxFor(a => a.Product1.Name)

_Partial2.cshtml
@model Test1.Models.ProductSearch

Product2

@Html.TextBoxFor(a => a.Product2.Name)

ActualView.cshtml
@model Test1.Models.ProductSearch

@{
    ViewBag.Title = "ActualView";
}

ActualView

@using (Html.BeginForm())
{
    @:SearchText
    @Html.TextBoxFor(m => m.q)
    Html.RenderAction("_Partial1", Model);
    Html.RenderAction("_Partial2", Model);
    <input type="submit" runat="server" id="btnSubmit" />
}

Temp Data (you will be getting it from DB/ any other source)
private List<Product> ProductsToSearch()
{
     return new List<Product>() { new Product() { Name = "Product One", Class = "A", Type = "High" }, new Product() { Name = "Product Two", Class = "A", Type = "Low" }, new Product() { Name = "Product Three", Class = "B", Type = "High" } };
}

Controller Actions
    public ActionResult _Partial1(ProductSearch search)
    {
        Product Product1 = ProductsToSearch().Where(a => a.Class.Equals(search.q) && a.Type.Equals("High")).SingleOrDefault();
        search.Product1 = Product1;
        return PartialView(search);
    }

    public ActionResult _Partial2(ProductSearch search)
    {
        Product Product2 = ProductsToSearch().Where(a => a.Class.Equals(search.q) && a.Type.Equals("Low")).SingleOrDefault();
        search.Product2 = Product2;
        return PartialView(search);
    }

    [HttpPost]
    public ActionResult ActualView(ProductSearch search)
    {
        return View(search);
    }

    public ActionResult ActualView()
    {
        ProductSearch search = new ProductSearch();
        return View(search);
    }

Now if you enter 'A' for SearchText and hit Submit Query you will get two different results (basically common search text is used and based on the search query in each partial view it has generated different results)


text:
Q: using jQuery Mobile in Yii 2 i'm a new Yii 2 develpoer !
i create a gridview like below :
<?php Pjax::begin()?>
    <?= GridView::widget([
        'dataProvider'   => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\ActionColumn'],
            'id',
            'countrydate',
            'countryName'=>[
                'attribute'=>'countryName',
                'content' => function($model,$key,$index,$column) {
                      return Html::a(
                '
'
                   .''
                     .''.$model->countryName.''
                   .''
                   .'
'
                     .'
enter the new data
'
                     .'<input id="myinput'.$key.'" type="text" >'
                     .'<button onclick=showcountryCode(myinput'.$key.'.value,'.$key.') >Submit</button>'
                   .'
'
                .'
'
                        ,null
                        ,$options = [
                        'id'=>'countryCode'.$key,
                        'style'=>['border'=>'none' , 'background'=>'none'],
                    ]);
                }
            ],
            'countryName',
            'countrydate',
            'population',
            'fipsCode',
        ],
    ]); ?>
    <?php Pjax::end()?>

as you can see i use jQuery Mobile in My php file in  'countryName' .
now this picture is my website  Pic
but when i change the page my page will be somthing like this : enter image description here
as you can see all of the jQuery MObile line that were hidden suddenly show block in the new page and i have to refresh the page to fix this !!!
can anybody tell me what should i do to fix this ?

A: The problem here is that jQuery mobile's "auto features" do not reload when you change content dynamically (via pjax for instance).
In order for this to work you will need to run .enhanceWithin() after every pjax success event. I suggest adding the following to your page JS (not column):
$(document).on('pjax:success', function(data, status, xhr, options){
   $('body').enhanceWithin();
})

For previous version of jQuery Mobile (< 1.4) use .trigger('create') instead of .enhanceWithin().
See : jQuery Mobile does not apply styles after dynamically adding content


text:
Q: Mapping textid's to text I have application written in spring, it communicate with another application, I received objects and now I have to map text id's to text in specific (given in object) language.
File with text id's and text looks like:
message.id=message
There is one file per language.
I'm looking for solution.

A: Spring provides some built-in support for internationalization in the form of MessageSources. See 3.13.1 Internationalization using MessageSource.

A: That's a job for the Java ResouceBundle class.
Basic usage:
ResourceBundle bundle = ResourceBundle.getBundle("path.on.the.classpath", requiredLocale);
String text = bundle.getString(textId);

You should handle MissingResourceExceptions etc. and maybe you even want to cache the bundles like some libraries/webframeworks do.


text:
Q: Is there any tool/method to generate database scripts for inserting data in SQLite? I am working on an Android application that maintains a SQLite database with around 40+ tables.The tables are supposed to have predefined data, so i need to insert bulk data in all tables. Is there any way using which i can create a data insertion script and run it just like they do in SQL Server and SQLyog instead of writing insert data function for insertion of data in each table.
I have researched about this but was unable to find any help. Can somebody please let me know if this is possible with SQLite Android or i have to see an alternative?
Any help will be appreciated.

A: Typically you would ship a pre-populated database as an asset populating the database using your favourtie SQLite Management tool (NaviCat, DBeaver, DBBrowser for SQlite and more).
The file (as all an SQLite Database is, is a single file) is then copied into the assets (assets/databases if using SQLiteAssethelper) folder, when developing the App.

*

*other support rollbak files may exist, but shouldn't when copying a database.

*the assets folder will likely have to be created.

When the App is first run the database is copied from the assets folder to it's final location, which is normally (recommended) in the data/data/the_package/databases/. See link above for SQLiteAssetHelper that does this on your behalf.
The above is perhaps the most efficient way startup wise, although the App will have a little bit of bloat as two copies of the database will exist.
You can build data from files. These could be JSON/GSON, CSV's are even SQL e.g. exported from your SQLite manage tool (or perhaps from other database tools).
You could, if the data required permits build the data using SQL to generate the data on the fly e.g.
WITH cte(cnt,ts,sid,t,p) AS
    (
        SELECT
          1,
            '1971-01-01 00:00:00',
            1,
            (ABS(random()) % 3000) / 99.35
            , ABS(random()) % 25 / 99.35
            AS b
        UNION ALL
        SELECT
            cnt + 1,
            datetime('1971-01-01 00:00:00','+'||(cnt / 96)||' days','+'||((cnt / 4) % 24)||' hours'),
            ((cnt % 4) +1),
            (ABS(random()) % 3000) / 99.35
            , ABS(random()) % 25 / 99.35
            FROM cte AS d
            LIMIT 8760 * 4 * 10
    )
-- SELECT * FROM cte;
INSERT INTO log SELECT ts,sid,t,p FROM cte;
;

This builds data for every hour of the day of the year for 10 years with 4 rows per hour. i.e. 350,400 rows.


text:
Q: How do I add runtime dependency for java with jruby I've create a wrapper gem for connecting to a tibco queue & uploaded that gem to my local gemserver. When I try to include the wrapper gem in other projects, I get the following error:
Bundler could not find compatible versions for gem "jruby-jms":
  In Gemfile:
    jruby-jms (>= 1.2.0, ~> 1.2) java

    tibco_client (>= 0) java depends on
      jruby-jms (>= 1.2.0, ~> 1.2) ruby

    jruby-jms (>= 0) java

    jruby-jms (>= 0) ruby
    Could not find gem 'jruby-jms (>= 1.2.0, ~> 1.2) ruby in any of the sources

I am trying to figure out how to list the runtime dependency but I can't find any instruction or examples:
spec.platform      = 'java'
spec.add_runtime_dependency 'jruby-jms', '~> 1.2', '>= 1.2.0'

Does anybody have experience in resolving something like this? I'm using jruby-1.7.19 (also tried 1.7.4, same result).

A: I found the problem was in my Gemfile. Syntax found on stackoverflow.
gem 'tibco_client', :source => 'http://gemserver:9292', :platforms => 'jruby'


text:
Q: Conversion failed when converting the varchar value '1,409.32 ' to data type int I have a USRDEF05 varchar(30) column in SOP10106 table declared as column that contains all numbers, when I try to execute below query I am getting conversion error.
Select
    DETAIL.SUBTOTAL as Sub_Total,
    CASE
       when USERDEF.USRDEF05 <> ' ' THEN USERDEF.USRDEF05
       ELSE 0
    END as Winsys
FROM
    SOP10100 DETAIL
Right JOIN
    SOP10106 USERDEF ON USERDEF.soptype = DETAIL.soptype
WHERE
    BACHNUMB ='WINSYS112012'

Can anybody give me an idea how to solve this error?

A: Try this -
CASE when ISNUMERIC(USERDEF.USRDEF05) <> 0 THEN
CAST(CAST(USERDEF.USRDEF05 as DECIMAL) as int) ELSE 0 END as Winsys

NOTE:- This will round off the decimal value to nearest integer.

eg:- if your value is 1409.32, the resulting int value is 1409
if your value is 1409.64, then resulting int value is 1410

A: Because your database schema is incorrect (numbers are not supposed to stored as text), then next incorrect statement should work also:
Select
    DETAIL.SUBTOTAL as Sub_Total,
    CASE
       when USERDEF.USRDEF05 <> ' ' THEN USERDEF.USRDEF05
       ELSE '0'
    END as Winsys

A: I am really don't what you  try to receive because USRDEF05 is string but seems you want that Winsys will be numeric.
Here are a couple ways:
Winsys is string
Select
DETAIL.SUBTOTAL as Sub_Total,
CASE
   when USERDEF.USRDEF05 <> ' ' THEN USERDEF.USRDEF05
   ELSE '0'
END as Winsys

Winsys is numeric
Select
DETAIL.SUBTOTAL as Sub_Total,
CASE
   when USERDEF.USRDEF05 <> ' ' THEN CONVERT(MONEY, USERDEF.USRDEF05, 1)
   ELSE 0
END as Winsys

A: I guess the problem is not in this value 1,409.32
Try to run this query using ISNUMERIC() function:
Select
    DETAIL.SUBTOTAL as Sub_Total,
    CASE
       when isnumeric(USERDEF.USRDEF05) = 1
            THEN cast(USERDEF.USRDEF05 as decimal(12,2))
       ELSE 0
    END as Winsys
FROM
    SOP10100 DETAIL
Right JOIN
    SOP10106 USERDEF ON USERDEF.soptype = DETAIL.soptype
WHERE
    BACHNUMB ='WINSYS112012'

And also check where is an error:
select USRDEF05 from USERDEF
where isnumeric(USERDEF.USRDEF05) = 0
and USERDEF.USRDEF05 <> ' '


text:
Q: PHP won't update When I run php -v, I get the following:
WARNING: PHP is not recommended
PHP is included in macOS for compatibility with legacy software.
Future versions of macOS will not include PHP.
PHP 7.3.24-(to be removed in future macOS) (cli) (built: May  8 2021 09:40:37) ( NTS )
Copyright (c) 1997-2018 The PHP Group
Zend Engine v3.3.24, Copyright (c) 1998-2018 Zend Technologies

When I run brew upgrade php I get Warning: php 8.1.1 already installed. How can I switch to from 7.3.24 to 8.1.1?

A: I ran echo 'export PATH="/usr/local/opt/php@8.1/bin:$PATH"' >> ~/.bash_profile then source ~/.bash_profile, and I am now getting the latest version.


text:
Q: Why does maven use my internal repository before my local repository? when I am doing development I often need to change a dependency, but I'm not ready to deploy my changes.  For example, I'm working on project Foo and I realize I need to add a method to the common library.  Before deploying this change to our internal repository, I would like to install the changes to common library (mvn install) and recompile Foo to use the common library in the local repository (note that I'm using all SNAPSHOT versions).
However, after I mvn install my common library, when I recompile Foo it doesn't use the new common library--it keeps using the latest SNAPSHOT of common library in the internal repository.  If I deploy the changed common library, Foo picks it up immediately.
How can I get maven to look first in the local repository?
UPDATE: when the file is installed into the local repository, it gets a name like foo-1.0.0-SNAPSHOT.jar, but when I deploy it, it gets a timestamp foo-1.0.0-20111104.191316-23.jar.  I think this is why the remote artifact gets pulled each time.  Any idea why mvn install is not working like mvn deploy?  Does it have to do with the fact that I have a snapshot repository set up for deploy?

A: By default, Maven checks for new versions of SNAPSHOT artifacts once per day. When it does this check, it will download SNAPSHOTS from remote repos that are newer than what you have locally. Either your artifact timestamps are out of sync and you're doing something to override Maven's update policy (like calling it with -U or setting the udpatePolicy to "always"), or else the local repository you're installing the artifact to isn't the same one you're subsequently running Maven against. What you're describing isn't typical Maven behavior. For a better answer, give more details in your question.
One indicator you can look for: after you install your common artifact, when you next compile Foo, does Maven download the common artifact again? If so, then it really is getting it from the remote, and you need to check your update settings. If not, then you have something strange going on locally.

A: You can try this option. This worked for me.
In your project's main pom.xml change 'snapshots' enabled setting to 'false'.
<repository>
    <id>yourRepo</id>
    <name>Repository</name>
    <url>http://your.repo.com/repo</url>
    <snapshots>
        <enabled>false</enabled>
    </snapshots>
</repository>


text:
Q: How can I do an incremental load based on record ID in Dagster I am trying to consume an HTTP API in my Dagster code. The API provides a log of "changes" which contain an incrementing ID. It supports an optional parameter fromUpdateId, which lets you only fetch updates that have a higher ID than some value.
This should let me do incremental loads, by looking at the highest update ID I have seen so far, and providing this as the parameter.
How can I accomplish this in Dagster? I am thinking it should be possible to write the highest ID as metadata when I materialize the asset. The metadata would then be available the next time the asset is materialized.

A:
I am thinking it should be possible to write the highest ID as metadata when I materialize the asset. The metadata would then be available the next time the asset is materialized.

That sounds like the right approach to me.
Here's some Python code that implements that approach:
from dagster import asset, Output

@asset
def asset1(context):
    asset_key = context.asset_key_for_output()
    latest_materialization_event = context.instance.get_latest_materialization_events(
        [asset_key]
    ).get(asset_key)

    if latest_materialization_event:
        materialization = (
            latest_materialization_event.dagster_event.event_specific_data.materialization
        )
        metadata = {entry.label: entry.entry_data for entry in materialization.metadata_entries}
        cursor = metadata["cursor"].value
    else:
        cursor = 0

    return Output(value=..., metadata={"cursor": cursor + 1})


text:
Q: add a username field to login form with accounts-entry package i installed the account-entry package.
in the default configuration this package request an Email for authentication.
How can i add a username field to the signIn/logIn from that will persists in DB.

A: All i nedded to do is change the passwordSignupFields attribute to 'USERNAME_AND_EMAIL' in the package. (/packages/accounts-entry/client/entry.coffee)

A: No need to fiddle with "/packages/accounts-entry/client/entry.coffee". Just do something like:
AccountsEntry.config({
   passwordSignupFields: 'USERNAME_AND_EMAIL'
});


text:
Q: Reading Paul Dirac's "Principles of Quantum Mechanics" I have a similair question to the question here, but regarding a different book.
"Principles of Quantum Mechanics" is a 1930 work by British Nobel laureate Paul Dirac. The wikipedia article on this book states that there have been a couple of editions (with improvements and additions), the latest being the 4th edition, published in 1958 (6 years before the Feynman lectures were published). This is a long time ago and I'm wondering if parts of the book are outdated, and if so, which ones and why?

A: Dirac did the last revision of that book in 1967, in the chapter of QED.
The book is 100% valid, nothing is outdated. You may only notice some slight difference of style with more modern books, in the absence of drawings and sometimes in the notation (most integration indices are not explicit, for instance). There aren't any exercises as well, but nevertheless it is a very good book, well structured and very clear.
Together with Sakurai's Modern Quantum Mechanics, it is the best book for mastering QM directly in the Dirac kets and bras notation.

A: Dirac's book was once thought to be a very hard book to understand
(and because of its yellow cover, was called "the yellow terror",
an shared by Norbert Wiener's book "The Theory of the Fourier Integral")
but is actualy an extremely lucid account.
Its methodical treatment makes up for the lack of figures and pyrotechnics.
Be prepared to read it slowly - Dirac was famous for not wasting words - and rereading passages after reaching a deeper understanding.

A: I can't recommend anything written by Dirac as an introduction to the concepts in Quantum Physics.
The two most common textbooks for a beginner (which include exercises) are "Quantum Mechanics" by Alastair Rae. (most recent update 2008) and
"Introduction to Quantum Mechanics" by David Griffith (Most recent update 2004).
Both books cover near identical material, but have different examples and different approaches.
From there, a good continuation point would be "Introduction to Elementary Particles" also by David Griffith.
Finally, after all that and you still want more, I'd recommend An "Introduction to Quantum Field Theory" by Michael Peskin and Daniel Schroeder, this book covers the same material that Dirac's book, but is considered a lot more approachable. If you somehow get through all this, you know more Quantum Physics than most Physics graduates.
As a matter of fact, Peskin and Schroeder is reading material for people taking their Theoretical Physics PhD!

A: The title of the book gives it away.
It's the Principles of QM. i.e the actual mathematical structure of the theory presented in a bare-bones, dry-as-dust format. It even states on the cover that it's a monograph, intended as a reference work for researchers and advanced students of the subject.
It's very thorough and as concise as possible so that reading it really requires a reasonable grasp of the subject to begin with. That is also why it's actually quite a slim volume despite the depth of cover. I don't remember seeing a single figure or illustration in the entire book.
Besides all that, although physics may not have come a long way since it was published, teaching techniques certainly have. IMO It would be a cruel trick to offer a textbook of that period to a modern student.


text:
Q: Handling cache beyong Nginx server and webpack js and css versioning I have a React nodejs app running on EC2.
I have set up 3 instances of it beyond Nginx for the load balancing.
I have also enabled cache in the Nginx configuration.
Basically everything should be cached beside different versions of app.js which holds the bundled React code and style.css which is also bundled.
I would like to add a version number in the js and css src link (e.g http://mywebsite.com/app.js?1.0)
My question is, can I automate this operation with webpack? Is this the way to go?

A: html-webpack-plugin is your friend here.
Instead of creating your index.html file, allow webpack to do it for you.
var HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {

    entry: "./index.js",
    output: {
        filename: "./dist/app.bundle.[hash].js"
    },
    plugins: [
        new HtmlWebpackPlugin({
            hash: true,
            filename: './dist/index.html'
        })
   ]

}

This will add the output script into index.html automatically and will generate a hash for the file.


text:
Q: Django Wagtail Jinja2 include_block tag not passing variables I have the following very simple statement to render blocks in wagtail.
{% for block in blocks %}
    {% include_block block %}
{% endfor %}

The for loop works and iterates over the blocks as does the template tag include_block. The variable 'block' however is not accessible in the template executed by include_block.
{% set background_image = block.background_image.image %}

The above statement called in the template called by include_block throws the following error.
'block' is undefined

This does not really make sense since the documentation for Wagtail's include_block states that variables get passed down into the called template.
http://docs.wagtail.io/en/v1.9/advanced_topics/jinja2.html#include-block
I have the following statement in order to explicitly pass in variables but it still does not work,
 {% include_block block with context %}

A: It is indeed surprising that block doesn't get passed down and might constitute a bug (edit: see comments below for further discussion on that matter)
That being said, in a block template, the block value is accessible as the variable value (see 6th paragraph of the StreamField template rendering section).


text:
Q: Optimization Metric for Compilers I'm very green to the compiler development scene.
Is there a specific way to measure the effectiveness of a compiler's optimizations, or would I simply compare execution times between direct compilation and optimized output?
This is not an open ended question, I'm not looking for somebody to count off QA software on their fingers or give me a list of wikipedia links. I want to know if I'm missing one big obvious thing that everyone else knows from having experience.

A: The most common performance metrics for compiler optimization is execution time for
a defined set of examples, or the size when comparing size-optimizations. Since a typical optimization often works better for one type of code and worse for another, the challenge is to define this set of examples, or benchmarks, to be as close to typical code as possible.


text:
Q: Formatting table to look nice I have the following code
#include "string"
#include "iostream"
#include "cmath"
#include "iomanip"

std::string name, item_name;
double loan_amount, annual_interest_rate;
int number_of_years;

double rate;
int number_of_payments;
double monthly_payments, total_amount_paid, total_interest_paid;

int main() {
    std::cout << "Welcome to the Monthly Payment Program." << std::endl << std::endl;
    std::cout << "Enter your name: ";
    std::getline(std::cin, name);
    std::cout << "Item being financed: ";
    std::getline(std::cin, item_name);
    std::cout << "Enter the loan amount: ";
    std::cin >> loan_amount;
    std::cout << "Enter the annual interest rate (in percentage): ";
    std::cin >> annual_interest_rate;
    std::cout << "Enter the duration of the loan in years: ";
    std::cin >> number_of_years;

    rate = annual_interest_rate / (12 * 100);
    number_of_payments = number_of_years * 12;
    monthly_payments = (rate * std::pow((1 + rate), number_of_payments))/(std::pow((1 + rate), number_of_payments) - 1);
    total_amount_paid = number_of_payments * monthly_payments;
    total_interest_paid = total_amount_paid - loan_amount;

    std::cout << std::endl;

    int width = 30;
    std::cout << std::left << std::setw(width) << "Name: " << name << std::endl;
    std::cout << std::left << std::setw(width) << "Item being financed: "  << item_name << std::endl;
    std::cout << std::left << std::setw(width) << std::setprecision(3) << "Monthly Interest Rate: "  << rate << "%" << std::endl;
    std::cout << std::left << std::setw(width) << "Number of Payments: "   << number_of_payments << std::endl;
    std::cout << std::left << std::setw(width) << std::setprecision(2) << "Monthly Payment: "  << "$ " << monthly_payments << std::endl;
    std::cout << std::left << std::setw(width) << std::setprecision(2) << "Total Amount Paid: "  << "$ " <<total_amount_paid << std::endl;
    std::cout << std::left << std::setw(width) << std::setprecision(2) << "Interest Paid: " << "$ " <<total_interest_paid << std::endl;
}

When I run the code it looks like this
Welcome to the Monthly Payment Program.
Enter your name: John Doe
Item being financed: Bass
Enter the loan amount: 15000
Enter the annual interest rate (in percentage): 8
Enter the duration of the loan in years: 3

Name:                         John Doe
Item being financed:          Bass
Monthly Interest Rate:        0.00667%
Number of Payments:           36
Monthly Payment:              $ 0.031
Total Amount Paid:            $ 1.1
Interest Paid:                $ -1.5e+04

I don't care that the calculations are all wrong, however, I need it to look like this

I have tried playing around with left, setw, and cannot seem to get it to look right.
How can I achieve the example?

A: Iomanip functions are not permanent. They need to be called before every output.
Example:
std::cout << std::left << std::setw( width )
          << "Interest Paid: "
          << "$ "
          << std::right << std::fixed << std::setw( width ) << std::setprecision( 2 )
          << total_interest_paid
          << std::endl;