text:
Q: Nginx not serving up Django admin static files An example 404 URL:
http://ip.address/static/admin/css/base.css
I'm not sure what I did wrong. Here's the associated files:
settings.py
STATICFILES_DIRS = [
  '/home/username/sitename/sitenameenv/lib/python3.5/site-packages/django/contrib/admin/static',
]
STATIC_URL = '/static/'
STATIC_ROOT = '/home/username/sitename/website/staticroot/'

Nginx config:
server {
    listen 80;
    server_name http://ip.address/;

    location = /favicon.ico { access_log off; log_not_found off; }
    location /static/ {
        root /home/username/sitename/website/;
    }

    location / {
        include proxy_params;
        proxy_pass http://unix:/home/username/sitename/sitename.sock;
    }
}

The regular static files are being served up correctly, and they were doing so also before I added STATIC_ROOT and used collectstatic, which I didn't think was necessary. My admin is getting 404s for its static files though.

A: UPDATE:
Running collectstatic will collect all your files in the directory specified by STATIC_ROOT settings.
So, you'll need to configure your Nginx server to serve your STATIC_ROOT folder at the /satic/ url:
location /static/ {
    # using `alias` instead of `root`
    # vvv
    alias   /home/username/sitename/website/staticroot/;
            #                                  ^^^
            # the full path to the STATIC_ROOT directory
}

Old Version (not very useful):
Why is this happening?
Here's one important thing to note: Django doesn't serve static files. I'm sure you know that.
So, when your browser requests for an admin css file from -  http://ip.address/static/admin/css/base.css, this request is intercepted by your Nginx server because you've mapped /static/ path to this directory - /home/username/sitename/website/static/.
Now, what happens next is, Nginx will try to find /admin/css/base.css file inside /home/username/sitename/website/static/. But there isn't any admin directory in there, hence this request ends up as a 404.

How to fix this?
You can map /static/admin/ url to that directory where the admin directory actually is. Example:
# put this before `location /static/` conf

location /static/admin/ {
    root   /home/username/sitename/sitenameenv/lib/python3.5/site-packages/django/contrib/admin/;
}

A: I have the same problem. My nginx server on Centos 7.6 can't access to static folder in path /home/user/app/mysyte/static/. In /var/log/nginx/error.log same error
open() "/home/user/app/mysyte/static/*.css" failed (13: Permission denied)

For solving and understanding this problem :=*

*

*run command getenforce

*if enforcing - cat /var/log/audit/audit.log | grep nginx
for me string with errrors looks like
type=AVC msg=audit(1558033633.723:201): avc:  denied  { read } for  pid=7758 comm="nginx" name="responsive.css" dev="dm-0" ino=17312394 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:user_home_t:s0 tclass=file permissive=0
type=SYSCALL msg=audit(1558033633.723:201): arch=c000003e syscall=2 success=no exit=-13 a0=564f710dd55d a1=800 a2=0 a3=68632f656d6f682f items=0 ppid=7757 pid=7758 auid=4294967295 uid=998 gid=996 euid=998 suid=998 fsuid=998 egid=996 sgid=996 fsgid=996 tty=(none) ses=4294967295 comm="nginx" exe="/usr/sbin/nginx" subj=system_u:system_r:httpd_t:s0 key=(null)

copy id of audit msg 1558033633.723:201

*run command grep yours_audit_id /var/log/audit/audit.log | audit2why
output for me
[root@uwsgi ~]# grep 1558034479.384:221 /var/log/audit/audit.log | audit2why
type=AVC msg=audit(1558034479.384:221): avc:  denied  { read } for  pid=7758 comm="nginx" name="responsive.css" dev="dm-0" ino=17312394 scontext=system_u:system_r:httpd_t:s0 tcontext=unconfined_u:object_r:user_home_t:s0 tclass=file permissive=0

        Was caused by:
        The boolean httpd_read_user_content was set incorrectly.
        Description:
        Allow httpd to read user content

        Allow access by executing:
        # setsebool -P httpd_read_user_content 1

So as you can see answer here setsebool -P httpd_read_user_content 1 when you run this command you see your static content


text:
Q: Can't open PDF: "Segmentation Fault (core dumped)" I'm new user in Linux system (I'm using Lubuntu 18.04 LTS), and I'm learning english yet, sorry if i made a mistake
I'm having trouble opening PDF documents. when I try to open my default reader (Okular) it can no longer display some of the '.pdf' documents I used most ... recently I upgraded some packages, and after that no pdf reader works. I'm getting the same error warning on all the readers I have installed (Okular, Evince, Atril).
This is the error warning that I get in the terminal:
$ okular

(okular:8965): Gtk-WARNING **: 23:28:29.044: Theme parsing error: gtk.css:597:14: not a number

(okular:8965): Gtk-WARNING **: 23:28:29.044: Theme parsing error: gtk.css:597:14: Expected a string.

(okular:8965): Gtk-WARNING **: 23:28:29.044: Theme parsing error: gtk.css:600:17: Expected a string.

(okular:8965): Gtk-WARNING **: 23:28:29.046: Theme parsing error: gtk.css:784:14: not a number

(okular:8965): Gtk-WARNING **: 23:28:29.047: Theme parsing error: gtk.css:784:14: Expected a string.

(okular:8965): Gtk-WARNING **: 23:28:29.047: Theme parsing error: gtk.css:787:17: Expected a string.

(okular:8965): Gtk-WARNING **: 23:28:29.050: Theme parsing error: gtk.css:1096:14: not a number

(okular:8965): Gtk-WARNING **: 23:28:29.050: Theme parsing error: gtk.css:1096:14: Expected a string.

(okular:8965): Gtk-WARNING **: 23:28:29.050: Theme parsing error: gtk.css:1099:17: Expected a string.

(okular:8965): Gtk-WARNING **: 23:28:29.060: Theme parsing error: gtk.css:2286:8: not a number

(okular:8965): Gtk-WARNING **: 23:28:29.060: Theme parsing error: gtk.css:2286:18: Using Pango syntax for the font: style property is deprecated; please use CSS syntax

(okular:8965): Gtk-WARNING **: 23:28:29.061: Theme parsing error: gtk.css:2291:8: not a number

(okular:8965): Gtk-WARNING **: 23:28:29.061: Theme parsing error: gtk.css:2291:18: Using Pango syntax for the font: style property is deprecated; please use CSS syntax

(okular:8965): Gtk-WARNING **: 23:28:29.071: Theme parsing error: gtk.css:4357:14: not a number

(okular:8965): Gtk-WARNING **: 23:28:29.071: Theme parsing error: gtk.css:4357:14: Expected a string.

(okular:8965): Gtk-WARNING **: 23:28:29.072: Theme parsing error: gtk.css:4419:12: not a number

(okular:8965): Gtk-WARNING **: 23:28:29.072: Theme parsing error: gtk.css:4419:12: Expected a string.

(okular:8965): Gtk-WARNING **: 23:28:29.072: Theme parsing error: gtk.css:4428:16: not a number

(okular:8965): Gtk-WARNING **: 23:28:29.072: Theme parsing error: gtk.css:4428:16: Expected a string.

(okular:8965): Gtk-WARNING **: 23:28:29.072: Theme parsing error: gtk.css:4443:22: not a number

(okular:8965): Gtk-WARNING **: 23:28:29.072: Theme parsing error: gtk.css:4443:22: Expected a string.

(okular:8965): Gtk-WARNING **: 23:28:29.072: Theme parsing error: gtk.css:4499:12: Expected a string.

(okular:8965): Gtk-WARNING **: 23:28:29.072: Theme parsing error: gtk.css:4501:16: not a number

(okular:8965): Gtk-WARNING **: 23:28:29.072: Theme parsing error: gtk.css:4501:16: Expected a string.

(okular:8965): Gtk-WARNING **: 23:28:29.073: Theme parsing error: gtk.css:4549:12: not a number

(okular:8965): Gtk-WARNING **: 23:28:29.073: Theme parsing error: gtk.css:4549:12: Expected a string.
QApplication: invalid style override passed, ignoring it.
   Segmentation Fault (core dumped) #(This part was in Portuguese, maybe in English it was different?)

Gtk-WARNINGS are common, and do not interfere with the usability of the program, but 'Segmentation fault (recorded core image)' is abnormal ..
Could you help me solve this problem?
the recently upgraded packages were:
2018-12-03 10:06:38 upgrade numix-icon-theme:all 0.3+933~201809192203~ubuntu18.04.1 0.3+934~201812011102~ubuntu18.04.1
2018-12-03 10:06:51 upgrade numix-icon-theme-square:all 18.10.03+201810041547~ubuntu18.04.1 18.12.01+201812011517~ubuntu18.04.1
2018-12-03 14:30:08 upgrade linux-generic:i386 4.15.0.39.41 4.15.0.42.44
2018-12-03 14:30:09 upgrade linux-image-generic:i386 4.15.0.39.41 4.15.0.42.44
2018-12-03 14:30:19 upgrade linux-headers-generic:i386 4.15.0.39.41 4.15.0.42.44
2018-12-03 14:30:20 upgrade linux-libc-dev:i386 4.15.0-39.42 4.15.0-42.45
2018-12-04 11:04:18 upgrade libperl5.26:i386 5.26.1-6ubuntu0.2 5.26.1-6ubuntu0.3
2018-12-04 11:04:20 upgrade perl:i386 5.26.1-6ubuntu0.2 5.26.1-6ubuntu0.3
2018-12-04 11:04:21 upgrade perl-base:i386 5.26.1-6ubuntu0.2 5.26.1-6ubuntu0.3
2018-12-04 11:04:23 upgrade perl-modules-5.26:all 5.26.1-6ubuntu0.2 5.26.1-6ubuntu0.3
2018-12-04 11:04:25 upgrade libfwupd2:i386 1.0.6-2 1.0.9-0ubuntu2
2018-12-04 11:04:26 upgrade fwupd:i386 1.0.6-2 1.0.9-0ubuntu2
2018-12-04 11:04:32 upgrade libpoppler-qt5-1:i386 0.62.0-2ubuntu2.2 0.62.0-2ubuntu2.4
2018-12-04 11:04:33 upgrade poppler-utils:i386 0.62.0-2ubuntu2.2 0.62.0-2ubuntu2.4
2018-12-04 11:04:34 upgrade libpoppler-glib8:i386 0.62.0-2ubuntu2.2 0.62.0-2ubuntu2.4
2018-12-04 11:04:35 upgrade libpoppler73:i386 0.62.0-2ubuntu2.2 0.62.0-2ubuntu2.4
2018-12-04 11:04:36 upgrade syncthing:i386 0.14.52 0.14.53
2018-12-04 22:52:41 upgrade chromium-browser-l10n:all 70.0.3538.77-0ubuntu0.18.04.1 70.0.3538.110-0ubuntu0.18.04.1
2018-12-04 22:52:43 upgrade chromium-browser:i386 70.0.3538.77-0ubuntu0.18.04.1 70.0.3538.110-0ubuntu0.18.04.1
2018-12-04 22:52:54 upgrade chromium-codecs-ffmpeg-extra:i386 70.0.3538.77-0ubuntu0.18.04.1 70.0.3538.110-0ubuntu0.18.04.1

I believe that perl, poppler and its libs were the packages that gave problem. I say this because was after these updates that I could no longer open the pdfs
I can still open some pdfs on my computer, but not all (unfortunately, I'm having this problem with my most important files)
thank you for your attention in advance

redpajama_set_name: RedPajamaStackExchange


text:
Q: autocomplete-plus blocked by dartlang in atom? I am using atom 1.9.8, with autocomplete-plus 2.31.0, and dartlang 0.6.35 and autocomplete seems blocked in dart files.  Works just fine in other file types.
Anyone else run into this?  Solutions?

A: The good news here is appears by 0.6.45 this is resolved!


text:
Q: Android Bluetooth Set Timeout for BluetoothSocket.connect(); Is there any chance to set a timeout for
BluetoothSocket.connect();

So that the method cancels after a certain amount of time ?
Thanks !

A: if you want to cancel the connect attempt if device is not connected in a certain amount of time, then run a thread.
runOnUiThread(new Runnable() {
    @Override
    public void run() {
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //Do something after 5 second
            }
        }, 5000);
    }
});


