text:
Q: How to check Array size and not print the null values? Please someone who knows c for 100 years to explain to me what am I looking at here. Am I taking the right route to learning c as a career? WOW what is this I really would like to know what is going on here
#include <stdio.h>
#include <string.h>

int main() {

char *checkArr[1000] = {"This is very good",
                        "text that has been",
                        "put into a file for",
                        "the purposes of",
                        "being an example.", NULL};
int size2 = strlen(checkArr);
printf("Check Array size: %d\n", size2);

for (int i =0; i < strlen(checkArr); i++){
    printf("%s\n", checkArr[i]);
}

char *checkArr2[1000] = {"This is very good",
                        "text that has been",
                        "put into a file for",
                        NULL,
                        NULL, NULL};
int size3 = strlen(checkArr2);
printf("Check Array size: %d\n", size3);

for (int i =0; i < strlen(checkArr2); i++){
    printf("%s\n", checkArr2[i]);
}

for (int i =0; i < strlen(checkArr2); i++){
    printf("%s\n", checkArr2[i]);
}

char *checkArr3[1000] = {"This is very good",
                        "text that has been",};
int size4 = strlen(checkArr3);
printf("Check Array size: %d\n", size4);

for (int i =0; i < strlen(checkArr3); i++){
    printf("%s\n", checkArr3[i]);
}

char *checkArr4[1000] = {"This is very good",
                        "text that has been",
                        NULL,
                        NULL,
                        NULL, NULL};
int size5 = strlen(checkArr4);
printf("Check Array size: %d\n", size5);

for (int i =0; i < strlen(checkArr4); i++){
    printf("%s\n", checkArr4[i]);
}

    return 0;
}

Explain this below please, stdout
Check Array size: 5
This is very good
text that has been
put into a file for
the purposes of
being an example.
Check Array size: 5
This is very good
text that has been
put into a file for
(null)
(null)
This is very good
text that has been
put into a file for
(null)
(null)
Check Array size: 5
This is very good
text that has been
(null)
(null)
(null)
Check Array size: 5
This is very good
text that has been
(null)
(null)
(null)

How is this possible. How can all these arrays have the same size length???

A: strlen() gives you the length of a single string.  So when you
    char *checkArr[1000] = {"This is very good",
                            ...,
                            NULL};
    int size = strlen(checkArr);

You are asking strlen() to measure an array of strings - which is not what it does.  Your compilter will complain:
main.c:16:20: warning: passing argument 1 of 'strlen' from incompatible pointer type [-Wincompatible-pointer-types]

    int size = strlen(checkArr);

And it is right - you are passing a pointer to the wrong thing.  If you had done this:
    char *checkArr[1000] = {"This is very good",
                            ...,
                            NULL};
    int size_of_string_0 = strlen(checkArr[0]);

Then that would have worked - but it isn't what you are trying to measure.
So then the question is, what are you trying to measure?
If what you want to measure is the length of the array then it will always be 1000 in your example because that's the size you defined it to be.  You can measure that with:
    char *checkArr[1000] = {"This is very good",
                            ...,
                            NULL};
    int size_of_array = sizeof(checkArr)/sizeof(checkArr[0]); // will be 1000

If what you want to measure is the number of things that you initialise the array with then you need to count those yourself.  All the ones you don't initialize are set to a default value so all 1000 of them exist but there is no way to know which ones you initialised manually and which were done for you.
If what you want to meansure is the length of an array of pointers until the first NULL pointer then you need to count those entries yourself.  But you can do that - you need to write your own function.  Something like:
// I use size_t instead of int.  For why, see:
// https://stackoverflow.com/questions/131803/unsigned-int-vs-size-t
size_t arrlen(char **checkArr) {
    size_t len = 0;
    for (;*checkArr != NULL; checkArr++)
        len++;
    return len;
}

So then all you need to do is make sure all you arrays of pointers have a value set to NULL.
Here is the whole code:
#include <stdio.h>
#include <string.h>

size_t arrlen(char **checkArr) {
    size_t len = 0;
    for (;*checkArr != NULL; checkArr++)
        len++;
    return len;
}

int main() {
    char *checkArr[1000] = {"This is very good",
                            "text that has been",
                            "put into a file for",
                            "the purposes of",
                            "being an example.",
                            NULL};
    int size2 = arrlen(checkArr);
    printf("Check Array size: %d\n", size2);
    for (int i =0; i < arrlen(checkArr); i++){
        printf("%s\n", checkArr[i]);
    }
    puts("");

    char *checkArr2[1000] = {"This is very good",
                            "text that has been",
                            "put into a file for",
                            NULL,
                            "being an example.",
                            NULL};
    int size3 = arrlen(checkArr2);
    printf("Check Array size: %d\n", size3);
    for (int i =0; i < arrlen(checkArr2); i++){
        printf("%s\n", checkArr2[i]);
    }
    puts("");

    char *checkArr3[1000] = {"This is very good",
                             "text that has been",
                             NULL};
    int size4 = arrlen(checkArr3);
    printf("Check Array size: %d\n", size4);
    for (int i =0; i < arrlen(checkArr3); i++){
        printf("%s\n", checkArr3[i]);
    }
    puts("");

    char *checkArr4[1000] = {"This is very good",
                            "text that has been",
                            NULL,
                            "the purposes of",
                            "being an example.",
                            NULL};
    int size5 = arrlen(checkArr4);
    printf("Check Array size: %d\n", size5);
    for (int i =0; i < arrlen(checkArr4); i++){
        printf("%s\n", checkArr4[i]);
    }
    puts("");

    return 0;
}

Try it here: https://onlinegdb.com/r1QOTg2m_
If you want to count the number of items that are not NULL even if some are null then you need to pass in the size of the initialized items and have the loop check each of those for NULL.  Something like:
#include <stdio.h>
#include <string.h>

size_t arritems(char *checkArr[], size_t size) {
    int count = 0;
    for (size_t len = 0; len<size; len++)
        if(checkArr[len] != NULL) {
            count++;
    }
    return count;
}

int main() {
    char *checkArr[1000] = {"This is very good",
                            "text that has been",
                            "put into a file for",
                            "the purposes of",
                            "being an example.",
                            NULL};
    int size2 = arritems(checkArr,6);
    printf("Check Array size: %d\n", size2);

    char *checkArr2[1000] = {"This is very good",
                            "text that has been",
                            "put into a file for",
                            NULL,
                            "being an example.",
                            NULL};
    int size3 = arritems(checkArr2,6);
    printf("Check Array size: %d\n", size3);

    char *checkArr3[1000] = {"This is very good",
                             "text that has been",
                             NULL};
    int size4 = arritems(checkArr3,3);
    printf("Check Array size: %d\n", size4);

    char *checkArr4[1000] = {"This is very good",
                            "text that has been",
                            NULL,
                            "the purposes of",
                            "being an example.",
                            NULL};
    int size5 = arritems(checkArr4,6);
    printf("Check Array size: %d\n", size5);

    return 0;
}

Try it here: https://onlinegdb.com/S1g90lhXu

A: This is prefaced by my top comments.
You're replicating code. Better to add an (e.g.) print_array function to do the NULL limited printing.
Note that checkArr3 does not have a NULL terminator

Here's some refactored code. I had replaced the strlen calls with the COUNTOF macro that I mentioned, but that still didn't work too well.
I've used cpp conditionals to denote old vs new code (e.g.):
#if 0
// old code
#else
// new code
#endif

Anyway, here it is:
#include <stdio.h>
#include <string.h>

#define COUNTOF(_arr) \
    (sizeof(_arr) / sizeof(_arr[0]))

void
print_array(char **arr)
{

    for (;  *arr != NULL;  ++arr)
        printf("%s\n",*arr);
}

int
main()
{

    char *checkArr[1000] = {
        "This is very good",
        "text that has been",
        "put into a file for",
        "the purposes of",
        "being an example.",
        NULL
    };
    int size2 = COUNTOF(checkArr);

    printf("Check Array size: %d\n", size2);

#if 0
    for (int i = 0; i < COUNTOF(checkArr); i++) {
        printf("%s\n", checkArr[i]);
    }
#else
    print_array(checkArr);
#endif

    char *checkArr2[1000] = {
        "This is very good",
        "text that has been",
        "put into a file for",
        NULL,
        NULL,
        NULL
    };
    int size3 = COUNTOF(checkArr2);

    printf("Check Array size: %d\n", size3);

#if 0
    for (int i = 0; i < COUNTOF(checkArr2); i++) {
        printf("%s\n", checkArr2[i]);
    }

    for (int i = 0; i < COUNTOF(checkArr2); i++) {
        printf("%s\n", checkArr2[i]);
    }
#else
    print_array(checkArr2);
#endif

    char *checkArr3[1000] = {
        "This is very good",
        "text that has been",
#if 1
        NULL
#endif
    };
    int size4 = COUNTOF(checkArr3);

    printf("Check Array size: %d\n", size4);

#if 0
    for (int i = 0; i < COUNTOF(checkArr3); i++) {
        printf("%s\n", checkArr3[i]);
    }
#else
    print_array(checkArr3);
#endif

    char *checkArr4[1000] = {
        "This is very good",
        "text that has been",
        NULL,
        NULL,
        NULL,
        NULL
    };
    int size5 = COUNTOF(checkArr4);

    printf("Check Array size: %d\n", size5);

#if 0
    for (int i = 0; i < COUNTOF(checkArr4); i++) {
        printf("%s\n", checkArr4[i]);
    }
#else
    print_array(checkArr4);
#endif

    return 0;
}


text:
Q: Next steps after succesfully taking image / selecting from gallery I succesfully made this simple app of where you can either choose and image from gallery or take a picture: Pick Image From Gallery Or Camera In Android Studio Programmatically. But for my purpose, where the selected image needs to serve as a profile image, I want the image to be square.
Also, some photos that are selected from gallery are rotated (Not to mention they are rectangled)
Where do I go from here in order to make user crop and rotate the image before uploading it? I want the final result to be a square image with the correct rotation.

A: In terms of cropping the image, there are many image cropping libraries for Android for you to choose from.
It is possible that one of those will also allow the user to rotate the image. If not, you will need to handle that yourself.
If you only need to allow the user to rotate the image a few ways (e.g., portrait and landscape), you could use a Switch or Spinner to allow the user to choose a rotation, then rotate the ImageView to show them what it looks like. Once they choose a rotation to use, you can use a Matrix to rotate the Bitmap. Ideally, you would rotate the image after cropping, as photos are large and you may run out of memory trying to rotate a photo.

redpajama_set_name: RedPajamaStackExchange


text:
Q: My Macbook Pro's headphone jack is buzzing/humming I have an audio problem with my new macbook pro 2017.
If there is an audio playing my headphone jack starts to buzz (headphones unplugged). When I stop playing audio, after a short period of time, it stops humming. When I plug the headphones and start playing the audio, headphone jack is not buzzing/humming. This is super weird. It looks like macbook for some reason thinks that it has plugged headphones even when it doesn't
Does anyone know how to deal with this problem?

A: Ok, I have fixed this problem by reinstalling the OS.


text:
Q: Query DNS for multiple domains at once I have recently moved servers and want to query all of the accounts domains on the new server to check that they are all resolving to the correct NS.
I am currently using http://www.whatsmydns.net/#NS which is great.
However, it's rather a slow process for 100 domains!
Can anyone recommend any tool available?
Thanks

A: Use dig from the command line, or nslookup if you're on windows. Either of these would be trivial to script and get the data you need.