text:
Q: What does 'factors through' mean in this context? I'm trying to understand the proof of the Fundamental Theorem of Algebra in Theorem 3.7 here.
I can't get my head around this sentence though

If $p(z)$ has no roots at all, the map $p|_{S1(R)}$ factors through the complex plane $\mathbb{C}$ and is therefore nullhomotopic (as $\mathbb{C}$ is contractible).

I know that $\mathbb{C}$ is convex so if $p$ is a map into $\mathbb{C}$ then it is homotopic to any other map into $\mathbb{C}$. Does this help? Also surely any map into $\mathbb{C}\setminus\{0\}$ is a map into $\mathbb{C}$. Doesn't this make the whole thing vacuous?!
Many thanks in advance.

A: If $p(z)$ has no roots at all then it defines a map $\mathbb C \to \mathbb C - \{0\}$.  Therefore, in this case we can write $p\vert_{S^1(R)}$ as a composition
$$
S^1(R) \stackrel{i}{\to} \mathbb C \stackrel{p(z)}{\to} \mathbb C - \{0\}
$$
where the first map is the inclusion.  Since $\mathbb C$ is contractible, the map $p(z)$ is nullhomotopic so that the composition, which is $p\vert_{S^1(R)}$, is also nullhomotopic.
The reasoning it's called factoring is that we've decomposed the original map $p\vert_{S^1(R)}$ into a composition $p\circ i$.
Note that even if $p$ has roots, $p\vert_{S^1(R)}$ is still $p \circ i$ but now the functions in the homotopy may have 0 as a value.


text:
Q: Matrix exponential of a skew-symmetric matrix without series expansion I have the following skew-symmetric matrix
$$C = \begin{bmatrix}   0 & -a_3 &  a_2 \\
                     a_3 &    0 & -a_1 \\
                    -a_2 &  a_1 &    0 \end{bmatrix}$$
How do I compute $e^{C}$ without resorting to the series expansion of $e^{C}$? Shall I get a finite expression for it?
NB:  Values of $a_i$ s can't be changed.

A: A geometric proof.
$C$ is the matrix of $u\in \mathbb{R}^3\rightarrow a\times u$ where $a=[a_1,a_2,a_3]^T$. $\exp(C){\exp(C)}^T=I$ and $\det(\exp(C))>0$ ; then $\exp(C)\in O^+(3)$, that is a rotation $\exp(C)=R=Rot(\Delta,\theta)$. Note that $Ca=0$ implies $Ra=a$ and $\Delta$ is the oriented line defined by $a$.
After some calculations, $Trace(R)=1+2\cos(\theta)=1+2\cos(||a||)$. Moreover, let $b=[a_2,-a_1,0]^T$ ($b$ is orthogonal to $a$) ; we obtain $\dfrac{1}{{a_1}^2+{a_2}^2}||b\times Rb||=\sin(||a||)$. Conclusion $\theta=||a||$.

A: Let $x = \sqrt{a_1^2+a_2^2+a_3^2}$. You can verify that $C^3 = -(a_1^2+a_2^2+a_3^2)C = -x^2C$.
Hence, $C^{2m+1} = (-1)^mx^{2m}C$ and $C^{2m} = (-1)^{m-1}x^{2m-2}C^2$.
Therefore, $e^C = \displaystyle\sum_{n=0}^{\infty}\dfrac{1}{n!}C^n = I + \sum_{m=0}^{\infty}\dfrac{1}{(2m+1)!}C^{2m+1} + \sum_{m=1}^{\infty}\dfrac{1}{(2m)!}C^{2m}$
$= \displaystyle I + \sum_{m=0}^{\infty}\dfrac{(-1)^mx^{2m}}{(2m+1)!}C + \sum_{m=1}^{\infty}\dfrac{(-1)^{m-1}x^{2m-2}}{(2m)!}C^{2}$
$= \displaystyle I + \dfrac{1}{x}\sum_{m=0}^{\infty}\dfrac{(-1)^mx^{2m+1}}{(2m+1)!}C - \dfrac{1}{x^2}\sum_{m=1}^{\infty}\dfrac{(-1)^{m}x^{2m}}{(2m)!}C^{2}$
$= I + \dfrac{\sin x}{x}C + \dfrac{1-\cos x}{x^2}C^2$

A: $
\def\tss{\mathop{\bigotimes}\limits}
\def\dss{\mathop{\odot}\limits}
\def\bbR#1{{\mathbb R}^{#1}}
\def\a{\alpha}\def\b{\beta}\def\g{\gamma}\def\t{\theta}
\def\l{\lambda}\def\s{\sigma}\def\e{\varepsilon}
\def\n{\nabla}\def\o{{\tt1}}\def\p{\partial}
\def\E{{\cal E}}\def\F{{\cal F}}\def\G{{\cal G}}
\def\L{\left}\def\R{\right}\def\LR#1{\L(#1\R)}
\def\vec#1{\operatorname{vec}\LR{#1}}
\def\diag#1{\operatorname{diag}\LR{#1}}
\def\Diag#1{\operatorname{Diag}\LR{#1}}
\def\trace#1{\operatorname{Tr}\LR{#1}}
\def\qiq{\quad\implies\quad}
\def\grad#1#2{\frac{\p #1}{\p #2}}
\def\hess#1#2#3{\frac{\p^2 #1}{\p #2\,\p #3}}
\def\c#1{\color{red}{#1}}
\def\m#1{\left[\begin{array}{r}#1\end{array}\right]}
\def\notimplies{\;\not\!\!\!\implies}
$The following method can be utilized even if you do not have access to a simple series definition of the function but are able to evaluate it for any value in its domain by some black-box method.
The first insight is that, as a consequence of the Cayley-Hamilton theorem, any analytic function of an $n\times n$ matrix is equal to a polynomial of degree $(n-1)$ with scalar coefficients.
For example, in the case of the matrix $C$ above
$$f(C) = \b_0 I + \b_1C + \b_2C^2$$
The problem boils down to calculating the $\b_k$ coefficients.
The next insight is that, if $\l_k$ are the eigenvalues of $C$,
then $f(\l_k)$ are the eigenvalues of $f(C)$. Therefore, you can write an eigenvalue version of the polynomial
$$f(\l_k) = \b_0 + \b_1\l_k + \b_2\l_k^2$$
Substituting the eigenvalues of $C$ yields a $3\times 3$ linear system, which can be solved for the $\b_k$ coefficients. The eigenvalues of
$C$ are known to be $\{\pm i\a,0\}$ where
$${
a = \m{a_1\\a_2\\a_3},\qquad
\a = \big\|a\big\|_2=\frac{1}{\sqrt 2}\big\|C\big\|_F
}$$
The linear system
$$\eqalign{
&\b_0 + i\a\b_1 - \a^2\b_2 &= f(i\a) &\doteq f_p
 \quad&\big(f\;{\rm plus}\big) \\
&\b_0 - i\a\b_1 - \a^2\b_2 &= f(-i\a) &\doteq f_m
 \quad&\big(f\;{\rm minus}\big) \\
&\b_0  &= f(0) &\doteq f_z
 \quad&\big(f\;{\rm zero}\big) \\
}$$
can be solved by Cramer's Rule to obtain
$$\eqalign{
\b_0 &= f_z \qquad
\b_1 &= \frac{f_p-f_m}{2i\a} \qquad
\b_2 &= \frac{2f_z-(f_p+f_m)}{2\a^2} \\
}$$
Again, these formulas are valid for any function of $C$:
$\;\,$log()$,\;$ erf()$,\;$ sinh()$,\, \ldots$
Let's evaluate the coefficients in the case of exp()
$$\eqalign{
\b_0 &= e^0 = \o \\
\b_1 &= \frac{e^{i\a}-e^{-i\a}}{2i\a}
  = \frac{2i\sin(\a)}{2i\a}
  = \frac{\sin(\a)}{\a} \\
\b_2 &= \frac{2-(e^{i\a}+e^{-i\a})}{2\a^2}
 = \frac{2-2\cos(\a)}{2\a^2}
 = \frac{\o-\cos(\a)}{\a^2} \\
}$$
Therefore
$$\eqalign{
\exp(C) = I + \frac{\sin(\a)}{\a}\;C + \frac{\o-\cos(\a)}{\a^2}\;C^2 \\
\\
}$$
This idea of eigenvalue interpolation is associated with the
names of$\,$ Sylvester $\,$and$\,$ Hermite.


text:
Q: CONCAT and UPDATE in codeigniter php Hi I am trying to execute this query:
If I get anything in POST['domain'] then I want to update the md_user field for each user in the Table.

UPDATE NECOFFICE_users SET md_user = md5(concat(ext,'@192.168.50.1')) WHERE site_key = 'EB22-0000'

This query runs perfectly fine in PHPMYADMIN
And My Active Record Code is :
$user_table = $this->session->userdata('user_table');
$string_md = $this->input->post('domain');

$this->db->set("md_user",md5("CONCAT('ext',@$string_md)"));
$this->db->where('site_key', $site_session);
$this->db->update($user_table);
echo $this->db->last_query();

Now this what should be my code to perform the above query in codeigniter ?

A: It looks like you're using the PHP MD5 function, instead of MySQL's:
$this->db->set("md_user",array("md5(CONCAT('ext',@{$string_md}))"), FALSE);

Try that, looks like it should work.
Edit:
After looking up CI's set method, you might be better just building it up without using MySQL's functions:

$this->db->set("md_user",md5('ext@' . $string_md));


text:
Q: Tomboy failed to Sync: (500) INTERNAL SERVER ERROR
Possible Duplicate:
How do I get Tomboy Sync to work?

I use Tomboy notes, And I find it very useful to sync the notes through U1, But today when I tried to sync, It showed an error message Synchronisation failed or something similar, Without any explanation in details section.
That's the text of /.config/tomboy/tomboy.log:

07/05/2012 18.10.55 [INFO]: Initializing Mono.Addins
        07/05/2012 18.10.59 [ERROR]: Unparsable last-sync-date element in /home/christian/.config/tomboy/manifest.xml
        07/05/2012 18.11.18 [ERROR]: Caught exception. Message: The remote server returned an error: (500) INTERNAL SERVER ERROR.
        07/05/2012 18.11.18 [ERROR]: Stack trace for previous exception:   at System.Net.HttpWebRequest.CheckFinalStatus (System.Net.WebAsyncResult result) [0x00000] in :0
          at System.Net.HttpWebRequest.SetResponseData (System.Net.WebConnectionData data) [0x00000] in :0
        07/05/2012 18.11.18 [ERROR]: Rest of stack trace for above exception:    at System.Environment.get_StackTrace()
           at Tomboy.WebSync.Api.OAuth.MakeWebRequest(RequestMethod method, System.String url, System.Collections.Generic.List`1 parameters, System.String postData)
           at Tomboy.WebSync.Api.OAuth.WebRequest(RequestMethod method, System.String url, System.String postData)
           at Tomboy.WebSync.Api.OAuth.Get(System.String uri, IDictionary`2 queryParameters)
           at Tomboy.WebSync.Api.UserInfo.GetUser(System.String userUri, IWebConnection connection)
           at Tomboy.WebSync.WebSyncServer.BeginSyncTransaction()
           at Tomboy.Sync.SyncManager.SynchronizationThread()
           at System.Threading.Thread.StartInternal()
        07/05/2012 18.11.18 [ERROR]: Synchronization failed with the following exception: The remote server returned an error: (500) INTERNAL SERVER ERROR.
          at System.Net.HttpWebRequest.CheckFinalStatus (System.Net.WebAsyncResult result) [0x00000] in :0
          at System.Net.HttpWebRequest.SetResponseData (System.Net.WebConnectionData data) [0x00000] in :0
        07/05/2012 18.11.28 [ERROR]: Unparsable last-sync-date element in /home/christian/.config/tomboy/manifest.xml
        07/05/2012 18.12.17 [ERROR]: Unparsable last-sync-date element in /home/christian/.config/tomboy/manifest.xml
        07/05/2012 18.12.19 [ERROR]: Caught exception. Message: The remote server returned an error: (500) INTERNAL SERVER ERROR.
        07/05/2012 18.12.19 [ERROR]: Stack trace for previous exception:   at System.Net.HttpWebRequest.CheckFinalStatus (System.Net.WebAsyncResult result) [0x00000] in :0
          at System.Net.HttpWebRequest.SetResponseData (System.Net.WebConnectionData data) [0x00000] in :0
        07/05/2012 18.12.19 [ERROR]: Rest of stack trace for above exception:    at System.Environment.get_StackTrace()
           at Tomboy.WebSync.Api.OAuth.MakeWebRequest(RequestMethod method, System.String url, System.Collections.Generic.List`1 parameters, System.String postData)
           at Tomboy.WebSync.Api.OAuth.WebRequest(RequestMethod method, System.String url, System.String postData)
           at Tomboy.WebSync.Api.OAuth.Get(System.String uri, IDictionary`2 queryParameters)
           at Tomboy.WebSync.Api.UserInfo.GetUser(System.String userUri, IWebConnection connection)
           at Tomboy.WebSync.WebSyncServer.BeginSyncTransaction()
           at Tomboy.Sync.SyncManager.SynchronizationThread()
           at System.Threading.Thread.StartInternal()
        07/05/2012 18.12.19 [ERROR]: Synchronization failed with the following exception: The remote server returned an error: (500) INTERNAL SERVER ERROR.
          at System.Net.HttpWebRequest.CheckFinalStatus (System.Net.WebAsyncResult result) [0x00000] in :0
          at System.Net.HttpWebRequest.SetResponseData (System.Net.WebConnectionData data) [0x00000] in :0
        07/05/2012 18.21.01 [ERROR]: Caught exception. Message: The remote server returned an error: (500) INTERNAL SERVER ERROR.
        07/05/2012 18.21.01 [ERROR]: Stack trace for previous exception:   at System.Net.HttpWebRequest.CheckFinalStatus (System.Net.WebAsyncResult result) [0x00000] in :0
          at System.Net.HttpWebRequest.SetResponseData (System.Net.WebConnectionData data) [0x00000] in :0
        07/05/2012 18.21.01 [ERROR]: Rest of stack trace for above exception:    at System.Environment.get_StackTrace()
           at Tomboy.WebSync.Api.OAuth.MakeWebRequest(RequestMethod method, System.String url, System.Collections.Generic.List`1 parameters, System.String postData)
           at Tomboy.WebSync.Api.OAuth.WebRequest(RequestMethod method, System.String url, System.String postData)
           at Tomboy.WebSync.Api.OAuth.Get(System.String uri, IDictionary`2 queryParameters)
           at Tomboy.WebSync.Api.UserInfo.GetUser(System.String userUri, IWebConnection connection)
           at Tomboy.WebSync.WebSyncServer.UpdatesAvailableSince(Int32 revision)
           at Tomboy.Sync.SyncManager.BackgroundSyncChecker()
           at Tomboy.Sync.SyncManager.m__3E(System.Object o)
           at System.Threading.Timer+Scheduler.TimerCB(System.Object o)
And the text of ./config/tomboy/Manifest.xml.

      0001-01-01T00:00:00.0000000+01:00
      -1

How should I fix it?
That's not the first time I have problem with tomboy sync. It never worked with Ubuntu 11.10. I had to upgrade my OS to make it work again.
If the solution is too complicated or impossible, could you suggest me a good alternative? Maybe a tool of Firefox? I tried with Evernote but it doesn't work well with long notes

A: I read around 10 bug reports related to Tomboy failing sync, some pretty dated and still present. It's not just one bug, and your bug (the same I get here) is: (500) INTERNAL SERVER ERROR. There are other bugs, some of which have workarounds.
This problem is not a Tomboy bug. It's perhaps not U1 bug, but more like "lost in translation" issue, i.e. https://bugs.launchpad.net/ubuntuone-servers/+bug/554313
What I do now, and see it as sane approach, is to use local folder option for sync. Then sync this local folder with you favorite online storage service (i.e. Dropbox, Ubuntu One, whatever...).
It's basically same thing, but on the safe route


text:
Q: How to check if a number is smaller or bigger or between two values? I have to check if input number is smaller or bigger or between two others numbers. I made the correct function but is there any way to write this function more readable and shorter? When at least one of input parameters is not a number the function should return NaN.

function order(num, a, b) {
  if (a > b) {
    return NaN;
  }
  if (num < a) {
    return -1;
  }
  if (num > b) {
    return 1;
  }
  if (a <= num && num <= b) {
    return 0;
  }
  return NaN;
}

// Use case examples
console.log(order(5, 10, 20));
console.log(order(10, 10, 20));
console.log(order(15, 10, 20));
console.log(order(20, 10, 20));
console.log(order(25, 10, 20));

console.log(order(15, 20, 10));
console.log(order(15, 10, undefined));
console.log(order(15, undefined, 20));
console.log(order(15, undefined, undefined));
console.log(order(undefined, 10, 20));

A: By the looks of it, you have an inherent assumption in the function that a <= b. It is good to have something like an assertion that verifies this condition. See for example What is "assert" in JavaScript?.
That aside, this is an example of a shorter code. Don't think it is any more readable though. At first I thought I reduced the number of if statements, but clearly that's not the case. However, I do think weeding out the non "number" types is important at the beginning rather than the end, and this is more explicit.

function order(num, a, b) {
  if (typeof num != "number" || typeof a != "number" || typeof b != "number")
      return NaN;
  if (num >= a) {
      if (num > b)
          return 1;
      return 0;
  }
  return -1;
}

// Use case examples
console.log(order(5, 10, 20));
console.log(order(10, 10, 20));
console.log(order(15, 10, 20));
console.log(order(20, 10, 20));
console.log(order(25, 10, 20));

console.log(order(15, undefined, 20));
console.log(order(15, undefined, undefined));
console.log(order(undefined, 10, 20));


text:
Q: TailwindCSS set same height for Grid Card Image I am using tailwind css for responsive grid card list. Card has image and title. I can't control the image size. So height of card is not same because of some small image size. At img tag, if I gave heigh, h-46, all image are same but aspect ratio is not working.

  {artists && artists.length > 0 ? (

      {artists.map((artist, index) => {
        return (

 {
              onClickHandler(slide.id);
            }}
          >

                <button className="absolute top-1/2 right-1/2 -mr-3 -mt-3 rounded-lg opacity-0 group-hover:opacity-100">
                  <PlayIcon className="text-primary" />
                </button>

{artist.name}

        );
      })}

  ) : (

  )}


text:
Q: Shuffle the records of a list of text files in one single file I have a list of text files file1.txt, file2.txt, file3.txt .. filen.txt that I need to shuffle creating one single big file as result *.
Requirements:
   1. The records of a given file need to be reversed before being shuffled
   2. The records of a given file should keep the reversed order in the destination file
   3. I don't know how many files I need to shuffle so the code should be generic as possible (allowing to declare the file names in a list for example)
   4. Files could have different sizes
Example:

File1.txt
---------
File1Record1
File1Record2
File1Record3
File1Record4

File2.txt
---------
File2Record1
File2Record2

File3.txt
---------
File3Record1
File3Record2
File3Record3
File3Record4
File3Record5

the output should be something like this:

ResultFile.txt
--------------
File3Record5   -|
File2Record2    |
File1Record4    |
File3Record4   -|
File2Record1    |
File1Record3    |-->File3 records are shuffled with the other records and
File3Record3   -|   are correctly "reversed" and they kept the correct
File1Record2    |   ordering
File3Record2   -|
File1Record1    |
File3Record1   -|

* I'm not crazy; I have to import these files (blog posts) using the resultfile.txt as input
EDIT:
the result could have any sort you want, completely or partially shuffled, uniformly interleaved, it does not matter. What it does matter is that points 1. and 2. are both honoured.

A: you could try the following: in a first step you zip() the reversed() items of the list:
zipped = zip(reversed(lines1), reversed(lines2), reversed(lines3))

then you can concatenate the items in zipped again:
lst = []
for triple in zipped:
    lst.append(triple)

finally you have to remove all Nones added by zip()
lst.remove(None)

A: What about this:
>>> l = [["1a","1b","1c","1d"], ["2a","2b"], ["3a","3b","3c","3d","3e"]]
>>> while l:
...     x = random.choice(l)
...     print x.pop(-1)
...     if not x:
...         l.remove(x)

1d
1c
2b
3e
2a
3d
1b
3c
3b
3a
1a

You could optimize it in various ways, but that's the general idea. This also works if you cannot read the files at once but need to iterate them because of memory restrictions. In that case

*

*read a line from the file instead of popping from a list

*check for EOF instead of empty lists

A: A simple solution might be to create a list of lists, and then pop a line off a random list until they're all exhausted:
>>> import random
>>> filerecords = [['File{0}Record{1}'.format(i, j) for j in range(5)] for i in range(5)]
>>> concatenation = []
>>> while any(filerecords):
...     selection = random.choice(filerecords)
...     if selection:
...         concatenation.append(selection.pop())
...     else:
...         filerecords.remove(selection)
...
>>> concatenation
['File1Record4', 'File3Record4', 'File0Record4', 'File0Record3', 'File0Record2',
 'File4Record4', 'File0Record1', 'File3Record3', 'File4Record3', 'File0Record0',
 'File4Record2', 'File2Record4', 'File4Record1', 'File3Record2', 'File4Record0',
 'File2Record3', 'File1Record3', 'File2Record2', 'File2Record1', 'File3Record1',
 'File3Record0', 'File1Record2', 'File2Record0', 'File1Record1', 'File1Record0']

A: filenames = [ 'filename0', ... , 'filenameN' ]
files = [ open(fn, 'r') for fn in filenames ]
lines = [ f.readlines() for f in files ]

output = open('output', 'w')

while len(lines) > 0:
    l = random.choice( lines )
    if len(l)==0:
        lines.remove(l)
    else:
        output.write( l.pop() )

output.close()

One bite may seem magical here: the lines read from files don't need reversing, because when we write them to output file we use list.pop() which takes items from the end of the list (here the contents of the file).

A: I strongly recommend investing some time to read Generator Tricks for Systems Programmers(PDF). It's from a presentation at PyCon 08 and it deals specifically with processing arbitrarily large log files. The reversal aspect is an interesting wrinkle, but the rest of the presentation should speak directly to your problem.

A: filelist = (
    'file1.txt',
    'file2.txt',
    'file3.txt',
)

all_records = []

max_records = 0
for f in filelist:
    fp = open(f, 'r')
    records = fp.readlines()
    if len(records) > max_records:
        max_records = len(records)
    records.reverse()
    all_records.append(records)
    fp.close()

all_records.reverse()

res_fp = open('result.txt', 'w')
for i in range(max_records):
    for records in all_records:
        try:
            res_fp.write(records[i])
        except IndexError:
            pass
    i += 1
res_fp.close()

A: I'm not a python zen master, but here's my take.
import random

#You have you read everything into a list from at least one of the files.
fin = open("filename1","r").readlines()
# tuple of all of the files.
fls = ( open("filename2","r"),
       open("filename3","r"), )

for fl in fls: #iterate through tuple
   curr = 0
   clen = len(fin)
   for line in fl: #iterate through a file.
      # If we're at the end or 1 is randomly chosen, insert at current position.
      if curr > clen or round(random.random()):
         fin.insert(curr,line)
         clen = len(fin)
      curr +=1 #increment current index.