A: simple bash script to loop and output just the IP address of each domain:
mydomains=(
domain1
domain2
domain3
)

for i in "${mydomains[@]}"; do dig $i +short; done

A: Are they external domains or internal domains? In any case, you can run something like:
I will use serverfault.com as my example domain here.
To resolve the hostname: www.serverfault.com
dig @4.2.2.2 www.serverfault.com +short

To find out the NS for your domain, serverfault.com
dig serverfault.com ns

To find the authoratative name servers for your domain:
dig serverfault.com +nssearch

If you have 100 external domains, you can write a for look and run as a shell scripts. Make sure all zones you are trying to query are on a separate lines. If you know your DNS or want to include in the dig command you can do so as: dig @4.2.2.2 $zone +short
In the above command 4.2.2.2 was my DNS Server.
#!/bin/bash
while read zone; do dig $zone +short; done <myzones.txt

A: I found a PowerShell script that could work.
http://cloud.kemta.net/2012/11/powershell-checking-multiple-dns-records-for-multiple-domains/
I also like to use http://www.intodns.com for DNS work.  Nice clean interface.  However you would still need to enter them one at a time.

A: You will be able to lookup multiple DNS records using this tool I wrote
http://www.matraex.com/quick-domain-research.php
It lists out the domainname, A records if any for @ and www, MX and NS records for the domain,  it lists the Email addresses for the WHOIS contacts,  as well as the NS Records on the Whois and puts them in a table for multiple domains.
I have used it to quickly address many DNS related issues.


text:
Q: Facebook C# SDK cannot resolve FB Login I'm developing an MVC-2 application with Facebook C# SDK and recently Facebook stopped to respond to my login requests. After some research, I've managed to get it working by putting 'localhost' in the 'Site Domain' field in facebook application settings.
Now, login through Facebook Javascript SDK seems to be working alright, but the Facebook C# SDK always returns the FacebookApp.Session value as null. To be sure that this issue is not because of some configuration or development mistakes, I've even tried the sample application from Facebook C# SDK website, but no luck.
Any suggestions on this issue?
Thanks.

A: Did you start with the sample application? If you start with that it should just work out of the box. I am guessing you have cookie support set to false in the web.config setting. http://facebooksdk.codeplex.com/releases/view/54371#DownloadId=160969 Your web.config file should look like this:
  <configSections>
    <section name="facebookSettings" type="Facebook.FacebookConfigurationSection"/>

  </configSections>

  <facebookSettings
        apiKey="your_api_key"
        apiSecret="your_api_secret"
        appId="your_app_id"
        cookieSupport="true" />

Also, make sure you are using the released version and not the latest source code. The source code is not for production use and has some bugs that will make it hard for you to learn the toolkit.

A: I've tried to work with this library, but imho wasn't that much fun.
For the Facebook Application you have to enter a static port number and your Visual Studio build in IIS have to run on this port, too.
For example:

http://localhost:55555/

If you've got enough time, try to take a look at https://github.com/prabirshrestha/FacebookSharp. It comes with a build in FacebookController for ASP.net MVC.
Works great for me :-)