# when you're *done* reverse. It's easier.
fin.reverse()

Unfortunately with this it becomes obvious that this is a weighted distrobution. This can be fixed by calculating the length of each of the files and multiplying the call to random by certain probability based on that. I'll see if I can't provide that at some later point.

A: A possible merging function is available in the standard library. It's intended to merge sorted lists to make sorted combined lists; garbage in, garbage out, but it does have the desired property of maintaining sublist order no matter what.
def merge_files(output, *inputs):
    # all parameters are opened files with appropriate modes.
    from heapq import merge
    for line in heapq.merge(*(reversed(tuple(input)) for input in inputs)):
        output.write(line)


text:
Q: RecyclerView Multiple View types (View Holders) Handle item Selection count state I'm having a sectioned recyclerview with title header and items under that catergoty. I have two viewHolders one for the title, and other for the items that come under that category. Here is my Adapter.
public class MenuAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

public static final String TAG = MenuAdapter.class.getSimpleName();
private Context mContext;
private ItemClickListener itemClickListener;
private List<HeterogeneousObject> heterogeneousObjects;

public MenuAdapter(Context mContext, CartHelper helper) {
    this.mContext = mContext;
    heterogeneousObjects = new ArrayList<>();

}

public void itemClickListenerCallback(ItemClickListener itemClickListenerCallback) {
    this.itemClickListener = menuItemClickListenerCallback;
}
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    if (viewType == 0) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_single_cuisine_rv, parent, false);
        return new MenuAdapterViewHolder(view);

    } else {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_single_cuisine_menu_items, parent, false);
        return new RecycledGridViewHolder(view);
    }

}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder viewHolder, int position) {
    HeterogeneousObject object = heterogeneousObjects.get(position);
    if (object.getItemType() == 0) {
        if (object.getCuisine() != null) {
            MenuAdapterViewHolder holder = (MenuAdapterViewHolder) viewHolder;
            holder.cuisineName.setText(object.getCuisine().getCuisine_name());

        }
    } else {
        if (object.getMenuItem() != null) {
            RecycledGridViewHolder holder = (RecycledGridViewHolder) viewHolder;
            holder.dishName.setText(object.getMenuItem().getItemName());
            holder.dishPrice.setText(mContext.getString(R.string.rupee_symbol, object.getMenuItem().getItemPrice() * 0.01));

            if (object.getMenuItem().getIsVeg()) {
                holder.vegNonVegIndicator.setImageDrawable(mContext.getResources().getDrawable(R.drawable.veg_symbol));
                //holder.vegNonVegIndicator.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_veg_indicator));
            } else if (!object.getMenuItem().getIsVeg()) {
                holder.vegNonVegIndicator.setImageDrawable(mContext.getResources().getDrawable(R.drawable.non_veg_symbol));
                //holder.vegNonVegIndicator.setImageDrawable(mContext.getResources().getDrawable(R.drawable.ic_non_veg_indicator));
            }
            Single<CartSelection> selection = cartHelper.getCartSelectionById(Long.parseLong(object.getMenuItem().getItemId()));
            selection.subscribe(new DisposableSingleObserver<CartSelection>() {
                @Override
                public void onSuccess(CartSelection cartSelection) {
                    if (cartSelection != null) {
                        holder.incDecButton.setNumber(cartSelection.getQty(), true);
                    }
                }

                @Override
                public void onError(Throwable e) {

                }
            });
            holder.bind(object.getMenuItem(), menuItemClickListener);
        }
    }

}

@Override
public int getItemCount() {
    return heterogeneousObjects.size();
}

@Override
public int getItemViewType(int position) {
    super.getItemViewType(position);
    if (heterogeneousObjects.get(position).getItemType() == 0) {
        return 0;
    } else {
        return 1;
    }
}

}
Here is my View Holder 1
public class RecycledGridViewHolder extends RecyclerView.ViewHolder {
    @BindView(R.id.tv_si_dish_name)
    TextView dishName;
    @BindView(R.id.tv_si_dish_price)
    TextView dishPrice;

    @BindView(R.id.btn_id_item_dish_grid)
    IncDecButton incDecButton;
    @BindView(R.id.iv_veg_non_veg_grid)
    AppCompatImageView vegNonVegIndicator;

    public RecycledGridViewHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
    }

    public void bind(final MenuItem menuItem, final MenuItemClickListener menuItemClickListener) {
        incDecButton.setOnButtonsClickedListener(new IncDecButton.OnButtonsClickedListener() {
            @Override
            public void onPlusClicked(int num) {

                if (menuItem.getCustomizable()) {
                    menuItemClickListener.onCustomizableItemClicked(menuItem, 1);
                    if (incDecButton.getNumber() == 0) {
                        incDecButton.setNumber(0, true);
                    }
                } else {
                    menuItemClickListener.onPlusButtonClicked(menuItem, num);
                }
            }

            @Override
            public void onMinusClicked(int num) {
                if (menuItem.getCustomizable()) {
                    menuItemClickListener.onCustomizableItemClicked(menuItem, 0);
                } else {
                    menuItemClickListener.onMinusButtonClicked(menuItem, num);
                }
            }
        });

}

View Holder 2
  class MenuAdapterViewHolder extends RecyclerView.ViewHolder {

    @BindView(R.id.tv_cuisine_name_menu_v2)
    TextView cuisineName;

    public MenuAdapterViewHolder(View itemView) {
        super(itemView);
        ButterKnife.bind(this, itemView);
    }
}

I'm maintaining a state of item count that the list item in ViewHolder 1 has to show in  IncDecButton outside of the ViewHolder in a ROOM Db Dao, which i query as onBindViewHolder is called for each item but the views gets recycled and item count gets misplaced.
when i only have a single view holder, i.e only View Holder 1, item counts have no issues, but it gets recycled and misplaced when there are 2 View Holders.
I don't really seem to understand what am i doing wrong.
This code works fine with only a single Viewholder (Single Item Type RecyclerView).

A: Views in a RecyclerView are recycled when dissapear in the screen. You should manage the state outside the ViewHolder and just use it for the presentation. You could store the current value of the count in the item data you pass to the adapter and then just show this current value in the ViewHolder.
Another important thing is to set always the value. If you do not put the correct value, the ViewHolder will maintain the recycled view, so if the count for new cells is 0, just put 0 in the binding.
Hope it helps.


text:
Q: Alert user if the password field contains spaces at start or end of the string with javascript I have a password field, and if password contains any spaces at start or end, I would like to alert the user. password can be a phrase so spaces in between the string is allowed.
I am sure it can be done through regex, but I don't have much hands on it.
If some one can please help me out.

A: Like this:
if (/^\s|\s$/.test(str)) {
    //Waah waah waah!
}

Explanation:

*

*The /.../ expression creates a RegExp object.

*The .test() method checks whether the given string matches the regex.

*

*The | expression in the regex matches either whatever is before it or whatever is after it (an or expression)

*The \s expression matches any single whitespace character (such as a space, tab, or newline, or a fancy unicode space)

*The ^ character matches the beginning of the string

*The $ character matches the end of the string

Thus, the regex reads: Match either the beginning of the string followed by whitespace or whitespace followed by the end of the string.

A: It's easy to write a regular expression to test whether there is whitespace before or after the text; anchor the test with ^ and $.
/^\s|\s$/

But why even bother the user with it? I think it would be better to trim the whitespace automatically.
str.replace(/^\s+|\s+$/g, '');

No muss, no fuss.

A: Where password is the string value of your candidiate:
if(password.match(/^\s|\s$/))
{
  // failed
}

In the regex:

*

*^ means "start of line"

*\s means "a whitespace character"

*| means OR

*$ means "end of line"


text:
Q: Can VSCode do intellisense when using an external JS script of an HTML page? I have an HTML page and in that page I have given some elements IDs and I've defined CSS classes and some elements use those classes.
If I load that page in a browser the web dev tools will show those elements and offer code assistance.
I have created a JavaScript file that I am including in my HTML page.
Can VSCode give me intelligent information when I write code in the external JavaScript file in a similar way to the web devs tool does or a node js project does?
Actually, does VSCode do intellisense if the JavaScript IS embedded in the HTML page (this question answered below)?
UPDATE:
I did a test with JavaScript inline in an HTML page and vscode did not show the element in the code complete list or any awareness of it:

It only showed code intelligence with code from other script blocks.

UPDATE 2:
It looks like theres a few parts to this.
There's no awareness of HTML elements, as shown and discovered in web tools in the browser.
There's no awareness of other Javascript libraries in the inline script.
So there's probably no awareness of HTML elements in an external JS and no awareness of JS objects from the main HTML page either.


text:
Q: Recognition of a plateau with a slope close to zero I am writing code to remove plateau outliers from time series data. I proceeded after receiving advice to use np.diff, but there was a problem that it could not be recognized if it was not the same value.
def find_plateaus(F, min_length=200, tolerance = 0.75, smoothing=15):

    import numpy as np
    from scipy.ndimage.filters import uniform_filter1d

    # calculate smooth gradients
    smoothF = uniform_filter1d(F, size = smoothing)
    dF = uniform_filter1d(np.gradient(smoothF),size = smoothing)
    d2F = uniform_filter1d(np.gradient(dF),size = smoothing)

    def zero_runs(x):

        iszero = np.concatenate(([0], np.equal(x, 0).view(np.int8), [0]))
        absdiff = np.abs(np.diff(iszero))
        ranges = np.where(absdiff == 1)[0].reshape(-1, 2)
        return ranges

    # Find ranges where second derivative is zero
    # Values under eps are assumed to be zero.
    eps = np.quantile(abs(d2F),tolerance)
    smalld2F = (abs(d2F) <= eps)

    # Find repititions in the mask "smalld2F" (i.e. ranges where d2F is constantly zero)
    p = zero_runs(np.diff(smalld2F))

    # np.diff(p) gives the length of each range found.
    # only accept plateaus of min_length
    plateaus = p[(np.diff(p) > min_length).flatten()]

    return (plateaus)

plateaus = find_plateaus(test, min_length=5, tolerance = 0.02, smoothing=11)

plateaus = np.ravel(plateaus, order = 'A')

plateaus = plateaus.tolist()
print(plateaus)
test2['T&F'] = np.nan

for i in test2.index:
        if i in plateaus:
            test2.loc[i,['T&F']] = test2.loc[i,'data']
        else :
            test2.loc[i,['T&F']] = 0

fig, ax = plt.subplots(figsize=(15,6))
ax.plot(test2.index, test2['data'], color='black', label = 'time_series')
ax.scatter(test2.index,test2['T&F'], color='red', label = 'D910')
plt.legend()
plt.show();

Do you know any libraries or methods that can be used?
I want to recognize the parts marked in the picture below.
enter image description here

A: Still in progress, but found the answer.
First, make the np array multidimensional.
ex) time_step = 3
.....
Then, using np.std(), find the standard deviation,
After checking, you can set the standard deviation range to recognize the included range.


text:
Q: How to convert boost::chrono::process_cpu_clock::duration to milliseconds I am using boost 1.59.0.
I am trying to use boost::chrono::process_cpu_clock to time a block of my code. I would like to report this time in milliseconds, not nanoseconds. I thought to use the duration_cast template function, although I have only found examples where it takes a single duration value as an argument, not the tuple of three values returned by process_cpu_clock.now().
Below is the code that I wrote:
chrono::process_cpu_clock mytimer;
const auto start = mytimer.now();
// do work
const auto duration = mytimer.now() - start;
const auto duration_msec = duration_cast<milliseconds>(duration);

duration_msec is exactly the same as duration; it is not converted to milliseconds.
Perhaps duration_cast isn't intended to take the process_cpu_clock::duration type as an argument; however, it compiles ok.
What am I doing wrong?


text:
Q: WebMethod called with or without parameters what I'm trying to do is to set up a WCF Web-Service exposed through IIS that has one method called GetArticle. This method has to be called with a few obligatory parameters such as userName and password and with other optional parameters (for example, brand).
So the method signature looks like this:
[WebMethod]
public void GetArticle(string userName, string password, string brand)

The client that will consume the web-service makes calls to the method through query strings so I would receive:
http://localhost:5985/WebService?op=GetArticle&userName=ADMIN&password=ADMIN&brand=BRAND

And the method would return some data correctly. Since here no problems, but the client needs to have other data in return if it calls the method with ONLY the first two parameters, like this:
http://localhost:5985/WebService?op=GetArticle&userName=ADMIN&password=ADMIN

One could think: Well, I write two different methods with only the parameters I need, I expose them and we are done. I'd be fine with it, but the client (that's not mine, it's a third-party software) must have ONLY ONE method to call, so if it want to be returned some data, it calls the method with only username and password and if it wants some other data, it calls GetArticle(username, password, brand).
I've read about optional parameters in WCF and it doesn't seem to be any way to call a webmethod without specifying each parameter, nor to have two methods with the same name and different signatures (overloading). I already tried using the MessageName attribute inside the [WebMethod] tag, like:
[WebMethod (MessageName = "GetBrands")]
public void GetArticle(string userName, string password, string brand)
{
   // Do stuff...
}

[WebMethod]
public void GetArticle(string userName, string password)
{
   // Do other stuff...
}

But I still have to call those methods using different names. I also tried omitting the parameter I don't want to send, but I get an exception.
Are there any workarounds to achieve this? I know that overloading is a problem related to IIS and not to WCF, but it seems strange to me not having any solution at all...
Thank you in advance for the help.

A: Passing credentials in a HTTP GET query like you described is a terrible idea, it is incredibly insecure and should be avoided.
In any case to do what you want to do, you cannot use optional parameters, WebMethod needs a specific signature... Therefore you need to use default parameters instead... ie. public void GetArticle(string userName, string password, string brand="")


text:
Q: php artisan make:auth scaffolding not working I'm trying to activate the authentication in Laravel 5.7. Reading the documentation I have started a new fresh project with the command:
composer create-project --prefer-dist laravel/laravel bpcb

and then I have edited my .env file with my credentials:
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=valcanale
DB_USERNAME=stefano
DB_PASSWORD=password

after that I wrote the command php artisan migrate but I've got the message
Nothing to migrate
Under app\Http\Controllers\Auth I have these files:
ForgotPasswordController.php
LoginController.php
RegisterController.php
ResetPasswordController.php
VerificationPasswordController.php

This is a fresh project and I haven't touched anything. Can you help me?
Thank you.

A: Please make sure that your .env settings are correct.
Then restart the server ( stop and then type php artisan serve again )
Then run command php artisan make:auth
after this  run php artisan migrate ( run migrate command after making auth )

A: What happens when you try this( Also make sure your .env database settings are correct )
 php artisan config:cache
 php artisan migrate:reset
 php artisan migrate

After this check your database
Got it from this link.


text:
Q: Memory exception when initializing QtFont I am trying to use the new fonts from OpenCV 3.3 that are required by cv::addText(). I am trying two different examples:
cv::QtFont font8 = cv::fontQt("Times", 1, cv::Scalar(255,255,255),
cv::QT_FONT_NORMAL, cv::QT_STYLE_NORMAL, 0);

It fails with a cv::Exception at at memory location. It is unable to perform the memcpy.
The second variant is something similar to:CvFont fontB = cv::fontQt ("Times", 30, cv::Scalar (255, 255, 255), CV_FONT_BOLD);
This one can be found in different tutorials but it doesn't work because there it can't convert a qt font to a cv font. Even the most basic example from the official documentation fails. I freshly installed OpenCV from its respective website and I am using Visual Studio 2015.
Is there any other method of initializing a QtFont? Does OpenCV need to be compiled in a special manner?


text:
Q: ReflectionException thrown on composer update for a file that exists To make this more interesting, things work just fine if I run composer dump-autoload -o but I am curious why would this throw an error when I run composer update in the first place? I need to get to the bottom of this. A quick fix doesn't make me happy internally.
aligajani at Alis-MBP in ~/Projects/saveeo on master ✗                                                                                [faaba41c]  4:53
> composer update
> php artisan clear-compiled
Loading composer repositories with package information
Updating dependencies (including require-dev)
Nothing to install or update
Package guzzle/guzzle is abandoned, you should avoid using it. Use guzzlehttp/guzzle instead.
Generating autoload files
> php artisan optimize

  [ReflectionException]
  Class Saveeo\Board\Observers\BoardEventListener does not exist

BoardEventListener.php (placed in Saveeo/Board/Observers)
<?php

namespace Saveeo\Board\Observers;

use Saveeo\Services\HashIds\Contracts\HashIds as HashIdService;

class BoardEventListener {
    private $hashIdService;

    public function __construct(HashIdService $hashIdService) {
        $this->hashIdService = $hashIdService;
    }

    public function whenBoardIsCreated($event) {
        $this->hashIdService->syncHashIdValueOnModelChanges($event, 'board');
    }

    public function whenBoardIsUpdated($event) {
        $this->hashIdService->syncHashIdValueOnModelChanges($event, 'board');
    }

    public function subscribe($events) {
        $events->listen(
            'Saveeo\Board\Observers\Events\BoardHasBeenCreated',
            'Saveeo\Board\Observers\BoardEventListener@whenBoardIsCreated'
        );

        $events->listen(
            'Saveeo\Board\Observers\Events\BoardHasBeenUpdated',
            'Saveeo\Board\Observers\BoardEventListener@whenBoardIsUpdated'
        );

    }
}

EventServiceProvider.php (placed in Saveeo/Providers)
<?php

namespace Saveeo\Providers;

use Illuminate\Contracts\Events\Dispatcher as DispatcherContract;
use Illuminate\Foundation\Support\Providers\EventServiceProvider as ServiceProvider;

class EventServiceProvider extends ServiceProvider
{
    /**
     * The event listener mappings for the application.
     *
     * @var array
     */
    protected $listen = [
        //
    ];

    /**
     * The subscriber classes to register.
     *
     * @var array
     */
    protected $subscribe = [
        'Saveeo\Board\Observers\BoardEventListener',
    ];

    /**
     * Register any other events for your application.
     *
     * @param  \Illuminate\Contracts\Events\Dispatcher  $events
     * @return void
     */
    public function boot(DispatcherContract $events) {
        parent::boot($events);

        //
    }
}

Here is the folder structure. Can't see anything wrong here?
https://imgur.com/BI44Lq6
Composer.json
{
    "name": "laravel/laravel",
    "description": "The Laravel Framework.",
    "keywords": [
        "framework",
        "laravel"
    ],
    "license": "MIT",
    "type": "project",
    "require": {
        "php": ">=5.5.9",
        "laravel/framework": "5.2.*",
        "firebase/php-jwt": "~2.0",
        "guzzlehttp/guzzle": "5.*",
        "guzzlehttp/oauth-subscriber": "0.2.0",
        "laravel/socialite": "2.*",
        "league/flysystem-aws-s3-v3": "~1.0",
        "aws/aws-sdk-php": "3.*",
        "bugsnag/bugsnag-laravel": "1.*",
        "vinkla/hashids": "^2.3"
    },
    "require-dev": {
        "fzaninotto/faker": "~1.4",
        "mockery/mockery": "0.9.*",
        "phpunit/phpunit": "~4.0",
        "phpspec/phpspec": "~2.1",
        "tymon/jwt-auth": "0.5.*",
        "symfony/dom-crawler": "~3.0",
        "symfony/css-selector": "~3.0"
    },
    "autoload": {
        "classmap": [
            "database"
        ],
        "psr-4": {
            "Saveeo\\": "app/"
        }
    },
    "autoload-dev": {
        "classmap": [
            "tests/TestCase.php"
        ]
    },
    "scripts": {
        "post-install-cmd": [
        "php artisan clear-compiled",
        "php artisan optimize"
    ],
    "pre-update-cmd": [
        "php artisan clear-compiled"
    ],
    "post-update-cmd": [
        "php artisan optimize"
    ],
    "post-root-package-install": [
        "php -r \"copy('.env.example', '.env');\""
    ],
    "post-create-project-cmd": [
        "php artisan key:generate"
    ]
    },
    "config": {
        "preferred-install": "dist"
    }
}

A: It looks like we changed the autoloading namespace (manually, or by using artisan app:name) for the classes in the app/ directory from App (the default) to Saveeo in composer.json:

"autoload": {
    "psr-4": {
        "Saveeo\\": "app/"
    }
},

This is perfectly fine to do when we understand the implications. We can see the issue described in the question when we take a look at the project's folder structure for the file that causes the exception (with the namespaces in parentheses):
app                    (Saveeo)
├── Saveeo             (Saveeo\Saveeo)
│   ├── Board          (Saveeo\Saveeo\Board)
│   │   ├── Observers  (Saveeo\Saveeo\Board\Observers)
│   │   │   ├── BoardEventListener
└── ...

For compatibility with PSR-4, the namespace for BoardEventListener should be Saveeo\Saveeo\Board\Observers because it exists in the Saveeo/ directory nested under app/. PSR-4 autoloading implementations resolve class files based on file names and paths, not the namespaces declared in the files. [Composer does read the namespace from the class files to create an optimized classmap, as long as the top-level namespace matches. See update.]
If we don't want to change the directory structure of the application, and we also don't want to use two Saveeos in the namespace, we can configure Composer to merge both directories into the same namespace when it autoloads classes:
"autoload": {
    "psr-4": {
        "Saveeo\\": [ "app/", "app/Saveeo/" ]
    }
},

...and remember to composer dump-autoload.
It works, but I don't recommend this in practice. It deviates from the PSR-4 standard, makes the application susceptible to namespace conflicts, and may be confusing to other people working on the project. I suggest that you flatten the Saveeo namespace and directory, or choose a different namespace for the classes in the nested directory.

...things work just fine if I run composer dump-autoload -o but I am curious why would this throw an error when I run composer update...?

When generating the autoloading cache file, Composer doesn't actually execute your code. However, the artisan optimize command, which runs after composer update in most Laravel applications (until 5.5), does boot the application to perform its operations, so the problem code executes and we see the exception.
Update:

If using Saveeo\Board\etc was wrong versus doing Saveeo\Saveeo\Board\etc then other files around the entire application wouldn't work, but they do.

We can technically use non-PSR-4 namespaces that don't match the project's directory structure when we generate an optimized autoloader like we would to prepare an application for production:
composer dump-autoload --optimize

This works because Composer will scan each class file for namespaces to create a static classmap. When we don't specify --optimize, Composer relies on dynamic autoloading which matches file paths to namespaces, so non-standard namespaces or directory structures fail to resolve.
The namespacing for the project in question works for the most part, even though it doesn't follow PSR-4, because we're manually dumping an optimized autoloader by using the -o option for dump-autoload. However, we see the error message because composer update removes the cached classmap before running the update, so, by the time the artisan optimize command runs, the classmap no longer contains the classes that we dumped.
We can configure Composer to always optimize the autoloader by setting the optimize-autoloader configuration directive in composer.json:
"config": {
    "optimize-autoloader": true
}

...which should fix the install and update commands for this project. It's a bit of a hack to get non-standard namespacing to resolve. With this approach, remember that we'll need to dump the autoloader whenever we add a new file in development that doesn't follow PSR-4.

A: This seems to be related to the Composer PSR autoloading. By default Laravel will include
"autoload": {
    "psr-4": {
        "App\\": "app/"
    }
}

which means "the root of the App namespace is in the app folder, and from there match namespace to folder structure".
Your Saveeo namespace hasn't been registered (it's not in the App hierarchy), so Composer doesn't know its location.
It should work if you add another line to your composer.json (and then dump-autoload)
"autoload": {
    "psr-4": {
        "App\\": "app/",
        "Saveeo\\": "app/Saveeo"
    }
}