text:
Q: Git First Push to Remote Repository Failed I created a new Visual Studio 2015 Solution and put the source files in a local repository on my laptop (Windows 7). On my Mac Fileserver I created a new bare repository (git init --bare --shared filename.git).
Back on my laptop I connected to my Mac Fileserver using a VPN connection and mounted the mapped drive where the remote repository is.
I configure the remote repository in Visual Studio (file:///Z:\path to remote repository).
I try to push the committed files but I get the following error:

Error encountered while publishing branch to the remote repository:
  Failed to rename lockfile to 'Z:/path to .git
  file/objects/pack/pack-6e7d6ac4bae59d61509d77b0ab11a393625e8859.idx':
  Access is denied.

I opened the local repository in Git Gui and tried again but the same error.
I have followed the same process on a simpler Visual Studio project with success, perhaps I'm missing something obvious.
Can anyone offer any suggestions please?


text:
Q: Function template parameter deduction I am writing the small C++ message-based communication framework with using of the Reactor pattern. The problem which I have met is the serialization of the application (user-defined) messages. To prevent API from redudant information I make an assumption about the serialization function. There is an Archive class which holds the serialized form of the message, however it is the template, so the user could choose the binary form of its. The assumption is that for each message there will be only one serialization function available (defined), so the type deduction of the binary type could be cleary deduced from the function signature. Let's see the code:
template <typename T> struct Archive {
  T t;
};  // struct Archive

template <typename Message, typename T>
void serialize(const Message& msg, Archive<T>* const ar);

struct Signal {
  void* payload;
};

template <typename T> struct Wrapper {
  Signal* pack() {
    Signal* s = new Signal;
    archive(&serialize, &s->payload);
    return s;
  }

  template <typename P>
  void archive(void(*f)(const T&, Archive<P>* const), void** payload) {
    Archive<P> ar;
    f(t, &ar);
    P* p = new P;
    *p = ar.t;
    *payload = p;
  }

  T t;
};

struct TestMsg {
  int i;
};

template <>
void serialize(const TestMsg& msg, Archive<int>* const ar) {
  ar->t = msg.i;
}

int main() {
  Wrapper<TestMsg> msg;
  msg.pack();
  return 0;
}

Compiler claims that it cannot deduce the P type. Is there any other way (without traits) to help compiler with such deduction?
Kind Regard, Gracjan
EDIT(14-05-2013 15:42): According to the request in comment I attach the Traits solution:
/****** Library part *******/
template <typename T> struct Archive {
  T t;
};  // struct Archive

template <typename T> struct MessageTrait {};

template <typename Message, typename T>
void serialize(const Message& msg, Archive<T>* const ar);

struct Signal {
  void* payload;
};

template <typename T> struct Wrapper {
  Signal* pack() {
    typedef Archive<typename MessageTrait<T>::ArchType> ArchiveType;
    Signal* s = new Signal;
    ArchiveType ar;
    serialize(t, &ar);
    return s;
  }

  T t;
};

/****** Application part ******/
struct TestMsg {
  int i;
};

template<> struct MessageTrait<TestMsg> {
  typedef int ArchType;
};

template <>
void serialize(const TestMsg& msg, Archive<int>* const ar) {
  ar->t = msg.i;
}

int main() {
  Wrapper<TestMsg> msg;
  msg.pack();
  return 0;
}

A: template <typename Message, typename T>
void serialize(const Message& msg, Archive<T>* const ar);

template <typenane T>
Signal* Wrapper<T>::pack() {
    Signal* s = new Signal;
    archive(&serialize, &s->payload);
    return s;
}

In the above code, serialize is the name of a template, and used in place of a function it represents the complete set of overloads result from all possible specializations of the template (i.e. every possible substitution of the template arguments). At the same time archive is a template that can potentially take any function from the subset that comply with the minimal restriction that the second argument is an instantiation of the Archive template.
The problem here is not that the template cannot deduce the argument, but that there are infinite types that match the requirements, your problem is too open ended. Which brings the next question, does everything need to be a template?
In general it is a bad idea to specialize function templates, could the serialize template be really an overload? Can you reduce the generality of the problem to a situation where deducible or not there is just one or two candidates? I have the feeling that you are opening yourself to too many degrees of liberty that you might or not need and then getting bit by the fact that anything can match.


text:
Q: Proof verification of the tangent space of the tangent bundle of the sphere using the canonical identifications Let $\iota : S^m \hookrightarrow \mathbb{R}^{m+1} $ and $\iota_T : TS^m \hookrightarrow TR^{m+1}$ be embeddings and let $J_v : V \xrightarrow{\cong} T_vV$ be the canonical isomorphism where $V$ is a vector space. Then one can show that $$ D\iota(p)(T_pS^m) = J_{\iota(p)}(\iota(p)^\bot) $$
where $x^\bot = \{y \in \mathbb{R}^{m+1} | \langle x, y\rangle\ = 0\}$. I would like to continue to use these maps for the moment to understand all the details and different objects before progressively get rid of these maps for clarity in a second time.

*

*Is this similar description for the tangent space of the tangent bundle correct?

Recall that the tangent bundle is $$TS^m = \left\{(p, \xi) \in S^m \times T_pS^m | \left\langle\iota(p), J_{\iota(p)}^{-1} \circ D\iota(p)(\xi)\right\rangle = 0\right\}. $$
Given $(p, \xi) \in TS^m$, consider a smooth curve $\gamma : (-\varepsilon,\varepsilon) \rightarrow TS^m$ such that $$ \gamma(0) = (p, \xi), \quad \dot{\gamma}(0) = (q, \zeta)$$
where $(q, \zeta) \in T_{(p, \xi)}(TS^m).$ Then by differentiating at time $t=0$ the fact that $\mathrm{pr}_1 \circ \gamma$ has image in $S^m$, we get
$$ 0 = \frac{d}{dt}\bigg|_{t=0} (|\iota \circ \mathrm{pr}_1 \circ \gamma(t)|^2) = \left\langle \iota(p), J_{\iota(p)}^{-1} \circ D\iota(p)(q)\right\rangle,$$
and by differentiating at time $t = 0$ the the scalar product condition of $TS^m$, we get
\begin{align}
0 &= \frac{d}{dt}\bigg|_{t=0} \left(\left\langle \iota \circ pr_1 \circ \gamma(t), J_{\iota \circ \mathrm{pr}_1 \circ \gamma(t)}^{-1} \circ D\iota(\mathrm{pr}_1 \circ \gamma(t))(\mathrm{pr_2} \circ \gamma(t)) \right\rangle\right) \\
&= \left\langle \iota(p), J_{(\iota(p), J_{\iota(p)}^{-1} \circ D\iota(p)(\xi))}^{-1} \circ D\iota_T(p, \xi)(\zeta)\right\rangle + \left\langle J_{\iota(p)}^{-1} \circ D\iota(p)(\xi), J_{\iota(p)}^{-1} \circ D\iota(p)(q)\right\rangle.
\end{align}
Since $(q, \zeta)$ was arbitrary, we have the inclusion
$$ D\iota_T(p, \xi)(T_{(p, \xi)}(TS^m)) \subset J_{(\iota(p), J_{\iota(p)}^{-1} \circ D\iota(p)(\xi))}((\iota(p), J_{\iota(p)}^{-1} \circ D\iota(p)(\xi))^\vdash) $$
where $(x, y)^\vdash = \{(q, \zeta) \in \mathbb{R}^{m+1} \times \mathbb{R}^{m+1} | \langle x, q\rangle = 0 = \langle x, \zeta \rangle + \langle y, q\rangle\}.$ Since, both of the vector spaces are of dimension $2m$, we have equality.

Edits
To be more readable, this is what the computation would look like if we use the identifications :
We recall that $$ TS^m = \{ (p, \xi) \in S^m \times \mathbb{R}^{m+1} | \langle p, \xi \rangle = 0 \}. $$
Given $(p, \xi) \in TS^m$, consider a smooth curve $\gamma : (-\varepsilon,\varepsilon) \rightarrow TS^m : t \mapsto (p(t), \xi(t))$ such that $$ \gamma(0) = (p, \xi), \quad \dot{\gamma}(0) = (q, \zeta)$$
where $(q, \zeta) \in T_{(p, \xi)}(TS^m).$ Then by differentiating at time $t=0$ the fact that $|p(t)|^2=1$, we get
$$ 0 = \langle p, q \rangle, $$
and by differentiating at time $t = 0$ the scalar product condition on $TS^m$, we get
$$ 0 = \langle p, \zeta \rangle + \langle \xi, q \rangle. $$
Since $(q, \zeta)$ was arbitrary, we have the inclusion
$$T_{(p,\xi)}(TS^m) \subset (p, \xi)^\vdash,$$
and we conclude by dimension.

A: I didn't fully read your first computations, but your second one is right. In general, we have the canonical identification $T\Bbb{R}^m\cong \Bbb{R}^m\times \Bbb{R}^m$ given by $[\gamma]\mapsto (\gamma(0),\gamma'(0))$. In words, we take an equivalence class of curves and we keep track of the base point and the vector-part (the derivative is possible since $\gamma$ takes values in the vector space $\Bbb{R}^m$).
Now, a slight generalization of what you've done is the following. Let $f:\Bbb{R}^n\to\Bbb{R}^k$ be a smooth submersion and $\rho\in\Bbb{R}^k$ a regular value for $f$. Then, as we know from the inverse/implicit function/regular-value theorem, $S:= f^{-1}(\{\rho\})$ is a smooth $n-k$-dimensional embedded submanifold of $\Bbb{R}^n$, and the tangent space at a point $p\in S$ is given by (after the canonical identification) $\ker Df_p$. Now, the tangent bundle can be identified as
\begin{align}
TS=\{(p,\xi)\in S\times \Bbb{R}^n\,|\,\,Df_p(\xi)=0\}
\end{align}
Now, the tangent space $T_{(p,\xi)}(TS)$ can be calculated exactly as you have just done. Take a curve $t\mapsto \gamma(t)=(p(t),\xi(t))$ in $TS$ passing through $(p,\xi)$ when $t=0$. Then, $t\mapsto p(t)$ is a curve in $S$, so $Df_p[p'(0)]=0$. Next, we also have the condition that for all $t$, $Df_{p(t)}[\xi(t)]=0$. Differentiating this and setting $t=0$, we get (by "product" and chain rule)
\begin{align}
D^2f_{p(0)}[p'(0),\xi(0)] +Df_{p(0)}[\xi'(0)]&=0.
\end{align}
Once again, arguing using dimension reasons (both are $2(n-k)$-dimensional), we find that
\begin{align}
T_{(p,\xi)}(TS)&=\{(q,\zeta)\in\Bbb{R}^n\times\Bbb{R}^n\,|\,\,Df_p(q)=D^2f_p[q,\xi]+Df_p[\zeta]=0\}
\end{align}
In the case of spheres, we have $f(x)=\langle x,x \rangle$, so $Df_p(\xi)=2\langle p,\xi \rangle$ and $D^2f_p[v,w]=2\langle v,w\rangle$, which coincides exactly with what you found.


text:
Q: DataGrid View Not Showing Newly Added Record using Access Database I am new to C# and I want to do this ASAP as I've had this problem since past week. I have tried a few approaches and not yet gotten the correct output. Here is my code:
private void btnDelete_Click(object sender, EventArgs e)
    {
        try
        {
            String itemcode = tbItemCode.Text.ToString();
            String shade = tbShade.Text.ToString();
            String rollnumber = tbRollNumber.Text.ToString();

            System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Eranga\Documents\Visual Studio 2010\Projects\RollAllocationModel\RollAllocationModel\Roll.mdb;Persist Security Info=True;Jet OLEDB:Database Password=admin");
            String deletequery = "DELETE FROM TabRoll WHERE (ItemCode = '" + itemcode + "') AND (Shade = '" + shade + "') AND (RollNumber = '" + rollnumber + "')";
            //String deletequery = "SELECT * FROM TabRoll";
            //code by query builder ----> DELETE FROM TabRoll WHERE (ItemCode = '" + itemcode + "') AND (Shade = '" + shade + "') AND (RollNumber = '" + length + "');
            conn.Open();

            OleDbDataAdapter da = new OleDbDataAdapter(deletequery, conn);
            OleDbCommandBuilder cb = new OleDbCommandBuilder(da);
            DataTable dt = new DataTable();
            da.Fill(dt);

            BindingSource bSource = new BindingSource();
            bSource.DataSource = dt;

            dataGridView1.EndEdit();
            bSource.EndEdit();
            da.Update(dt);
            dataGridView1.DataSource = bSource;

            conn.Close();
            MessageBox.Show("Data deleted");
        }
        catch (Exception exceptionObj)
        {
            MessageBox.Show(exceptionObj.Message.ToString());
        }
    }

Why doesn't the DataGrid does not update with the new record.


text:
Q: ExcelSoftArtisans - Bug on Save method with open Stream - Cannot accessed closed file I have the following issue:
I'm doing an export of an ASP.Net GridView directly to an excel file.
I'm setting an image as a header in this method:
private static void insertPageHeaderFooter(ExcelInterfaceSoftArtisans excel,DateTime generatedDateTime)
    {
        StringBuilder builderFooterLeft = new StringBuilder();
        builderFooterLeft.Append("&08Comfone AG                  Tel: +41 31 341 10 10");
        builderFooterLeft.Append("\r");
        builderFooterLeft.Append("&08Nussbaumstrasse 25     Fax: +41 31 341 10 11");
        builderFooterLeft.Append("\r");
        builderFooterLeft.Append("&08CH-3000 Bern 22           www.comfone.com");

        StringBuilder builderFooterRight = new StringBuilder();
        String sDateTime = generatedDateTime.ToString(CultureInfoHandler.ShortDateShortTimeFormat);
        builderFooterRight.Append("&08&F");
        builderFooterRight.Append("\r");
        builderFooterRight.Append(string.Format("&08 {0}", sDateTime));
        builderFooterRight.Append("\r"); //new line
        builderFooterRight.Append("&08Page &P of &N");

        excel.SetHeader("&G", 0.6, HeaderFooterSection.Section.Left, false);
        excel.SetFooter(builderFooterLeft.ToString(), HeaderFooterSection.Section.Left, false);
        excel.SetFooter(builderFooterRight.ToString(), HeaderFooterSection.Section.Right, false);
    }

protected void SetHeader(string sText, double dImageSizeFactor, HeaderFooterSection.Section section, Worksheet sheet)
    {
       string headerAbsolutePath = HttpContext.Current.Server.MapPath("~/Resources/Mandates/CHECF.png");
        Stream imageStream = new FileStream(headerAbsolutePath, FileMode.Open, FileAccess.Read);
        Size imageSize = Image.FromStream(imageStream).Size;
        imageStream = new FileStream(headerAbsolutePath, FileMode.Open, FileAccess.Read);
        HeaderFooterSection header = sheet.PageSetup.GetHeader(section);
        header.SetContent(sText, imageStream);
        header.SetContent(sText);
        header.GetPicture().Height = (int)(imageSize.Height * dImageSizeFactor);
        header.GetPicture().Width = (int)(imageSize.Width * dImageSizeFactor);

        imageStream.Close();
    }

As you can see on the last line, I close the Stream.
Now, I want to save my excel file this way:
HttpContext.Current.Response.ClearContent();
                HttpContext.Current.Response.Clear();
                HttpContext.Current.Response.ClearHeaders();
                excel.SaveWorkbook(sFileName, HttpContext.Current.Response, false);
/// <summary>
    /// Saves the current Workbook under the given filename
    /// </summary>
    /// <param name="filename"></param>
    /// <param name="response"></param>
    /// <param name="openInBrowser"></param>
    public void SaveWorkbook(string filename, HttpResponse response, bool openInBrowser)
    {
        if (book != null)
        {
            application.Save(book, response, filename, openInBrowser);
        }
    }

but when I close the stream in the SetHeader method, I get the following error:
    Error Message: Cannot access a closed file.

 Stack Trace:   at System.IO.__Error.FileNotOpen()
at System.IO.FileStream.Seek(Int64 offset, SeekOrigin origin)

and when I don't close the stream in the SetHeader method, the file is correctly saved.
Are you aware of this bug? How is it possible that I need to have an open stream in order to save an excel file? What can I do to fix that?
I'm attaching you the whole classes I'm using, so you can identify the problem better.
Thanks for your quick answer and solution on this problem.

A: [Disclaimer: I am the product owner of OfficeWriter]
This issue has been confirmed as a bug and has been submitted to the OfficeWriter development team.
In the meantime, I would recommend Sam's suggested workaround of using the overload that takes the image's file path instead of the image stream.
Here is a generic code snippet for how to insert an image into the header of an Excel file using the file path overload of HeaderFooterSection.SetContent():
//Open the workbook and get a handle on the worksheet that will contain the
//image in the header
ExcelApplication xla = new ExcelApplication();
Workbook wb = xla.Open(Page.MapPath("\\template.xlsx"));
Worksheet ws = wb.Worksheets["Sheet1"];

//Set the header
HeaderFooterSection header = ws.PageSetup.GetHeader(HeaderFooterSection.Section.Left);
header.SetContent("&G", Page.MapPath("\\images\\image1.png"));

Please see our documentation for additional reference on the SetContent() overloads and using ExcelWriter to format headers and footers in workbooks.

A: This issue has been addressed in the recent 8.5.1 release of OfficeWriter.  See the change log.


text:
Q: javascript files cant reload when struts2 page refresh Here is my problem, I'm using Angular and Require.js with Struts2 and lets say i have the URL
http://localhost:6666/struts-context/action/#/angular-fragment
and a resource in
http://localhost:6666/struts-context/scripts/script.js,
when i hit the refresh button or F5 on this URL, my "struts-context" get lost, and the server try to find the script on
http://localhost:6666/scripts/script.js,
is like the URL http://localhost:6666/struts-context/action/#/angular-fragment is not interpreted by struts.
That is all, thanks for any response.

A: You can use <s:url> tag
 <s:url action="scripts/script.js" var="jsURL"></s:url>
 <script type="text/javascript" src="${jsURL}"></script>


text:
Q: Writing ArrayList to a file in a Web Service I want to write an ArrayList file data.txt my code:
try{
    File destination = new File("data.txt");
    ObjectOutputStream os = new ObjectOutputStream(new FileOutputStream(destination));
    os.writeObject(userList);
    os.close();
} catch....

This do's not trow any exceptions, just nothing.. Code runs normal. Is this code not going to work for a Web Service ? (REST @ Jersey, pretty sure nothing to do with it)

A: Here the updated code:
FileOutputStream userfile = new FileOutputStream("C:\\user.dat");
ObjectOutputStream userstream = new ObjectOutputStream(userfile);
userstream.writeObject(userList);
userstream.close();

Notice the "C:\data.dat" the code was not able to run with just data.dat ( no files where visible created on source folder.
For input the code is as follows:
ArrayList<User> dataList; // ** User is a custom Class
....
FileInputStream userfile = new FileInputStream("C:\\user.dat");
ObjectInputStream usersteam = new ObjectInputStream(userfile);
dataList = (ArrayList<User>)usersteam.readObject();
usersteam.close();

A: Use a file upload servlet rather than a JAX-RS enpoint.Its much easier in the long run. In relation to writing from an arraylist to a file,  This code will write it to a file and also check if the file has already been uploaded or not.
private List<File> files=new ArrayList<File>();
  private String filename="yourfilename.dat"

     private boolean fileHasAlreadyBeenUploaded() throws IOException, ClassNotFoundException {

    boolean hasFileAlreadyBeenUploaded=false;
    File currentfile=new File(fileName);
    if(!currentfile.exists()){
        currentfile.createNewFile();
        ObjectOutputStream output
        = new ObjectOutputStream(
              new FileOutputStream(currentfile));
        files.add(currentFile);
        output.writeObject(currentFile);
        output.close();
        hasFileAlreadyBeenUploaded=false;
    }
    else{
         ObjectInputStream input
            = new ObjectInputStream(
                  new FileInputStream(currentfile));

         files = (List<File>) (input.readObject());
         input.close();
        for(int i=0;i<files.size();i++){
            if(FileUtils.contentEquals(files.get(i), currentfile)){
                hasFileAlreadyBeenUploaded=true;
            }
        }
        if(!hasFileAlreadyBeenUploaded){
            ObjectOutputStream output
            = new ObjectOutputStream(
                  new FileOutputStream(fileName));
            files.add(currentfile);
            output.writeObject(currentfile);
            output.close();
        }
    }
    return hasFileAlreadyBeenUploaded;

}

and then you ca ndo whatever you want with it. With your web service you are better off using a Fileupload servlet that JAX-RS endpoint. The annotation @Webservlet will provide you with that endpoint
Please look at the following link for that example
File upload servlet java


text:
Q: Python watchdog: ignoring duplicate events I'm trying to set up watchdog so I can monitor changes to JavaScript files. But you always get duplicate events when a single file is modified.
I want to set it up so that when a file is modified it looks at the time of the event and if it is the same second as the previous event then it doesn't do anything. This way it can ignore the duplicate events. Is there a way to achieve this and always have the time of the previous event stored in a variable?
import time
from os import path
from watchdog.observers import Observer
from watchdog.events import FileSystemEventHandler

class MyHandler(FileSystemEventHandler):
    def on_modified(self, event):
        print(time.ctime(), f'path : {event.src_path}')

if __name__ == "__main__":
    event_handler = MyHandler()
    observer = Observer()
    observer.schedule(event_handler, path=path.join(path.dirname(__file__), 'static/js'), recursive=False)
    observer.start()

    try:
        while True:
            time.sleep(1)
    except KeyboardInterrupt:
        observer.stop()
    observer.join()

A: One naive way to do this is to store the files/dates in a dictionary, and then check to see if the time/file source is in the dictionary before handling the event.
class MyHandler(FileSystemEventHandler):
    file_cache = {}

    def on_modified(self, event):
        seconds = int(time.time())
        key = (seconds, event.src_path)
        if key in self.file_cache:
            return
        self.file_cache[key] = True
        # Process the file

If you are worried about the number of events, you could try using cachetools to cache the results so the dictionary stays a bit smaller.

A: I am not sure anybody else. but I took on_closed event instead of modified as normally file writer will close the file after done with writing the file (at least in my case).
Be noted that on_closed event seems not triggered on win32 system.


text:
Q: Expo cannot auto import React-native on Visual studio code in Typescript I just start to learn the react-native with Expo SDK.
I follow the official tutorial to init managed Typescript template.

And I found that I can only import unique React-native component.

Not the React-native component which has same name across Dom, React.

I saw the node-modules already have the Types but not know why the auto-import not work.
This is what vscode try to find but not go through the React-native type definition.

But React-native types has the type definition.

If I import the Text manually from the React-native, it can get the correct definition.
import { Image, StyleSheet, Text, View } from 'react-native';

Any help is appreciated.


text:
Q: Php table template for sql queries In a php inventory management application let's say I'm having two sql tables : tblAcq and tblInvoice. Both identical (ID, Number, Note, Date) but with different data.
I have two pages : acq.php and invoice.php. Both pages display a html table from a query (SELECT * FROM tblX).
Because the table is identical on both pages and the only difference between the two is in the FROM tblX (tblAcq or tblInvoice), is there any way I can make a template for the table (for example orders.php) and include it in acq.php and invoice.php?
I'm new to php and I can't figure this out because the table must be in a while clause
The code is something like this for acq.php page:
<?php
$sqlacq ="SELECT * FROM tblAcq";
$resultacq = $conn->query($sqlacq);
?>

                AcqID
                Data (an-luna-zi)
                AcqNumber
                AcqSupplier
                AcqNote
                InStocLa

          <?php
        if ($resultacq->num_rows > 0) {
            while($rowacq = $resultacq->fetch_assoc()) {
           ?>

                <?php echo $rowacq["AcqID"]; ?>
                <td contenteditable="true" onBlur="saveToDatabase(this,'AcqDate','<?php echo $rowacq["AcqID"]; ?>')" onClick="showEdit(this);"><?php echo $rowacq["AcqDate"]; ?>
                <td contenteditable="true" onBlur="saveToDatabase(this,'AcqNumber','<?php echo $rowacq["AcqID"]; ?>')" onClick="showEdit(this);"><?php echo $rowacq["AcqNumber"]; ?>
                <td contenteditable="true" onBlur="saveToDatabase(this,'AcqSupplier','<?php echo $rowacq["AcqID"]; ?>')" onClick="showEdit(this);"><?php echo $rowacq["AcqSupplier"]; ?>
                <td contenteditable="true" onBlur="saveToDatabase(this,'AcqNote','<?php echo $rowacq["AcqID"]; ?>')" onClick="showEdit(this);"><?php echo $rowacq["AcqNote"]; ?>
                <?php echo $rowacq["InStocLa"]; ?>
                <a href="javascript:delete_id(<?php echo $rowacq["AcqID"]; ?>)">

        <?php
            }
        }

A: you can embed html in php using echo statements.
<?php
$sqlacq ="SELECT * FROM tblAcq";
$resultacq = $conn->query($sqlacq);
?>

                AcqID
                Data (an-luna-zi)
                AcqNumber
                AcqSupplier
                AcqNote
                InStocLa

          <?php

        if ($resultacq->num_rows > 0) {
            while($rowacq = $resultacq->fetch_assoc()) {
              echo '
';
              echo ''.$rowacq["AcqID"].'	';
              echo ''.$rowacq["AcqDate"].'	';
              echo ''.$rowacq["AcqNumber"].'	';
              echo ''.$rowacq["AcqSupplier"].'	';
              echo ''.$rowacq["AcqNote"].'	';
              echo ''.$rowacq["InStocLa"].'	';
              echo '	'
              echo "
";
            }
          }

?>

EDIT:
In your case, $rowacq is an assoc array. So your final code will be,
<?php
$sqlacq ="SELECT * FROM tblAcq";
$resultacq = $conn->query($sqlacq);
?>

                AcqID
                Data (an-luna-zi)
                AcqNumber
                AcqSupplier
                AcqNote
                InStocLa

       <?php
        function table_print($rowacq) {
              echo '
';
              echo ''.$rowacq["AcqID"].'	';
              echo ''.$rowacq["AcqDate"].'	';
              echo ''.$rowacq["AcqNumber"].'	';
              echo ''.$rowacq["AcqSupplier"].'	';
              echo ''.$rowacq["AcqNote"].'	';
              echo ''.$rowacq["InStocLa"].'	';
              echo '	'
              echo "
";

        }
       if ($resultacq->num_rows > 0) {
            while($rowacq = $resultacq->fetch_assoc()) {
                table_print($rowacq);
            }
       }
?>


text:
Q: Which are MVVM pattern features and extensions? Which are MVVM pattern features and extensions?
As I have noticed there are many MVVM frameworks out there, and all share the same concept, even though there are some differences. I won't ask what the differences are, however I would like to create a general list of key features/extensions for MVVM pattern that will provide a good starting point when choosing between different frameworks or own created MVVM pattern .
Please explain the feature you are mentioning. For making the question clear I'll start with my own knowledge. I'll complete the list as I get answers.
Patterns

*

*ObservableCollection

*INotifyPropertyChanged

*ICommand

*Mediator

*Behaviours(System.Windows.Interactivity)

Structure

*

*Model

*ViewModel

*ModelView

A: Behaviours(System.Windows.Interactivity) are very usefull when coding mvvm. there are a lot out there.


text:
Q: Definition of limsup when points tend to boundary of a region I am reading Complex Analysis by Marshall,he said in the remark of maximal principle:
The reader should verify the alternative form:if $u$ is continuous and subharmonic on a region
$\Omega$ in the extending  complex plane (i.e. $C\cup\{\infty\}$),then
$\limsup_{z\rightarrow\partial\Omega}u(z)=sup_{z\in\Omega}\ u(z) $
I don't get what the lefthand side means.I do know what $\limsup$ means when $z\rightarrow z_0$ for some $z_0$,but I even don't know what $z\rightarrow\partial\Omega$ means.
I try to regard the 'limsup' as the limsup when distance from $z$ to $\partial\Omega$ tends to $0$,but $\Omega$ is a region in the extending complex plane,so Euclidean metric is not available.But if I use other metric on $C\cup\{\infty\}$,it will be too complicate.
Does anyone know what Marshall wants to say ?
Thanks in advance !


text:
Q: Get Ruby class constant dynamically by name I have a class API that pulls objects from a third party API and builds them into objects that are subclasses of type APIObject.  APIObject subclasses match the object names from the API that I'm pulling from:
User < APIObject
Account < APIObject

I would like to define a class method in APIObject that allows me to pull objects using standard Rails accessors:
user = User.find id

I would like the method to translate this call into an API call like this:
API::User::findById id

I would like to access the name of the APIObject subclass (User) using self.class.name and use that to call the constant (API::User), but I know API::self.class.name won't work.  I could rewrite this method over and over again for every subclass, but it seems like this should be possible without doing that.  Suggestions?

A: I think you're looking for const_get. Perhaps something like:
def self.find(id)
  API.const_get(self.name).find_by_id(id)
end

(note you only need self.name, since this is already in the context of the class, and self.class.name will just be Class).


text:
Q: filled contour plot in R I am trying to generate a filled contour plot in R.  My data labels x and y are length 20 vectors, and my z matrix is 20 by 20.  The following is my code, with the filled.contour command copied directly from the r help(filled.contour) file, just with extraneous parameters removed:
x <- seq(1,5)
y <- seq(1,5)
cells <- c(1,4,9,16,25,1,4,9,16,25,1,4,9,16,25,1,4,9,16,25,1,4,9,16,25)
z <- matrix(cells,nrow=5,ncol=5,byrow=TRUE)
filled.contour(x,y,z,nlevels = 20,col = cm.colors(19))

A: You have to remove col =color.palette(length(levels) - 1). You have to know that in R manuals, the line that is under Usage just shows which parameters are available and next to it the default parameter. Which does not necessarily mean you can write it exactly the same way. So if you leave these parameter, it will automatically take the value that is stated there.
For examples you should check the Examples section, which is usually quite rich.
EDIT
To get 19 colors you have to write
filled.contour(x,y,z,nlevels = 20,col =cm.colors(19))

cm.colors is a function that returns n colors. color.palette can not do that for you because it is not a function but a parameter for filled.contour.


text:
Q: How can I run a command on an existing container in IBM Bluemix? I've got an existing container on IBM Bluemix that is having issues while running.
I need to execute commands inside the container without stopping to get more information to allow me to debug the issue. The container doesn't have an SSH daemon enabled allowing me remote access.
Is there a way to execute remote commands and get the output?

A: In Docker 1.3, docker introduced the exec command allowing you to spawn a new process inside a running container.
IBM Containers supports using this Docker command with containers running on IBM Bluemix using the IBM Containers plugin for the Cloud Foundry CLI.
Use the following command to retrieve the container ID for the running instance you want to debug:

$ cf ic ps

Now, we can open a bash shell (or execute any available command) on the running container using the command below:

$ cf ic exec -it <container_id> /bin/bash


text:
Q: Why is my UILabel not saving/loading with NSUserDefaults? Here is my code to save and load.  I did an NSLog, and it shows the text which should be saved/loaded but it isn't, and just shows the default text on launch in the UILabel.
UPDATE:
Also, in my NSLog, it does actually load the text but I think the problem is getting it into the label.
To save:
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];

NSString* CalLabel1Text = CalLabel1.text;
[defaults setObject:CalLabel1Text forKey:@"CalLabel1TextKey"];
NSString* callbltxt1 = [defaults objectForKey:@"CalLabel1TextKey"];
CalLabel1.text = callbltxt1;
NSLog(@"Saved Cal Label 1: %@", callbltxt1);

NSString* CalLabel2Text = CalLabel2.text;
[defaults setObject:CalLabel2Text forKey:@"CalLabel2TextKey"];
NSString* callbltxt2 = [defaults objectForKey:@"CalLabel2TextKey"];
CalLabel2.text = callbltxt2;
NSLog(@"Saved Cal Label 2: %@", callbltxt2);

NSString* CalLabel3Text = CalLabel3.text;
[defaults setObject:CalLabel3Text forKey:@"CalLabel3TextKey"];
NSString* callbltxt3 = [defaults objectForKey:@"CalLabel3TextKey"];
CalLabel3.text = callbltxt3;
NSLog(@"Saved Cal Label 3: %@", callbltxt3);

NSString* CalLabel4Text = CalLabel4.text;
[defaults setObject:CalLabel4Text forKey:@"CalLabel4TextKey"];
NSString* callbltxt4 = [defaults objectForKey:@"CalLabel4TextKey"];
CalLabel4.text = callbltxt4;
NSLog(@"Saved Cal Label 4: %@", callbltxt4);

NSString* CalLabel5Text = CalLabel5.text;
[defaults setObject:CalLabel5Text forKey:@"CalLabel5TextKey"];
NSString* callbltxt5 = [defaults objectForKey:@"CalLabel5TextKey"];
CalLabel5.text = callbltxt5;
NSLog(@"Saved Cal Label 5: %@", callbltxt5);

NSString* CalLabel6Text = CalLabel6.text;
[defaults setObject:CalLabel6Text forKey:@"CalLabel6TextKey"];
NSString* callbltxt6 = [defaults objectForKey:@"CalLabel6TextKey"];
CalLabel6.text = callbltxt6;
NSLog(@"Saved Cal Label 6: %@", callbltxt6);

[defaults synchronize];

To load:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
NSString* CalLabel1Text = CalLabel1.text;
NSString* callbltxt1 = [defaults objectForKey:@"CalLabel1TextKey"];
CalLabel1.text = callbltxt1;
NSLog(@"Loaded Cal Label 1: %@", callbltxt1);

NSString* CalLabel2Text = CalLabel2.text;
NSString* callbltxt2 = [defaults objectForKey:@"CalLabel2TextKey"];
CalLabel2.text = callbltxt2;
NSLog(@"Loaded Cal Label 2: %@", callbltxt2);

NSString* CalLabel3Text = CalLabel3.text;
NSString* callbltxt3 = [defaults objectForKey:@"CalLabel3TextKey"];
CalLabel1.text = callbltxt3;
NSLog(@"Loaded Cal Label 3: %@", callbltxt3);

NSString* CalLabel4Text = CalLabel4.text;
NSString* callbltxt4 = [defaults objectForKey:@"CalLabel4TextKey"];
CalLabel1.text = callbltxt4;
NSLog(@"Loaded Cal Label 4: %@", callbltxt4);

NSString* CalLabel5Text = CalLabel5.text;
NSString* callbltxt5 = [defaults objectForKey:@"CalLabel5TextKey"];
CalLabel5.text = callbltxt5;
NSLog(@"Loaded Cal Label 5: %@", callbltxt5);

NSString* CalLabel6Text = CalLabel6.text;
NSString* callbltxt6 = [defaults objectForKey:@"CalLabel6TextKey"];
CalLabel6.text = callbltxt6;
NSLog(@"Loaded Cal Label 6: %@", callbltxt6);

[defaults synchronize];

Why is this not working for me? I put the "save" code onto a button action and the "load" code in viewDidLoad.

A: I bet you forgot to wire up the referencing outlets in Interface Builder.
Also, your code has unused variables.

A: Check your settings.bundle file and its Root.plist. There might be some data problem or the objectForKey problem. Check this link
Hope it will help you out.


text:
Q: The electron and neutrino spin Can you please clarify some basic notions about spin?
Can you please explain what is intended when they say that the spin of a neutrino is left-handed and equal to -1/2?

Does it mean its angular momentum is equal in direction and strength to the spin of the electron ( $h /4\pi$), even though its mass is about one million times smaller? If so, is there an explanation for that? Is there any experimental direct evidence of that magnitude?
Also, since the electron g-factor is 2, does that mean that its value is $h /2 \pi$ , equal to the orbital angular momentum in the hydrogen atom?

A: The spin of a fundamental fermionic particle always has the absolute value $\frac{\hbar}{2}$. This does not relate to its orbital angular momentum, it's just what the spin of a fundamental fermion is.
It now turns out that, for massless particles, there is the notion of helicity (see also What is polarisation, spin, helicity, chirality and parity?), which is the projection (i.e. the relative direction) of spin and momentum.
In your picture, someone decided to orient the axis along which one component of the spin is measured parallel to the particles momentum, so that $+1/2$ spin corresponds to the spin being parallel to the linear momentum, and $-1/2$ to them being anti-parallel. In situations where "neutrinos are massless" is a good approximation, this picture is Lorentz-invariant and indeed a good description for the otherwise rather technical notion of chirality.
The electron cannot correspond to an anti-neutrino because the latter has zero electrical charge. Spin is only one of many quantum numbers.

A:
My question is about the spin of the neutrino, and the evidence (or speculative arguing) for its magnitude which is not proportionate to its mass.

You are dealing with "things" that are supposed to be point particles, so they should not, in classical terms, have a mass in the first place. The math takes over from common sense notions on this scale, and the spin of the neutrino has to be 1/2 to conserve quantum numbers. The mass is the link between the classical world, in which we expect it to be a certain value, and the quantum world, in which the particles are not real in a way we understand.
I hopefully will not annoy you because you already know this. Because "spin" is an analogy, with absolutely nothing to do with ordinary soccer ball type spin, you could have asked the same question about the top quark, which has a huge mass but still has spin angular momentum of 1/2, because that is what we define it to have.
So comparing the mass of one point object (which classically should not have a mass) with another point object with lower mass, and expecting a different angular momentum will not make sense in ordinary terms, but this is not the ordinary world you are asking about.


text:
Q: Split array into chunks of a total value I have an array of values that I need to split in chunks of a total value. Each chunks total value should not be higher than 4.
var arr = [1, 2, 4, 1, 1, 4, 2, 2, 1, 4];

This should become something like:
var chunks = [[1, 2, 1], [4], [1, 2, 1], [4], [2], [4];

So I need all values of the original array split up into chunks of variable size, but its total value should never be higher than 4 in this case.

A: Something like this?

var arr = [1, 2, 4, 1, 1, 4, 2, 2, 1, 4];
var max = 4;
var chunks = [];

arr.forEach(x => {
  // get the first chunk that the value can be added to
  var chunk = chunks.find(c => {

    // calculate sum of chunk
    var sum = c.reduce((a, b) => a + b);

    // return true if the sum of the chunk + current value in array iteration is less than max
    return sum + x <= max;
  });

  if (chunk)
    chunk.push(x); // found a chunk. Add value to that.
  else
    chunks.push([x]); // Can't be added to existing chunks. Create new one.
});

console.log(chunks);


text:
Q: Pyorient batch parsing issue I am currently trying to fill an orientdb graph database using pyorient. In general, everything works well. However, I have stumbled across a parsing issue with one of my commands. In Python if I run the following code:
>>> ab = 'UPDATE Patent SET  primary_id = 676, original_abstract = set(original_abstract, "
The present invention relates to compounds of the general formula (I) wherein\\n\\nR1 is the group (A) or (B) or (C) or (D); R2 is a non aromatic\\n\\nheterocycle, or is OR\' or N(R\\")2; R\' is lower alkyl,\\n\\nlower alkyl substituted by halogen or -(CH2)n-cycloalkyl;\\n\\nR\\" is lower alkyl; R3 is NO2, CN or SO2R\';\\n\\nR4 is hydrogen, hydroxy, halogen, NO2, lower alkyl, lower\\n\\nalkyl, substituted by halogen, lower alkoxy, SO2R\' or C(O)OR\\";\\n\\nR5/R6/R7 are hydrogen, halogen, lower alkyl\\n\\nor lower alkyl, substituted by halogen; X1/X1\\u00bf\\n\\nare CH or N, with the proviso that X1/X1\\u00bf are not simultaneously\\n\\nCH; X2 is O, S, NH or N(lower alkyl); n is 0, l or 2; and to pharmaceutically\\n\\nactive acid addition salts and to their use in the treatment of neurological and\\n\\nneuropsychiatric disorders.
")  UPSERT WHERE primary_id = 676'
>>> client.batch(ab)

I get the following errors:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/shaungupta/anaconda/lib/python2.7/site-packages/pyorient/orient.py", line 402, in batch
.prepare(( QUERY_SCRIPT, ) + args).send().fetch_response()
  File "/Users/shaungupta/anaconda/lib/python2.7/site-packages/pyorient/messages/commands.py", line 145, in fetch_response
    super( CommandMessage, self ).fetch_response()
  File "/Users/shaungupta/anaconda/lib/python2.7/site-packages/pyorient/messages/base.py", line 256, in fetch_response
self._decode_all()
  File "/Users/shaungupta/anaconda/lib/python2.7/site-packages/pyorient/messages/base.py", line 240, in _decode_all

 self._decode_header()
  File "/Users/shaungupta/anaconda/lib/python2.7/site-packages/pyorient/messages/base.py", line 192, in _decode_header
    [ exception_message.decode( 'utf8' ) ]
pyorient.exceptions.PyOrientCommandException: com.orientechnologies.orient.core.sql.parser.TokenMgrError - Lexical error at line 1, column 311.  Encountered: <EOF> after : "\"
The present invention relates to compounds of the general formula (I) wherein\\n\\nR1 is the group (A) or (B) or (C) or (D); R2 is a non aromatic\\n\\nheterocycle, or is OR\' or N(R\\\")2"

If I run this using command I also get errors:
>>> client.command(ab)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/shaungupta/anaconda/lib/python2.7/site-packages/pyorient/orient.py", line 398, in command
    .prepare(( QUERY_CMD, ) + args).send().fetch_response()
  File "/Users/shaungupta/anaconda/lib/python2.7/site-packages/pyorient/messages/commands.py", line 145, in fetch_response
    super( CommandMessage, self ).fetch_response()
  File "/Users/shaungupta/anaconda/lib/python2.7/site-packages/pyorient/messages/base.py", line 256, in fetch_response
    self._decode_all()
  File "/Users/shaungupta/anaconda/lib/python2.7/site-packages/pyorient/messages/base.py", line 240, in _decode_all
    self._decode_header()
  File "/Users/shaungupta/anaconda/lib/python2.7/site-packages/pyorient/messages/base.py", line 192, in _decode_header
    [ exception_message.decode( 'utf8' ) ]
pyorient.exceptions.PyOrientCommandException: com.orientechnologies.orient.core.sql.OCommandSQLParsingExceptioncom.orientechnologies.orient.core.exception.OSerializationException - Error on parsing command at position #0: Error on reading parameters in: set(original_abstract, "
The present invention relates to compounds of the general formula (I) wherein

R1 is the group (A) or (B) or (C) or (D); R2 is a non aromatic

heterocycle, or is OR' or N(R")2; R' is lower alkyl,

lower alkyl substituted by halogen or -(CH2)n-cycloalkyl;

R" is lower alkyl; R3 is NO2, CN or SO2R';

R4 is hydrogen, hydroxy, halogen, NO2, lower alkyl, lower

alkyl, substituted by halogen, lower alkoxy, SO2R' or C(O)OR";

R5/R6/R7 are hydrogen, halogen, lower alkyl

or lower alkyl, substituted by halogen; X1/X1¿

are CH or N, with the proviso that X1/X1¿ are not simultaneously

CH; X2 is O, S, NH or N(lower alkyl); n is 0, l or 2; and to pharmaceutically

active acid addition salts and to their use in the treatment of neurological and

neuropsychiatric disordersFound invalid ) character at position 229 of text original_abstract, "
The present invention relates to compounds of the general formula (I) wherein

R1 is the group (A) or (B) or (C) or (D); R2 is a non aromatic

heterocycle, or is OR' or N(R")2. Ensure it is opened and closed correctly.

I have found however that if I do not add the information under original_abstract as a set, it works when using command:
>>> aba = 'UPDATE Patent SET  primary_id = 676, original_abstract = "
The present invention relates to compounds of the general formula (I) wherein\\n\\nR1 is the group (A) or (B) or (C) or (D); R2 is a non aromatic\\n\\nheterocycle, or is OR\' or N(R\\")2; R\' is lower alkyl,\\n\\nlower alkyl substituted by halogen or -(CH2)n-cycloalkyl;\\n\\nR\\" is lower alkyl; R3 is NO2, CN or SO2R\';\\n\\nR4 is hydrogen, hydroxy, halogen, NO2, lower alkyl, lower\\n\\nalkyl, substituted by halogen, lower alkoxy, SO2R\' or C(O)OR\\";\\n\\nR5/R6/R7 are hydrogen, halogen, lower alkyl\\n\\nor lower alkyl, substituted by halogen; X1/X1\\u00bf\\n\\nare CH or N, with the proviso that X1/X1\\u00bf are not simultaneously\\n\\nCH; X2 is O, S, NH or N(lower alkyl); n is 0, l or 2; and to pharmaceutically\\n\\nactive acid addition salts and to their use in the treatment of neurological and\\n\\nneuropsychiatric disorders.
"  UPSERT WHERE primary_id = 676'
>>> client.command(aba)
['1']

However client.batch still cannot handle this correctly:
>>> client.batch(aba)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/Users/shaungupta/anaconda/lib/python2.7/site-packages/pyorient/orient.py", line 402, in batch
    .prepare(( QUERY_SCRIPT, ) + args).send().fetch_response()
  File "/Users/shaungupta/anaconda/lib/python2.7/site-packages/pyorient/messages/commands.py", line 145, in fetch_response
    super( CommandMessage, self ).fetch_response()
  File "/Users/shaungupta/anaconda/lib/python2.7/site-packages/pyorient/messages/base.py", line 256, in fetch_response
    self._decode_all()
  File "/Users/shaungupta/anaconda/lib/python2.7/site-packages/pyorient/messages/base.py", line 240, in _decode_all
    self._decode_header()
  File "/Users/shaungupta/anaconda/lib/python2.7/site-packages/pyorient/messages/base.py", line 192, in _decode_header
    [ exception_message.decode( 'utf8' ) ]
pyorient.exceptions.PyOrientCommandException: com.orientechnologies.orient.core.exception.OSerializationException - Found invalid ) character at position 274 of text UPDATE Patent SET  primary_id = 676, original_abstract = "
The present invention relates to compounds of the general formula (I) wherein\n\nR1 is the group (A) or (B) or (C) or (D); R2 is a non aromatic\n\nheterocycle, or is OR' or N(R\")2; R' is lower alkyl,\n\nlower alkyl substituted by halogen or -(CH2)n-cycloalkyl;\n\nR\" is lower alkyl; R3 is NO2, CN or SO2R';\n\nR4 is hydrogen, hydroxy, halogen, NO2, lower alkyl, lower\n\nalkyl, substituted by halogen, lower alkoxy, SO2R' or C(O)OR\";\n\nR5/R6/R7 are hydrogen, halogen, lower alkyl\n\nor lower alkyl, substituted by halogen; X1/X1\u00bf\n\nare CH or N, with the proviso that X1/X1\u00bf are not simultaneously\n\nCH; X2 is O, S, NH or N(lower alkyl); n is 0, l or 2; and to pharmaceutically\n\nactive acid addition salts and to their use in the treatment of neurological and\n\nneuropsychiatric disorders.
"  UPSERT WHERE primary_id = 676. Ensure it is opened and closed correctly.