Alternatively, you could, as the other answer points out, just place the whole Saveeo namespace within App (so it's App\Saveeo\Board\Observers\Events\BoardHasBeenCreated for instance). However your Saveeo namespace seems to be sort of a self-contained module, it may be more reasonable to have it as a separate namespace rather than renaming the namespace in all of its files.

A: I believe if you just change your namespace to:
App\Saveeo\Board\Observers instead of Saveeo\Board\Observers
all your problems should be solved. Please let me know if you have a reason for creating this new namespace, instead of just branching out from the base App namespace.


text:
Q: Why does wrapping a layer removes the kernel attribute of another layer in Keras? I am currently creating a LSTM-based network for time series forecasting and I wanted to try to use Keras' Bidirectional wrapper to see if it could increase my accuracy.
However, adding the wrapper causes my output layer to lose its kernel attribute, which is problematic as my optimizer tries to access it, resulting in a crash during compilation time.
That is to say, when I do:
model = Sequential()
model.add(LSTM(
    100,
    batch_input_shape=(batch_size, look_back, features),
))
model.add(Dense(1))

print(hasattr(model.layers[-1], 'kernel'))

True

But when wrapping the LSTM like so:
model = Sequential()
model.add(Bidirectional(LSTM(
    100,
    batch_input_shape=(batch_size, look_back, features),
)))
model.add(Dense(1))

print(hasattr(model.layers[-1], 'kernel'))

False

A: The solution is to have your network predict something, then compile it with your custom optimizer:
model = Sequential()
model.add(Bidirectional(LSTM(
    100,
    batch_input_shape=(batch_size, look_back, features),
)))
model.add(Dense(1))

model.predict(np.zeros((batch_size, look_back, features)))
print(hasattr(model.layers[-1], 'kernel'))
model.compile(optimizer=CustomOptimizer(), loss='mse')

True


text:
Q: improving the following try and expect I have the function below but it is very messy. Any advice on improving the code below?
     try:
        driver.find_element_by_id("edit").click()
    except:
        pass

    try:
        self.text.find_element_by_xpath('/..//..//..//td/input[@type="checkbox"]')
        self.text.find_element_by_xpath('/..//..//..//td/input[@value=%s]' % enterValue).click()

    except:
        try:
            self.text.find_element_by_xpath('./..//..//./td/select')
            Select(self.text.find_element_by_xpath('./..//..//./td/select')).select_by_visible_text(enterValue)
        except:
            try:
                self.text.find_element_by_xpath('/..//..//..//td/input[@type="text"]')
                self.text.find_element_by_xpath('/..//..//..//td/input[@type="text"]').sendkeys(enterValue)
            except:
                #do this

A: Create a wrapper method for the find_ methods you use that does the try/except within it


text:
Q: Symfony and Doctrine, how do I join with a subquery as clause? I'll admit I'm kinda new at both Symfony and Doctrine but I can't find a way to join a table that has multiple details for each row on the starting table, so I only want the max(date) row out of that
The raw SQL would be something like
SELECT *
FROM users
JOIN activities on activities.user_id = users.id
    and activity.date = (select max(date)
        from activities a2
        where a2.user_id = activites.user_id
        and activities.date <= sysdate)

I've tried putting the RAW clause in the ->leftJoin method but it's not working
$query->leftJoin('p.activities', 'att', 'WITH', 'att.date = (select max(a2.date) from activities a2 where att.user_id = a2.user_id and a2.date< sysdate)');

this results in a
[Semantical Error] line 0, col 133 near 'activities a2 where': Error: Class 'activities' is not defined.

If I remove that where clause the join works fine though (but obviously returns too many rows)
Is there a way to do this with Doctrine? I can't convert the whole thing to raw SQL cause there are way more joins and conditions to apply after this (filtering results on a list page)
PS: I'm on Symfony 3.4, if that changes anything

A: Ok, it was as easy as defining the actual class instead of the table name, so \AppBundle\Entity\Activities
Changing that (and the name fields to the entity properties) fixed the error and works fine


text:
Q: JQuery Mobile - transition fails when ajax is disabled I have two data-role="page" divs, "content" and "links".
Content is the default page, with a button for displaying links:
More

If $.mobile.ajaxLinksEnable = false then the following is broken:

*

*It does not link to a bookmark on the same page. i.e. it links from example.com/randompage.html to example.com/#links

*The transition (slide) fails even if I add data-ajax="true" to the anchor.

HTML:
<!DOCTYPE html>

<title>Example for SO</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.0a4.1/jquery.mobile-1.0a4.1.min.css" />

    More
    Text here

    Back

A bunch of extra links here

P.S.
I'm realizing that this may be a library bug, and not my fault.
Edit: Live example link has been removed.

A: Try adding the data-url attribute to the page div. Even if the page is normally loaded using ajax, the presence of that attribute tells the framework that the requested url is already on the page and doesn't need to be loaded again.
You may also need data-dom-cache to prevent the page from being removed when it is hidden.


text:
Q: Website blocks my requests from linux ubuntu server I'm a Java engineer with zero dev ops experience. Lately I was playing around with linux ubuntu server first time and used docker with my selenium project and faced this problem:
I try to scrape HTML from a website, but my calls are getting blocked, and I get 403 forbidden response. I tried to curl same website and also get same response.
Furthermore, I only get blocked in my Linux machine, everything works in local dev env with same docker image, so thats why I think its "server fault".
Any ideas what my Linux server is missing here? Maybe I don't have some sort of certificate or have cors problem? Any ideas, what can I try? (For learning purposes only)
curl call here

A: I believe you're getting rate-limited or blocked by the website. If I run the same curl command from my laptop, I get the webpage back.
Remember to respect robots.txt if you're doing web scraping.


text:
Q: jQuery scroll function stops working randomly I'm using $(window).scroll to hide my header on scroll, with an identical function as I have successfully used on another site with no problems. On this site, however, the scroll function simply stops firing randomly after some scrolling. At first I thought it was when I scrolled too fast, or scrolled immediately to the bottom of the page, but it seems to be randomly stopping however I scroll. Even something as simple as:
$(window).scroll(function(){
  console.log('scrolling');
});

just stops firing after a little scrolling up and down. So it's not because I'm performing some crazy actions on each scroll event.
What can cause this?


text:
Q: Передать изображение в UIImageView (Swift 3) Пытаюсь передать картинку из галереи в новый ViewController, но возникает ошибка

Creating an image format with an unknown type is an error fatal error:
  unexpectedly found nil while unwrapping an Optional value

Код:
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        if let im = info[UIImagePickerControllerOriginalImage] as? UIImage {
            let vc = self.storyboard?.instantiateViewController(withIdentifier: "editImage") as! EditImageViewController
            vc.imageView.image = im
            self.present(vc, animated: true, completion: nil)
        } else {
            print("Something went wrong")
    }
    imagePicker.dismiss(animated: true, completion: nil)
}

В чем ошибка?

A: Попробуйте принимать картинку так
class EditImageViewController: UIViewController {
    @IBOutlet weak var imageView: UIImageView!
    var image: UIImage!

    override func viewDidLoad() {
        super.viewDidLoad()
        imageView.image = image
    }
}

А передавать так
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
    if let im = info[UIImagePickerControllerOriginalImage] as? UIImage {
        let vc = storyboard?.instantiateViewController(withIdentifier: "editImage") as! EditImageViewController
        vc.image = im
        present(vc, animated: true, completion: nil)
    } else {
        print("Something went wrong")
    }
    imagePicker.dismiss(animated: true, completion: nil)
}

Потому что похоже, что Вы пытаетесь вставить image в еще недоступный imageView


text:
Q: Caching WCF ChannelFactories for multiple ASP.NET users I have an enterprise system that is used by a handful of WinForms clients and a public-facing ASP.NET site.  A backend WCF service provides several services to be consumed by each of these clients.  The services require message credentials, which in the case of a WinForms app is supplied by the user when the program first starts.
I cache ChannelFactories in the WinForm apps for performance.  I would like to do the same on the ASP.NET site.  However, since ClientCredentials are stored as part of the factory (ChannelFactory<T>.Credentials), will I need to cache one ChannelFactory per service per user?  It seems that even under moderate use that will add up quickly.  Additionally, I believe I will need to store them at the application-level, not the session-level, since for future scalability I can't guarantee that I will always be using InProc session state.
I don't see any way that I can create one ChannelFactory per service, and then upon creation of the channel specify credentials.  Am I missing something?

A: I just ran across this unanswered question many months later, and finally I can provide an answer for it.  I went with a solution very similar to ASP.NET Web Site + Windows Forms App + WCF Service: Client Credentials.  Still I decided I would do a write-up of my approach here.
Regular (thick client) users of the WCF service are authenticated with a username/password, and web users are authenticated by a header provided with the request.  This header can be trusted because the web server itself authenticates with a X509 certificate for which the WCF service has the public key.  So, the solution is to have a single ChannelFactory in the ASP.NET application that will insert a header into the request, telling the WCF service which user is actually making the request.
I set up two endpoints for my ServiceHost, with slightly varying URLs and different bindings.  Both bindings are TransportWithMessageCredential, but one is message credential type Username, and the other is Certificate.
var usernameBinding = new BasicHttpBinding( BasicHttpSecurityMode.TransportWithMessageCredential )
usernameBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;

var certificateBinding = new BasicHttpBinding( BasicHttpSecurityMode.TransportWithMessageCredential )
certificateBinding.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.Certificate;

var serviceHost = new ServiceHost( new MyService() );
serviceHost.Description.Namespace = "http://schemas.mycompany.com/MyProject";
serviceHost.AddServiceEndpoint( typeof( T ), usernameBinding, "https://myserver/MyProject/MyService" );
serviceHost.AddServiceEndpoint( typeof( T ), certificateBinding, "https://myserver/MyProject/Web/MyService" );

I configured a ServiceCredentials object with a) the server-side certificate, b) the custom username/password validator and c) the client-side certificate.  This was a little confusing because WCF would by default attempt to use all of these mechanisms (A+B+C), even though one endpoint is set up for A+B and the other is configured for A+C.
var serviceCredentials = new ServiceCredentials();
serviceCredentials.ServiceCertificate.SetCertificate( StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, "myserver" );
serviceCredentials.UserNameAuthentication.UserNamePasswordValidationMode = UserNamePasswordValidationMode.Custom;
serviceCredentials.UserNameAuthentication.CustomUserNamePasswordValidator = this.UserNamePasswordValidator;
serviceCredentials.ClientCertificate.Authentication.CertificateValidationMode = X509CertificateValidationMode.None;
serviceCredentials.ClientCertificate.SetCertificate( StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, "SelfSignedWebsiteCertificate" );
serviceHost.Description.Behaviors.Add( serviceCredentials );

My solution was to implement an IAuthorizationPolicy, and use it as part of the ServiceHost's ServiceAuthorizationBehavior.  This policy checks if the request had been authenticated by my implementation of UserNamePasswordValidator, and if so, I create a new IPrincipal with the identity that had been supplied.  If the request is authenticated by an X509 certificate, I look for a message header on the current request indicating who the impersonated user is, and then create a principal using that username.  My IAuthorzationPolicy.Evaluate method:
public bool Evaluate( EvaluationContext evaluationContext, ref object state )
{
    var identity = ((List<IIdentity>) evaluationContext.Properties[ "Identities" ] ).First();

    if ( identity.AuthenticationType == "MyCustomUserNamePasswordValidator" )
    {
        evaluationContext.Properties[ "Principal" ] = new GenericPrincipal( identity, null );
    }
    else if ( identity.AuthenticationType == "X509" )
    {
        var impersonatedUsername = OperationContext.Current.IncomingMessageHeaders.GetHeader<string>( "ImpersonatedUsername", "http://schemas.mycompany.com/MyProject" );

        evaluationContext.AddClaimSet( this, new DefaultClaimSet( Claim.CreateNameClaim( impersonatedUsername ) ) );

        var impersonatedIdentity = new GenericIdentity( impersonatedUsername, "ImpersonatedUsername" );
        evaluationContext.Properties[ "Identities" ] = new List<IIdentity>() { impersonatedIdentity };
        evaluationContext.Properties[ "Principal" ] = new GenericPrincipal( identity, null );
    }
    else
        throw new Exception( "Bad identity" );

    return true;
}