Running string ab directly in the orientdb console also gives the same errors, however running string aba in the orientdb console works fine, so I cannot understand why aba does not work with the pyorient batch command (I also have managed to run aba in the orientdb console as part of a begin/commit transaction with success).
Does anybody understand why this command works via client.command and not client.batch? I need to have this command running as part of a batch of commands, so need to find a fix..... Ideally, I would like to have the command in string ab where I am adding original abstract as a set to work, as I need to keep track of any new information for matching nodes.
From what I can see this is a parsing limitation of the command executor, but please do tell me if I am doing something wrong here...
Thanks!!

A: The first error shows you have End of File (EOF) character in your command which might not be visible, It is common if it is copied from somewhere else.


text:
Q: 301 redirect from www.example.com to http://example.com in apache htaccess
Possible Duplicate:
how to redirect www.example.com to example.com via htaccess while on zend framework

I want to redirect
www.example.com to example.com

Can any body help me, How can do that using htaccess.

A: This should do it;
RewriteEngine On
RewriteCond %{HTTP_HOST} ^www\.example\.com$
RewriteRule (.*) http://example.com/$1 [R=301,L]


text:
Q: Unable to use a single form to collect data for two models in yii2 I am trying to use a single form to collect information for two models (Staffmodel and Garantormodel) sharing the same relationship in yii2 basic, but I keep receiving the error

Call to undefined method app\models\StaffGarantor::find()

when the form is submitted.
My code is below.
//custom model called StaffGarantor

<?php

namespace app\models;

use app\models\Staff;
use app\models\Garantor;
use yii\db\ActiveQuery;
use base\InvalidConfigException;

/**
 * Description of RegisterStudent
 *
 */
class StaffGarantor extends \yii\base\Model {
//class StaffGarantor extends \yii\db\ActiveRecord{
    //put your code here

//Staff Property
    public  $Fname;
    public  $mname;
    public  $others;
    public  $dob;
    public  $Gender;
    public  $state_of_origin;
    public  $lga_of_origin;
    public  $p_address;
    public  $c_address;
    public  $mobile;
    public  $qualification;
    public  $passport;
    public  $staff_id;
    public  $created_by;
    public  $date_created;

    public  $vErrors; //Error reporting

//Garantor property
    public  $first_name;
    public  $others_name;
    public  $g_dob;
    public  $g_gender;
    public  $state_origin;
    public  $lga_origin;
    public  $permenent_address;
    public  $con_address;
    public  $email;
    public  $home_line;
    public  $phone;
    public  $occupation;
    public  $employee_name;
    public  $employee_address;
    public  $photo;
    public  $relationship;

     public function rules(){

       return[
            [['Fname', 'mname', 'others', 'dob', 'Gender',
'state_of_origin', 'lga_of_origin', 'c_address', 'mobile', 'qualification',
'staff_id', 'created_by', 'date_created'], 'required'],
            [['Fname', 'mname', 'others'], 'string', 'max' => 30],
            [['dob'], 'string', 'max' => 11],
            [['Gender'], 'string', 'max' => 10],
            [['state_of_origin', 'lga_of_origin','created_by'], 'string', 'max' => 50],
            [['p_address', 'c_address'], 'string', 'max' => 100],
            [['mobile'], 'string', 'max' => 13],
            [['qualification', 'staff_id'], 'string', 'max' => 20],
            [['passport'], 'file', 'extensions' => ['png','jpg','jpeg'],
'maxSize' => 500 * 1024,
                'message' => 'Passoport cannot be more than 500KB.'],
            [['staff_id'], 'unique', 'targetClass' => Staff::className(),
'targetAttribute' => 'staff_id'],
            [['date_created'], 'string', 'max' => 15],
            [['date_created'],'date','format'=>'yyyy-mm-dd'],
            [['g_dob'],'date','format'=>'yyyy-mm-dd'],
            [['staff_id'], 'unique'],
           //Garantor Info
            [['first_name', 'others_name', 'g_dob', 'g_gender',
'state_origin', 'lga_origin', 'permenent_address', 'con_address', 'phone',
'occupation', 'photo','relationship'], 'required'],
            [['first_name', 'others_name', 'state_origin', 'lga_origin'],
'string', 'max' => 50],
            [['g_dob'], 'string', 'max' => 13],
            [['g_gender'], 'string', 'max' => 20],
            [['permenent_address', 'con_address', 'email', 'employee_name',
'employee_address'], 'string', 'max' => 100],
            [['home_line', 'phone'], 'string', 'max' => 15],
//           [['id','exist']],
            [['g_dob'],'date','format'=>'yyyy-mm-dd'],
            [['occupation', 'relationship'], 'string', 'max' => 30],
            [['photo'], 'file', 'extensions' => ['png','jpg','jpeg'],
'maxSize' => 500 * 1024,
                'message' => 'Passoport cannot be more than 500KB.'],
           [['staff_id'], 'exist', 'skipOnError' => true, 'targetClass' =>
Staff::className(), 'targetAttribute' => ['staff_id' => 'id']],
        ];
    }
    public function register()
    {
        if (!$this->validate()){

            $this->vErrors = $this->errors;
            return  $this;
        }

        $staff = new Staff();

        $staff->Fname                  = $this->Fname;
        $staff->mname                  = $this->mname;
        $staff->others                 = $this->others;
        $staff->dob                    = $this->dob;
        $staff->Gender                 = $this->Gender;
        $staff->state_of_origin        = $this->state_of_origin;
        $staff->lga_of_origin          = $this->lga_of_origin;
        $staff->p_address              = $this->p_address;
        $staff->c_address              = $this->c_address;
        $staff->mobile                 = $this->mobile;
        $staff->passport               = $this->passport;
        $staff->qualification          = $this->qualification;
        $staff->staff_id               = $this->staff_id;
        $staff->created_by             = $this->created_by;
        $staff->date_created           = $this->date_created;
         $staff->passport       =  $staff->myUploader($this->passport);

        $staff->generateAuthKey();

        if ($staff->validate()){

            $garantor    = new Garantor();
        $garantor->first_name                  = $this->first_name;
        $garantor->others_name                      = $this->gothers_name;
        $garantor->g_dob                         = $this->g_dob;
        $garantor->g_gender                      = $this->g_gender;
        $garantor->state_origin                = $this->state_origin;
        $garantor->lga_origin                  = $this->lga_origin;
        $garantor->permenent_address           = $this->permenent_address;
        $garantor->con_address                 = $this->con_address;
        $garantor->home_line                   = $this->home_line;
        $garantor->phone                       = $this->phone;
        $garantor->email                       = $this->email;
        $garantor->occupation                  = $this->occupation;
        $garantor->employee_name               = $this->employee_name;
        $garantor->employee_address            = $this->employee_address;
        $garantor->photo                       = $this->photo;
        $garantor->relationship                = $this->relationship;
        $garantor->date_created                = $this->date_created;
        $garantor->created_by                  = $this->created_by;

        $garantor->photo       =  $garantor->myUploader($this->photo);

        if ($garantor->validate()){
                    $this->vErrors = $garantor->errors;
                    return  $this;
                }else {
                    $staff->save();
                    $garantor->staff_id    =   $staff->id;
                    $garantor->save();
                    return $staff;
                }
             }else{
//            echo '
'; var_dump($member);echo '
';die();

            $this->vErrors = $staff->errors;
            return  $this;
        }

    }//End Register method
} // End Class