Adding the policy to the ServiceHost is straightforward:
serviceHost.Authorization.ExternalAuthorizationPolicies = new List<IAuthorizationPolicy>() { new CustomAuthorizationPolicy() }.AsReadOnly();
serviceHost.Authorization.PrincipalPermissionMode = PrincipalPermissionMode.Custom;

Now, ServiceSecurityContext.Current.PrimaryIdentity is correct regardless of how the user was authenticated.  This more or less takes care of the heavy lifting on the side of the WCF service.  In my ASP.NET application, I have to set up an appropriate binding (certificateBinding, mentioned above), and create my ChannelFactory.  However, I add a new behavior to factory.Endpoint.Behaviors to pull the current user's identity from HttpContext.Current.User and place it into the WCF request header that my service looks for.  This is as easy as implementing IClientMessageInspector and using a BeforeSendRequest such as this (although adding null-checks where appropriate):
public object BeforeSendRequest( ref System.ServiceModel.Channels.Message request, System.ServiceModel.IClientChannel channel )
{
    request.Headers.Add( MessageHeader.CreateHeader( "ImpersonatedUsername", "http://schemas.mycompany.com/MyProject", HttpContext.Current.User.Identity.Name ) );

    return null;
}

Of course we still need an IEndpointBehavior to add the message inspector.  You can use a fixed implementation that references your inspector; I chose to use a generic class:
public class GenericClientInspectorBehavior : IEndpointBehavior
{
    public IClientMessageInspector Inspector { get; private set; }

    public GenericClientInspectorBehavior( IClientMessageInspector inspector )
    { Inspector = inspector; }

    // Empty methods excluded for brevity

    public void ApplyClientBehavior( ServiceEndpoint endpoint, System.ServiceModel.Dispatcher.ClientRuntime clientRuntime )
    { clientRuntime.MessageInspectors.Add( Inspector ); }
}

And finally the glue to make the ChannelFactory use the proper client-side certificate and endpoint behavior:
factory.Credentials.ClientCertificate.SetCertificate( StoreLocation.LocalMachine, StoreName.My, X509FindType.FindBySubjectName, "SelfSignedWebsiteCertificate" );
factory.Endpoint.Behaviors.Add( new GenericClientInspectorBehavior( new HttpContextAuthenticationInspector() ) );

The only final piece is how to ensure that HttpContext.Current.User is set, and that the user has actually been authenticated.  When the user attempts to log in to the website, I create a ChannelFactory that uses my usernameBinding, assigns the provided username/password as ClientCredentials, and makes a single request to my WCF service.  If the request succeeds, I know the user's credentials were correct.
I can then use the FormsAuthentication class or assign an IPrincipal to the HttpContext.Current.User property directly.  At this point I no longer need the single-use ChannelFactory using the usernameBinding, and I can use a single ChannelFactory using the certificateBinding where one instance is shared across my ASP.NET application.  That ChannelFactory will pick up the current user from HttpContext.Current.User and insert the appropriate header in future WCF requests.
So, I need one ChannelFactory per WCF service in my ASP.NET application, plus creating a temporary ChannelFactory every time a user logs in.  In my situation, the site is used for long periods and logins are not all that frequent, so this is a great solution.

A: So you're making a WCF connection using the client credentials as they have logged into the server?
My idea would be to set up the WCF binding to use impersonation.  Effectively the channel factory can connect as your website's identity, or as a least privilege identity, and WCF code can cause the service to reject the call if the identity isn't correct.
That way you can create one channel factory with many connections to the server, and you can simply impersonate the logged on user when you make the WCF call (from memory you can do this nicely by wrapping the impersonate call into a using statement.)
This link should be helpful I hope: MSDN Delegation and Impersonation
This code sample is taken from the page:
public class HelloService : IHelloService
{
    [OperationBehavior]
    public string Hello(string message)
    {
        WindowsIdentity callerWindowsIdentity =
        ServiceSecurityContext.Current.WindowsIdentity;
        if (callerWindowsIdentity == null)
        {
            throw new InvalidOperationException
            ("The caller cannot be mapped to a WindowsIdentity");
        }
        using (callerWindowsIdentity.Impersonate())
        {
           // Access a file as the caller.
        }
        return "Hello";
    }
}


text:
Q: What is the suggested way for DAG config file in Airflow We are looking for the best approach for setting up the configuration file for each DAG, I know we can use JSON in Variable, but want to see if there are suggested approaches in Airflow or other format (i.e.YAML). Thanks!

A: YAML it's a good combination between human-readbility and a good document storage format.


text:
Q: How can I change my font to Raleway in letter class? I'm somewhat a novice in writing letters in LaTeX, and I would like to shy away from the standard Times New Roman font. Specifically, I would like to use Raleway font, but I have no idea how to implement this. I've researched, but can't find anything.

A: You need the raleway-package on your system. If you don't have a complete LaTeX-installation – in which case you don't have to do anything – you can use the package manager of your distribution to install the package.
Then you can just use the raleway font by putting \usepackage{raleway} in your preamble. Like this:
\documentclass{letter}
\usepackage{raleway}                      % Load raleway font
\renewcommand{\familydefault}{\sfdefault} % Set sans serif for document
\begin{document}
    Hello, World!
\end{document}

Et voilà:


text:
Q: neural network: in neurons[[i]] %*% weights[[i]] : requires numeric/complex matrix/vector arguments i am trying to the neural network method on my data and i am stuck.
i am allways getting the message:
in neurons[[i]] %*% weights[[i]] :    requires numeric/complex matrix/vector arguments
the facts are:

*

*i am reading my data using read.csv
i am adding a link to a file with some of my data, i hope it helps
https://www.dropbox.com/s/b1btx0cnhmj229p/collineardata0.4%287.2.2017%29.csv?dl=0

*i have no NA in my data (i checked twice)

*the outcome of str(data) is:
'data.frame':   20 obs. of  457 variables:
 $ X300.5_alinine.sulphate    : num  0.351 0.542 0.902 0.656 1 ...
 $ X300.5_bromocresol.green   : num  0.435 0.603 0.749 0.314 0.922 ...
 $ X300.5_bromophenol.blue    : num  0.415 0.662 0.863 0.345 0.784 ...
 $ X300.5_bromothymol.blue    : num  0.2365 0.0343 0.4106 0.3867 0.8037 ...
 $ X300.5_chlorophenol.red    : num  0.465 0.1998 0.7786 0.0699 1 ...
 $ X300.5_cresol.red          : num  0.534 0.311 0.678 0.213 0.821 ...
continued

*i have tried to do use model.matrix

*the code i have was tried on different datasets (i.e iris) and it was good.

can anyone please try and suggest what is wrong with my data/data reading?
the code is
require(neuralnet)
require(MASS)
require(grid)

require(nnet)

#READ IN DATA
data<-read.table("data.csv", sep=",", dec=".", head=TRUE)
dim(data)

# Create Vector of Column Max and Min Values
maxs <- apply(data[,3:459], 2, max)
mins <- apply(data[,3:459], 2, min)

# Use scale() and convert the resulting matrix to a data frame
scaled.data <- as.data.frame(scale(data[,3:459],center = mins, scale =   maxs - mins))

# Check out results
print(head(scaled.data,2))

#create formula
feats <- names(scaled.data)

# Concatenate strings
f <- paste(feats,collapse=' + ')
f <- paste('data$Type ~',f)

# Convert to formula
f <- as.formula(f)

f

#creating neural net
nn <- neuralnet(f,model,hidden=c(21,15),linear.output=FALSE)
str(scaled.data)

apply(scaled.data,2,function(x) sum(is.na(x)))

A: There are multiple things wrong with your code.
1.There are multiple factors in your dependent variable Type.  The neuralnet only accepts numeric input so you must convert it to a binary matrix with model.matrix.
y <- model.matrix(~ Type + 0, data = data[,1,drop=FALSE])

# fix up names for as.formula
y_feats <- gsub(" |\\+", "", colnames(y))
colnames(y) <- y_feats

scaled.data <- cbind(y, scaled.data)

# Concatenate strings
f <- paste(feats,collapse=' + ')
y_f <- paste(y_feats,collapse=' + ')
f <- paste(y_f, '~',f)

# Convert to formula
f <- as.formula(f)

2.You didn't even pass in your scaled.data to the neuralnet call anyway.
nn <- neuralnet(f,scaled.data,hidden=c(21,15),linear.output=FALSE)

The function will run now but you will need to look in to the multiclass problems (beyond the scope of this question).  This package does not output straight probabilities so you must be cautious.


text:
Q: How to convert zip file to base64Binary I have a zipped file that contains some xml files and must send it to WCF service
This is the parameter's definition into wsdl service definitions
<xs:element name="contentFile" type="xs:base64Binary" nillable="true" minOccurs="0"/>

Then I have a c# client built for that WCF, one method have this parameter with byte[] Type.
How can I convert my zipped file to base64Binary and use it as value for that parameter?
NOTE:
This is the signature method

A: Considering that the base64 only uses alpha-numeric, I do not think it matters which encoding you use. You can probably use GetBytes of any encoding to convert the string to an array of bytes.

System.Text.Encoding.UTF8.GetBytes(base64String);


text:
Q: jQuery UI-animated text box hops into the container div only after toggle effect is complete I have a container div, a one line-high div at the very top and a jQuery-hidden text box inside. There is a visible button on that bar. Clicking it should make the hidden text box slide into view, with the entire animation taking place on that thin header bar.
Instead, it animates outside the bar and jumps into the bar once the animation is complete.
Current JS:
$(document).ready(function() {
    $('#userNameInput').hide();
    $('#userNameInputButton').click(function() {
        $('#userNameInput').toggle('slide', {direction: 'right'}, 2000);
    });
});

Check this JSFiddle and you'll understand. I'm new to jQuery. How can I fix this?

A: Just include the css
#userNameInputButton {
    float: left;
}

#userNameInput {
    width: 140px;
}

Updated Fiddle

A: I have updated the fiddle.
CSS:
.ui-effects-wrapper {
    width: 140px;
    display:inline-block;
    vertical-align: middle;
    height: auto;
}

Why it is happening?
If you look in the devtool, while animating, the textbox is wrapped by a div with class .ui-effects-wrapper. The on animation complete the textbox is taken out of this wrapper. Since div is a block element by default, you notice the the jump as block elements are stacked horizontally and not vertically

A: Replace the Css with
#userNameInput {
    padding: 0;
    width: 140px;
    float :left;
}


text:
Q: datagridview text box column containing button
regarding to above picture i want to have a datagridview by spacial column which have a button at left side.
Users can both type values in the text box or click the button to select value from a list.
when users click the button a new form appears below the selected cell.
is there any way to create any thing like this in C# windows form application?

A: For Data Grid View control, you need to create your own user control which contains button and text box
Next link show some example:  Multiple controls in a single DataGridView cell


text:
Q: Start a teensy sketch after USB handshake has completed or upon a button has been pressed I have an issue in starting a sketch on my Teensy at the right time.
I work in a school as an IT technician and over the summer I go through all the computers on site, log-on and check if they're behaving correctly.
To avoid to log on more than 500 workstation. I thought that emulating a keyboard with teensy was the best way to make this process faster so I wrote some code to help me doing so...unfortunately there's a problem with timings.
To solve this issue I'd like the teensy to start the program after the usb device on windows has been installed correctly or after a button as been pressed.
Below is the code, please would it be possible for some of you gurus to help me out?
int count = 0;
const int buttonPin = 5;
int buttonState = 0;