//Action rendering form in the staffcontroller
public function actionRegister()
    {
      $model = new StaffGarantor();

        if ($model->load(Yii::$app->request->post())) {

            $model->passport = UploadedFile::getInstance($model, 'photo');
            $model->photo = UploadedFile::getInstance($model, 'photo');
            $model = $model->register();

            if(!$model->vErrors){

                return $this->redirect(['view', 'id' => $model->id]);

            }else{
                return $this->render('add', [
                    'model' => $model,
                ]);
            }

        } else {
            return $this->render('add', [
                'model' => $model,
            ]);
        }
    }

//custom form collecting data
<?php
use yii\helpers\Html;
use yii\widgets\ActiveForm;
use app\models\Staff;
use app\models\Garantor;
use yii\helpers\ArrayHelper;
use kartik\widgets\DatePicker;
use kartik\file\FileInput;
?>

       <?php $form = ActiveForm::begin(); ?>

Enter Staff's Personal Details.

            <?= $form->field($model, 'staff_id')->label('Staff ID No') ?>
            <?= $form->field($model, 'Fname') ?>
            <?= $form->field($model, 'mname') ?>
            <?= $form->field($model, 'others') ?>
            <?= $form->field($model, 'dob') ?>
            <?= $form->field($model, 'Gender')-