void setup()
{
    pinMode(buttonPin, INPUT);
}

void loop() {
   buttonState = digitalRead(buttonPin);
   if (buttonState == HIGH){
      Keyboard.set_modifier(MODIFIERKEY_CTRL);
      Keyboard.send_now();
      Keyboard.set_modifier(MODIFIERKEY_CTRL | MODIFIERKEY_ALT);
      Keyboard.send_now();
      Keyboard.set_key1(KEY_DELETE);
      Keyboard.send_now();
      Keyboard.set_modifier(0);
      Keyboard.set_key1(0);
      Keyboard.send_now();
      delay(2500);
      Keyboard.print("Administrator");
      delay(1000);
      Keyboard.press(KEY_TAB);
      Keyboard.release(KEY_TAB);
      delay(500);
      Keyboard.print("XXXXXXXXXXXXXXXX");
      delay(500);
      Keyboard.press(KEY_TAB);
      Keyboard.release(KEY_TAB);
      delay(500);
      Keyboard.press(KEY_ENTER);
      Keyboard.release(KEY_ENTER);
}

else {

     Keyboard.print("No Button Pressed!")
     }

}

Many thanks in advance.

A: Having been in Shannon's position, I can understand what he's trying to do.  Doing this by remote won't help.  You have to physically go to each machine, turn it on, and check not just that it boots, but that the drives are OK, that the keyboard and mouse work, that the monitor is OK, etc.  Last but not least is of course seeing that it is where it should be and updating the database if the PC has been moved (or putting it back where it belongs.)
This is as much a physical inventory as anything else.  Since it is summer, I would also expect the PCs to be shut off to save power and reduce the school's electricity bill.
Horta's suggestion of using VNC is therefore out of the question - and VNC would be a bad choice, anyway.  In a Windows System you would do better to use RDP (which is already installed compared to having to install and configure VNC 500 times.)  Under Linux, you would have a good many options but still, Shannon has to go and physically check the machines.
I would also hope that the PCs in the school cannot be reached for VNC (or even RDP) over the internet.
I would have preferred to make this a comment to Horta's comment, but I don't have enough reputation for that.


text:
Q: Getting Force close when I try to open my golf scoreboard application I am quite new androids and seem to have came across a Force close on my app and have no idea how to solve it.
Basically a part of my golf app is a scoreboard that the hole the person is on and the amount of strokes taken.
My code works were you have 2 buttons, add and subtract and change the number that shows up in the EditText. A button is then clicked and submits the number into a listview.I'm now trying to get it so that there is 2 add, subtract buttons and edittext and when both numbers have been entered and button to submit is clicked, will show something like 'Your stroke was 2' 'On hole 1'
Here is the code for it
package com.uhi.myGolfApp;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Intent;
import android.content.SharedPreferences;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class scoreboard extends Activity implements OnClickListener {
Button buttonPlus1;
Button buttonMinus1;
EditText editScore1;
Button buttonPlus;
Button buttonMinus;
Button buttonOk;
EditText editScore;
ListView scoreCard;
Cursor cursor;
SimpleCursorAdapter adapter;
Integer score=0;
Integer score1=0;
SharedPreferences prefs;
databaseHelper dbHelper;
SQLiteDatabase db;
Intent i;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // Inflate UI from XML
    setContentView(R.layout.scoreboard);

    // Get a hang of UI components
    buttonPlus1 = (Button)findViewById(R.id.buttonadd);
    buttonMinus1 = (Button)findViewById(R.id.buttonsub);
    editScore1 = (EditText)findViewById(R.id.score1);
    buttonPlus = (Button)findViewById(R.id.add);
    buttonMinus= (Button)findViewById(R.id.subtract);
    buttonOk   = (Button)findViewById(R.id.enter);
    editScore  = (EditText)findViewById(R.id.score);
    scoreCard  = (ListView)findViewById(R.id.scorePosted);

    // Add onClick listeners
    buttonPlus1.setOnClickListener(this);
    buttonMinus1.setOnClickListener(this);
    buttonPlus.setOnClickListener(this);
    buttonMinus.setOnClickListener(this);
    buttonOk.setOnClickListener(this);

    // Get preferences
    prefs = PreferenceManager.getDefaultSharedPreferences(this);
    editScore.setText( score.toString() );
    editScore1.setText( score1.toString() );

    // Initialize the database
    dbHelper = new databaseHelper(this);
    db = dbHelper.getWritableDatabase();

    // Load the data (essentially executes a SELECT statement)
    cursor = db.query(databaseHelper.tableName, null, null, null, null, null, null);
    startManagingCursor(cursor);

    // Set the list adapter
    String[] from = {databaseHelper.colStrokes, databaseHelper.colHole};
    int[] to = {R.id.textStroke, R.id.textHole};
    adapter = new SimpleCursorAdapter(this, R.layout.golfscores, cursor, from, to);
    scoreCard.setAdapter(adapter);
}

@Override
public void onRestoreInstanceState(Bundle inState) {
    score = (inState!=null) ? inState.getInt("score",0) : 0;
    score1 = (inState!=null) ? inState.getInt("score1",0) : 0;
    editScore.setText( score.toString() );
    editScore1.setText( score1.toString() );
}
@Override
public void onSaveInstanceState(Bundle outState) {
    outState.putInt("score", score);
    outState.putInt("score1", score1);
    super.onSaveInstanceState(outState);
}

@Override
public void onClick(View src) {
    switch(src.getId()) {
    case R.id.buttonadd:
        score1++;
        break;
    case R.id.buttonsub:
        score1--;
        break;
    case R.id.add:
        score++;
        break;
    case R.id.subtract:
        score--;
        break;
    case R.id.enter:
        // Save in DB
        ContentValues values = new ContentValues();
        values.put(databaseHelper.colHole, score1);
        values.put(databaseHelper.colStrokes, score);
        db.insert(databaseHelper.tableName, null, values);

        cursor = db.query(databaseHelper.tableName, null, null, null, null, null,     null);
        startManagingCursor(cursor);

        adapter.changeCursor(cursor);
        score=0;
        adapter.changeCursor(cursor);
        score1=0;
        break;
    }
    editScore.setText( score.toString() );
    editScore1.setText( score1.toString() );
}

}

and the database
package com.uhi.myGolfApp;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

public class databaseHelper extends SQLiteOpenHelper {
// DB constants
private static final String DB_NAME = "scoreboard.db";
private static final int DB_VERSION = 1;    // Schema version

// Schema constants
public static final String tableName  = "scoreboard";
public static final String colHole = "hole";
public static final String colStrokes = "strokes";

// Constructor
public databaseHelper(Context context) {
    super(context, DB_NAME, null, DB_VERSION);
}

//create the SQL table and the attributes it will hold
@Override
public void onCreate(SQLiteDatabase db) {
    String sql = "create table "+tableName +
        " (_id integer not null primary key autoincrement, "+
            colHole + " integer, "+ colStrokes+" integer)";
    db.execSQL(sql);
}

// upgrade the database off the old version
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
}
}

Also I dont know if this is any help but this appears in the LogCat = 'Caused by: java.lang.IllegalArgumentException: column 'hole' does not exist'
Appreciate any help =]

A: I would guess that you ran your code once, before you added  the "hole" column, and that is the database that is being read. You need to delete your app's data (Settings -> Applications -> Your app) so that the newest version of the database is created. If you don't have the option to delete data then uninstall it.


text:
Q: Antlr4 "primitive" recursion Following along http://blog.ptsecurity.com/2016/06/theory-and-practice-of-source-code.html#java--and-java8-grammars, I am trying to reduce left-recursion in my fairly complex grammar.  From what I understand, the non-primitive form of recursion can lead to performance problems both in terms of memory and process time.
So I am trying to refactor these rules in my grammar to use only "primitive" recursion.  Of course, that blog post is the only time I have seen the phrase "primitive" recursion in regards to Antlr.  So I am just guessing at its meaning/intent.  Seems to me it means a rule that refers to itself as a lhs for at most just a single rule branch.  Correct?
At the moment I have an expression rule like:
expression
    : expression DOUBLE_PIPE expression         # ConcatenationExpression
    | expression PLUS expression                # AdditionExpression
    | expression MINUS expression               # SubtractionExpression
    | expression ASTERISK expression            # MultiplicationExpression
    | expression SLASH expression               # DivisionExpression
    | expression PERCENT expression             # ModuloExpression
    ...
    ;

The ... includes quite a few sub-rules that also refer back to expression.  But these are the only ones with direct recursion.
If I understand correctly, refactoring these to be "primitive" recursion would look something like:
expression
    : binaryOpExpression                        # BinaryOpExpression
    ...
    ;

binaryOpExpression
    : expression DOUBLE_PIPE expression         # ConcatenationExpression
    | expression PLUS expression                # AdditionExpression
    | expression MINUS expression               # SubtractionExpression
    | expression ASTERISK expression            # MultiplicationExpression
    | expression SLASH expression               # DivisionExpression
    | expression PERCENT expression             # ModuloExpression
    ;

First, is that the correct refactoring?
Secondly, will that really help performance?  At the end of the day it is still the same decisions, so I'm not really understanding how this helps performance (aside from maybe producing less ATNConfig objects).
Thanks

A: I have not heard "primitive recursion" before in this context and the author probably only means to name a specific form of recursions in ANTLR4.
Fact is there are 3 relevant forms of recursions in ANTLR4:

*

*Direct left recursion: recursion from the first rule reference in a rule (to the same rule). For example: a: ab | c;

*Indirect left recursion: left recursion not directly from the same rule. For example: a: b | c; b: c | d; c: a | e; (not allowed in ANTLR4)

*Right recursion: any other recursion in a rule. For example: a: ba | c;. The name "right recursion" is however only correct in cases of binary expression, but is used often to differentiate from left recursions in general.

Having said that it becomes clear that your rewrite is wrong, as it would create indirect left recursion, which ANLTR4 does not support. Direct left recursion is usually not a problem (from a memory or performance standpoint) because ANTLR4 converts them to non-recursive ATN rule graphs.
What can become a problem are right recursions, because they are implemented by code recursion (recursive function calls in the runtime), which may qickly exhaust the CPU stack. I have seen cases with big expressions which could not be parsed in a separate thread, because I couldn't set the thread stack size to a larger value (the main thread stack size usually can be adjusted via linker settings).
The only solution for the latter case, which I have found useful, is to lower the number of parser rules in the grammar that call each other. Of course it's a matter of structure, readability etc. to put certain expression elements in different rules (for example andExpression, orExpression, bitExpression etc.), but that may lead to pretty deep invocation stacks, which may exhaust the CPU stack and/or require a lot of time to process them.


text:
Q: MongoDB Aggregation Framework Group Performance Working with the MongoDB aggregation framework it is clear that the $group function is the bottleneck.   By using explain() on some find queries, I'm able to tailor my indexes to reduce table scans significantly, however it seems that $group does not take into account any $sort that happens before, even if I end up sorting by the fields it will end up doing the $group by.
Besides simply reducing the result set, are there any practical ways to improve the performance of the $group function?  I'm almost tempted to take advantage of the sort, and just do the $group in my own application, but there must be an elegant and performant solution using the framework.
I'm noticing that as the result set from the $match increases, the $group time also increases.
My document is basically like this
{
 a: (String)
 b: (String)
}

with a pipeline that looks something like
$match :{ a : 'frank'}
$sort : { b : 1 }
$group : { _id : { $b : b }}

It is surprising to me, because I assume by the time it gets to the group, the data is loaded into memory, and since the fields are indexed, a few thousand records shouldn't take that much time to load into memory. Is this not the case?
Just seems that the $sort has no effect on the overall performance.  Is there a way to use indexes, as well as the previous functions of the pipeline to improve the performance of the $group?  Also, does $group stay within the result set from the previous functions, or does it go back to an entire table scan (I'm pretty sure, or hopefully that's not it)