>dropDownList(['Male'=>'Male', 'Female'=>'Female'],
                    ['prompt'=>'-Please, select Gender']) ?>
            <?= $form->field($model, 'state_of_origin') ?>
            <?= $form->field($model, 'lga_of_origin') ?>
            <?= $form->field($model, 'p_address') ?>
            <?= $form->field($model, 'c_address') ?>
            <?= $form->field($model, 'mobile') ?>
            <?= $form->field($model, 'qualification') ?>
            <?= $form->field($model, 'created_by') ?>
            <?= $form->field($model, 'date_created') ?>

            <?= $form->field($model, 'passport')->fileInput()->label('Add a
passport photograph
')?>

Staff's Guarantors Details

            <?= $form->field($model, 'first_name') ?>
            <?= $form->field($model, 'others_name') ?>
            <?= $form->field($model, 'g_dob') ?>
            <?= $form->field($model, 'g_gender') ?>
            <?= $form->field($model, 'state_origin') ?>
            <?= $form->field($model, 'lga_origin') ?>
            <?= $form->field($model, 'permenent_address') ?>
            <?= $form->field($model, 'con_address') ?>
            <?= $form->field($model, 'home_line') ?>
            <?= $form->field($model, 'phone') ?>
            <?= $form->field($model, 'email') ?>
            <?= $form->field($model, 'occupation') ?>
            <?= $form->field($model, 'employee_name') ?>
            <?= $form->field($model, 'employee_address') ?>
            <?= $form->field($model, 'relationship') ?>

             <?= $form->field($model, 'photo')->fileInput()->label('Add a
passport photograph
')?>

            <?= Html::submitButton(Yii::t('app', 'Submit'), ['class' => 'btn
btn-primary']) ?>

    <?php ActiveForm::end(); ?>

//the actual StaffModel
<?php

namespace app\models;

use Yii;
use app\models\Garantor;

/**
 * This is the model class for table "staff".
 *
 * @property integer $id
 * @property string $Fname
 * @property string $mname
 * @property string $others
 * @property string $dob
 * @property string $Gender
 * @property string $state_of_origin
 * @property string $lga_of_origin
 * @property string $p_address
 * @property string $c_address
 * @property string $mobile
 * @property string $qualification
 * @property string $passport
 * @property string $staff_id
 * @property string $created_by
 * @property string $date_created
 *
 * @property Garantor[] $garantors
 */
class Staff extends \yii\db\ActiveRecord implements
\yii\web\IdentityInterface
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'staff';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['Fname', 'mname', 'others', 'dob', 'Gender',
'state_of_origin', 'lga_of_origin', 'c_address', 'mobile', 'qualification',
'staff_id', 'created_by', 'date_created'], 'required'],
            [['Fname', 'mname', 'others'], 'string', 'max' => 30],
            [['dob'], 'string', 'max' => 11],
            [['Gender'], 'string', 'max' => 10],
            [['state_of_origin', 'lga_of_origin', 'passport', 'created_by'],
'string', 'max' => 50],
            [['p_address', 'c_address'], 'string', 'max' => 100],
            [['mobile'], 'string', 'max' => 13],
            [['qualification', 'staff_id'], 'string', 'max' => 20],
            [['date_created'], 'string', 'max' => 15],
            [['staff_id'], 'unique'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'Fname' => 'Fname',
            'mname' => 'Mname',
            'others' => 'Others',
            'dob' => 'Dob',
            'Gender' => 'Gender',
            'state_of_origin' => 'State Of Origin',
            'lga_of_origin' => 'Lga Of Origin',
            'p_address' => 'P Address',
            'c_address' => 'C Address',
            'mobile' => 'Mobile',
            'qualification' => 'Qualification',
            'passport' => 'Passport',
            'staff_id' => 'Staff ID',
            'created_by' => 'Created By',
            'date_created' => 'Date Created',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
     public function getId()
    {
        return $this->getPrimaryKey();
    }

    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }

    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }

    public static function findIdentity($id) {

    }

     public static function findIdentityByAccessToken($token, $type = null)
{

    }

    public function getGarantors()
    {
        return $this->hasMany(Garantor::className(), ['staff_id' => 'id']);
    }
// Student Picture Uploader
     public function myUploader($file){

        if($file){

            $tempName = Yii::$app->security-
>generateRandomString().time().'.'.$file->extension;

            $file->saveAs('uploads/'.$tempName);

            return $tempName;
        }else{
            return "No passport photographe";
        }
    }

     // Parents or Gaurdian Picture Uploader
     public function pUploader($pfile){

        if($pfile){

            $ptempName = Yii::$app->security-
>generateRandomString().time().'.'.$pfile->extension;

            $pfile->saveAs('uploads/'.$ptempName);

            return $ptempName;
        }else{
            return "No passport photographe";
        }
      }

    }

A: your StaffGarantor class extends from yii\base\Model. To use the ActiveRecord method find() your class will need to extend yii\db\ActiveRecord.
class StaffGarantor extends \yii\db\ActiveRecord {}

A: I suggest you to not make a separate model for collecting data for two models.
You can use two models in one  active form


text:
Q: How do I use SCP with two different ports on each IP in script bash How do I use scp with two different ports on each IP.
SSH LOCAL : IP=111.111.111.111 & port=22

I have a redirection ports on a router
EXAMPLE SCRIPT BASH:
for i in "${array[@]}"

array[1]=192.168.20.159
array[2]="192.168.20.159 -p 24"

scp /home/innobing/video/$video pi@$i:/home/pi/video/$video.new

RESULT IN ARRAY [2]:
ssh: connect to host 24 port 22: Invalid argument
lost connection

There is a solution?

A: You do not have to mention a source port, it will be a auto-generated (>=1024).
Also to mention a custom port number use -P option, -p is to preserve metadata.
Do:
scp -P 24 /home/aa/video/a.mp4 user@222.222.222.222:/home/aa/video/a.mp4.new

A: scp -P 24 /home/aa/video/a.mp4 user@222.222.222.222:/home/aa/video/a.mp4.new
The "P" is upper case. You don't need to worry about the "local port", scp can access the filesystem directly, it doesn't need the network for it.


text:
Q: change height and width of dropped element dynamically I have created a drag n drop file in which the user will enter the coordinates like 3*4 when the dropped element is clicked, using scalar factor I get height and width for the element. I want to change the height and width of the dropped element. Can anyone help?
 $(document).ready(function () {

  var x = null;

  // Make element draggable
  $(".drag").draggable({
    helper: 'clone',
    cursor: 'move',
    tolerance: 'fit'
  });

  var i = 1, j = 0;
  var x1, x2, y1, y2, tmp, tmp2;
  var sf = pf;

  $("#droppable").droppable({

    drop: function(e, ui) {

      var attr = ui.helper.attr('id');
      if (typeof attr == typeof undefined || attr == false) {
        ui.helper.attr('id',"id"+i);
      }
      tmp = ui.helper.attr('id');
      x = ui.helper.clone().bind("click",'img',function(){

        alert("clicked"+ ui.helper.attr('id') + tmp);
        leftpos = ui.offset.left-210;
        toppos = ui.offset.top;
        var cor = window.prompt("Enter coordinates x1,y1");
        var c = cor.split(',');
        var w = c[0]*sf;
        var h = c[1]*sf;
        w = w/2;
        h = h/2;
        ui.helper.width(leftpos-w);
        ui.helper.height(toppos-h);
      });

      x.draggable({
        helper: 'original',
        containment: '#droppable',
        tolerance: 'fit',
      });

      x.appendTo('#droppable');
      ui.helper.remove();
      i++;
    }
  });
});

A: There are couple of things which are missing in your code.

*

*The click event handler is a closure , which means it would have access to ui.helper even though the event handler function is executed outside its defined scope. but to change the width and height, you need to refer to the current event bounded object via this keyword.

*variable pf is undefined, so I have defined one local variable with the same name.

*With your current logic, the target dropped item looks odd, so I have set the static value of 300 for width and height in below jsfiddle.

JS CODE:
x= ui.helper.clone().bind("click", 'img', function() {
    //leftpos = ui.helper.offset.left - 210;
    //toppos = ui.helper.offset.top;
    leftpos = ($(this).offset().left) - 210;
    toppos = ($(this).offset().top);
    ...

    //ui.helper.width(leftpos-w);
    //ui.helper.height(toppos-h);
    $(this).width(300);
    $(this).height(300);

Live Demo @ JSFiddle


text:
Q: How to use multiple themes for multiple matplotlib imports I am importing multiple matplotlib as names within my python program and would like to use different styles for different plots.
However when i change the style for one plot (say : dark_background) it changes the style for all other plots as well.
suggestions shall be appreciated
Current import is something like this :
import matplotlib.pyplot as plt_surfacegt
import matplotlib.pyplot as plt_mascon
import matplotlib.pyplot as plt_gravmod
import matplotlib.pyplot as plt_realtime
plt_realtime.style.use('dark_background')

it should only change the theme for  plt_realtime to dark however all others are changed to dark as well.!

A: I cannot exactly explain why this wouldn't work, but it seems to me a crazy idea to achieve your desired result.
Instead, I think you should use matplotlib's context manager to change the style sheet on a per-plot basis. Something like (from the link):
with plt.style.context('dark_background'):
    plt.plot(np.sin(np.linspace(0, 2 * np.pi)), 'r-o')
plt.show()


text:
Q: PHP Pass by Reference Issue So I am having a strange issue where the functions are NOT defined by pass by reference parameters, yet objects are being changed in ways that I cannot explain.  I have verified function definitions are not pass by reference time and time again.  I have retrieved an object from the DB.  Then I have run an analysis function on that initial object.  I have copied the object to another variable.  Then I run a different analysis function on the copy and not the original.  Running the second analysis function seems to alter the first variable-object. Any ideas on what might be going on here. I have been trying to debug this for hours upon hours and I cannot explain this behavior.  I would prefer not to post the the actual functions as they are proprietary information, however, I can possibly send them privately for some help.   I thank you kindly for your time in trying to help me.
//get object from db
$resp= json_decode($ln->getResponseFromDb($resultid));

//run pwf analysis function
$resp = $ln->pwfBGCheck($resp);

//show result after pwf
print_r($resp->pwf);

/* shows
* stdClass Object ( [status] => p [reason] => Person has no c record. )
*/

//copy to another variable
$r2 = $resp;
//run pwf for s record other variable so it is not touching the first one!
$r2 = $ln->pwfBGCheckSexOffender2($r2);
echo '
this is first variable
';
print_r($resp->pwf);
/* copies from second to first for some reason... no pass by reference on this call...       resp variable has not been touched!
* stdClass Object ( [status] => p [reason] => Person has no s record. )
*/
echo '
this is second
';
print_r($r2->pwf);
/* returns
* stdClass Object ( [status] => p [reason] => Person has no s record. )
*/

A: Since PHP5 object always pass by reference. If you want to get copy of object you have to use clone.
Objects and references

An exception to the usual assignment by value behaviour within PHP occurs with objects, which are assigned by reference in PHP 5. Objects may be explicitly copied via the clone keyword.

Assignment Operators

A: Also you could use json_decode($json, true); (instead of json_decode($json);) to get assoc array (instead of stdClass).
And there would not any issues with references.

A: after going crazy forever...
I found this solution:
$r2 = unserialize(serialize($resp));

I know it is not ideal as there is a performance hit, but I am under a deadline and needed to create a working solution as soon as possible.  I believe that issue remained because even the variables that are being copied are also passed by reference. I am willing to accept another working solution if someone comes up with a better alternative.  Thank you!
also... due to some other issues with serialization (libxml cannot be serialized), this solution didn't work...
but then I thought of
$r2 = json_decode(json_encode($resp));

and this actually did the trick!


text:
Q: Pushing random variables into array PHP
*

*I declare an array called $stack

*I make an if statement that checks if the button in my html body fired.

*Once it is fired, I try to push a random value (via mt_rand) in my $stack array.

*I print my array to see what values are in there.

With the variable y I try to increase the amount of times the for loop will run and thus there should be more values pushed into the array. This, however does not happen. Why doesn't his happen? I had the feeling that when I push the button, the page is refreshed and my $y variable is 0 once again. Is this correct?
I hope you can help me.
<html>
<head>
<?php

    $stack = array();
    if( isset($_POST['dobbelTrig'])){
        $y=0;
        $y++;

            for($x = 0; $x < $y; $x++){
                $newvalue = mt_rand(1,6);
                $stack[] = $newvalue;
            }

        print_r($stack);
    }
?>
</head>
<body>

<p>
    <form method="post" action="">
        <input type="submit" value="dobbelen" name="dobbelTrig">
    </form>
 </p>

</body>
</html>

A: First you set $y to 1

$y=0;
$y++;

Then you loop between 0 and $y:

for($x = 0; $x < $y; $x++){

So 0 is less than 1, so you add a value to the array.
Then 1 is not less than 1, so you stop.
At this point you have one value in the array.

When you click submit again, the program runs from the beginning. It creates a new array and puts one value in it.
If you want to persist data between form submissions then you need to store the results somewhere persistent (such as in a session, a database, or embedded in hidden input elements in the form).

A: Look here:
$y=0; // Y is 0
$y++; // Y is now 1
for($x = 0; $x < $y; $x++){ //So X is zero, when $x++ it is no longer < $y


text:
Q: How can I stop my other DIVs from moving when I expand on hover My other DIVs keep moving when one of my DIVs expand on hover

#entertainment
{
 width:49%;
 height: 49%;
 display: grid;
 grid-template-columns: auto auto auto;
 grid-gap: 10%;
 border: 1px solid red;
 float: left;
}

#circle
{
 position: relative;
 overflow: auto;
  width: 80%;
 padding-top: 80%;
 border-radius: 50%;
 background: white;
  background-repeat: no-repeat;
  background-position: center;
  background-size: 100%;
 box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2), 0 6px 20px 0 rgba(0, 0, 0, 0.19);
 transform:translate(-5%, 0);
transition: all 0.5s ease;

align-self: center;
  justify-self: center;
}

#circle:hover
{
 width: 100%;
 padding-top: 100%;

}

The other Divs keep moving when I hover over one and there is no padding pushing them. It seems like there is an object pushing the other divs as I expand and I am very confused as to what is doing it.
Please help as I need to finish this, thanks

A: Instead of changing the width on :hover, change the size with transform: scale(1.25). The value in the scale() function can be whatever you want (1 equals 100% or full size).
When changing the size using transform, the other elements should maintain their position in the layout.


text:
Q: Cannot create a new database in Sql Server - changed username I installed Sql Server on a server in a company I used to work for.
I left the company - and rejoined a year later - and now I have a different domain login.
I've logged on to the server again, and in SSMS tried to create a new database - however I get the error:

create database permission denied in database 'master'

I have tried changing permission and adding DBCreator to BuiltInUsers and to SA - and also tried adding my new domain name to the security section - but when I try to add DBCreator to my user name, I get the error:

Cannot alter the server role 'dbcreator' because it does not exist or you do not have permission

Is there any way I can take control of the Sql Server instance again, to allow me to create new databases?
Thanks for any help,
Mark

A: I faced this problem when I made another SQL user which I login with, and I tried to give this user [dbcreator] grant.
I solved this via

*

*runnig sql server as administrator

*switching to my windows authentication.

*going to folder Security -> Logins and double click on my new sql login user.

*selecting Server roles and give grant to my user.


text:
Q: When Kan extensions don't exist Kan extension are an incredibly useful concept when they exist. My question is: can we still derive information about a functor when Kan extensions don't exist, and if so, what information and in what way?
I can think of one way to look at it:
Let $p:C\to C'$ and $F:C\to D$ be functors.  We can define a category of pairs $(G:C'\to D, \eta: F\Rightarrow p^*G)$ with morphisms being natural transformations that commute with the $\eta$s.
A left Kan extension of $F$ along $p$ is an initial object in this category, so one can study this category as a replacement when the Kan extension fail to exist.
Has this direction been explored before?

A: Yes, directions like this have been explored, for all kinds of objects with universal properties (which includes Kan extensions, since as MacLane famously wrote "all concepts are Kan extensions").  Rather than the category whose initial object would be the missing object, it's more common to consider the functor for which a representation would be the missing object.  Properties of this functor can then be considered as properties of the "missing object", and at the extreme the category of all functors/presheaves (or a subcategory such as a category of sheaves, concrete sheaves, schemes, etc.) can be studied as a "better-behaved" replacement for the original category in which "missing objects" have been put in.
As one concrete example, a non-existing left adjoint can exist as a pro-adjoint; in fact it does so precisely when the putative right adjoint preserves finite limits (whereas, modulo size considerations, for an actual left adjoint to exist, the putative right adjoint would have to preserve all limits).

A: There are several points worth making here.
(i) One solution is to use Benabou's theory of 'distributeurs' also called profunctors. A functor F from C to D defines two profunctors basically $D(F-,-):C^{op}\times D\to Sets$ and $D(-,F-): D^{op}\times C\to Sets$. The profunctors from C to D form a bicategory. Any functor considered as a profunctor has an adjoint profunctor (I leave it up to the reader to work this out.) The n-Lab page on profunctors gives several suitable references, and a basic introduction. The Kan extensions question is then solvable as the 'existence' is a question of representability. i.e., you get a profunctor as the Kan extension but do not know if it has a representing object /  functor etc. (Some of that is described in my book (with Jean-Marc Cordier) on Shape Theory: Categorical Methods of Approximation, (Published by Dover). PS. I do not get any royalties from the sales of that book so this is not really self promotion!)
This theory also works in an enriched category setting, and in a derived form (suitably adapted).
(ii) It is worth pointing out that in many contexts you can study the properties of a Kan extension object even if the object does not exist in the category you would like it to be in. This just extends the use by Grothendieck etc. of functors that encode something useful but may not be representable. (You may have some setting in which, say, a moduli space does not exist but there is a functor that behaves as if it was maps from that non-existent object to whatever. You may be able to determine the cohomology of the non-existent moduli space! Alternatively you can enlarge the category of `spaces' so as to think of the functor as being representable but in that larger category. This led to Artin's algebraic spaces and further on to the study of stacks, etc.)
(iii) Another instance of the same sort of thing is with the use pro-objects. I will illustrate this with adjoints rather than with  more general Kan extensions. The inclusion of, for instance, the category of finite groups into that of all groups does not have a left adjoint, but it does have a pro-adjoint which send a group to its filtering system of finite quotients.  Using this sort of idea one can quite often get a pro-version of Kan extensions. (There are several instances of this in quite classical algebraic topology and algebra; again my book with Cordier looks at some of that. I only mention it because I know its contents, and not because those examples are the only important ones. There are many other uses for these ideas.)
For the Kan extensions the idea is that you go via the comma category approach, giving a functor to one of the categories concerned,  and of which you would normally take a limit or colimit. However the limit might not exist.  If the comma category is `filtering' then the resulting functor gives a pro-object that replaces the hoped for Kan extension by an inverse system of objects that give approximations to the Kan extension.
(Above I have used adjoints as examples rather than Kan extensions in the above, as they provide easier instances of the main ideas.)


text:
Q: Alert message before before performing button_clicking event in C#.NET I am creating an data driven application in C#.NET. In this application when user click on load button, data from csv file will be loaded in data grid view.
Further, there is save button to insert data from data grid view into database. I am trying to insert alert message at time of inserting data into database.
eg) user click on save button then it should show him message like do yow want to save data or not and if it click on ok data should be inserted into database and if he press cancel it should stop.
I am using this code, I don't whether it is proper or not before save button clicking event.
MessageBox.Show("Do You Want To Save Data!", "Alert", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);

Can any provide me with proper solution.
Thanks,
Rushabh Shah.

A: if (MessageBox.Show("Do You Want To Save Data!", "Alert", MessageBoxButtons.OKCancel,
    MessageBoxIcon.Error) == DialogResult.OK))
   SaveDataHere();


text:
Q: Facebook button open in safari rather than app I have a Facebook button in my app which is linked to my Facebook page however it open up in safari rather than the Facebook app. I have also linked twitter that opens up in the app first and not safari which is how i want it. My code for both buttons is the same so i don't understand why it is behaving this way?
   @IBAction func openFB(sender: AnyObject) {

    if UIApplication.sharedApplication().canOpenURL(NSURL(string: "fb://profile/XXXXXXXXX")!) {
  UIApplication.sharedApplication().openURL(NSURL(string: "fb://profile/XXXXXXXXX")!)
} else {
  UIApplication.sharedApplication().openURL(NSURL(string: "https://facebook.com/XXXXXXXX")!)
}
 }

@IBAction func openTW(sender: AnyObject) {

if UIApplication.sharedApplication().canOpenURL(NSURL(string: "tw://profile/XXXXXXX")!) {
  UIApplication.sharedApplication().openURL(NSURL(string: "fb://profile/XXXXXXXX")!)
} else {
  UIApplication.sharedApplication().openURL(NSURL(string: "https://twitter.com/XXXXXXXXXX")!)
}
}

A: yes this is happening after iOS 9. you will find how to resolve this by following this answer
Hope this will help.