Spring Rest Respository Collection name case sensitivity

Question: I am using Spring Boot and MongoDB, and am trying to expose them over REST using Spring Rest Repositories.
I have a Mongo collection called user and the Java domain model class called User. My Rest Repository looks like this:
@RepositoryRestResource(  collectionResourceRel = "users", path = "users")
public interface UserRepository extends MongoRepository<User, String> {

    public User findByEmail(@Param("email") String email);

}

With this in place, I get the advertised benefits of the resource getting automatically exposed over REST. GET, PUT, POST all that jazz.
What I find though is that when I rename the Mongo collection to User, it doesn't find records on the /users endpoint. It is almost as if Spring REST Repositories assumes that the collection name will be in lowercase (yes, I did come across the documentation here - https://docs.spring.io/spring-data/rest/docs/current-SNAPSHOT/reference/html/)

Spring Data REST exposes a collection resource named after the uncapitalized, pluralized version of the domain class the exported repository is handling. Both the name of the resource and the path can be customized using the @RepositoryRestResource on the repository interface.

What I am after is a way to get this configured so that I can use a collection name like User instead of user.
I have searched a fair bit, but haven't been able to come up with answers.
Any help much appreciated!
Cheers!
Comment: In much the same sentiment as the comment just added, instead of telling us *"I followed the guide"* show us exactly what you did by providing the necessary code/configuration within the question itself. It kind of sounds like your changed both the `collectionResourceRel` and the `path`, when you're only meant to change one of them. Not that I'm going to recommend starting a collection name with an uppercase character anyway, since that goes against common conventions.
Comment: Have you tried changing `collectionResourceRel = "users"` to `collectionResourceRel = "Users"` as the docs suggest?
Comment: @RandyCasburn Thanks for the quick reply. Yes, tried it but no luck! In fact, when the Mongo collection name is `users`, it works regardless of whether `collectionResourceRel` is `users` or `Users` :(
Comment: Thanks @NeilLunn, yes, I agree. Unfortunately, I don't have direct control on being able to change the case of the collection :( And no, I didn't change the `path`, just `collectionResourceRel`
Comment: You agree to what exactly? We are pretty much asking you to **show your code** instead of just repeating "did that" or "followed that". [Edit your question](https://stackoverflow.com/posts/53423947/edit) and show us exactly what you did.
Answer: I experienced the same problem,
In my case I have annotated the User class with @Document but I was missing to add the value :
@Document("User")

javadoc of value attribute:

The collection the document representing the entity is supposed to be
stored in. If not configured, a default collection name will be
derived from the type's name.

So by default if not configured, seems to use the Class name in lowerCamelCase.


Intersection of nested compact sets in a Hausdorff space

Question:
Suppose that a non-empty Hausdorff space $X$ is compact and there is a continuous map $f:X \to X$. Let $X_1=X$ and put $X_{n+1} = f(X_n)$ inductively for all $n \in \mathbb{N}$.
Prove that $A = \bigcap\limits_{n=1}^\infty X_n$ is non-empty.

Thoughts: Since $f$ is continuous, we have that $X_{n}$ is compact for all $n$. Furthermore, they are all closed because of $X$'s Hausdorffness.
In a normal metric space this would be easier, using the equivalence of compactness and sequential compactness, by constructing a sequence such that $a_n \in X_n$, and using the fact that it necessarily has a convergent subsequence with limit in the intersection.
Any hints would be really helpful.
Thanks!
Answer: Hint. Let $U_n := X \setminus X_n$. If we have $\bigcap_n X_n = \emptyset$, we would have $\bigcup_n U_n = X$ with open $U_n$. Now use compactness.
Comment: Then $X = \bigcap_{i=1}^n U_i = U_n$ (the $U_n$ are increasing). But $U_n = X$ gives $X_n = \emptyset$, which is wrong. (If $x \in X$, then $f^{n-1}(x) \in X_n$.
Comment: So $\mathcal{U} = \{U_i\}_{n \in \mathbb{N}}$ is an open cover of $X$, by compactness we can extract a finite cover $\{U_i\}_{i=1}^n$ of $X$, but then what?


How to order multiple values in a field collection

Question: I have an Content type which includes a field of type Field collection, of which there can be an unlimited number of values. I can't work out how to order the rows of data that are displayed by this field.
Answer: You can order the Items when you are creating it using the widget that is next to the field. I mean this (It is a field collection that contains multiple fields)

and if you need to sort the items after adding the content, you can use  Field Collection views module. This module creates a view of type field collection and by some configurations you can get what you want.
Comment: Thanks. It looks like Field Collection Views is what I need.
Comment: You welcome, If you think it is the correct solution for your question Please check as accepted for people who visit your question in the future


Envio de imagem com phpmailer

Question: Tenho um site que o fomulário precisa ser autenticado,estou usando a biblioteca phpmailer, até aí tudo bem eu consegui, no entanto esse formulário tem uma foto que deve ser enviada junto e não estou conseguindo fazer com que essa imagem chegue na caixa de entrada.
usei vários exemplos que ni na internet, como este $mail->addAttachment($_FILES['arquivo']); mas não funcionou :/
Comment: tente ser mais especifico qual errou apareceu ?
Comment: Apareceu este erro Fatal error: Call to a member function AddAttachment() on a non-object in /home/sindesep/public_html/teste1/enviar.php on line 29
Answer: Tente trocar para $mail->addAttachment($_FILES['arquivo']['tmp_name']).
Não sei ao certo como o método addAttachment funciona, mas acho que ele não foi preparado para ler a chave tmp_name sozinho.
Comment: eu ja usei esse código,  o email é enviado mas não chega a foto anexada

Envio de imagem com phpmailer


Tornado: Reset database before running all tests

Question: I am using Python Tornado web server. When I write test, before all tests, I want to do something (such as prepare some data, reset database ...). How can I achieve this in Python or Tornado web server.
In some languages I can easily do this. Example: in Golang, there is a file named main_test.go.
Thanks
Answer: If you use unittest.TestCase or tornado.testing.*TestCase (which actually are subclasses of unittest.TestCase), look at the setUp() and tearDown() methods. You can wrap everything you want just like
class MyTests(unittest.TestCase):

    def setUp(self):
        load_data_to_db()

    def test_smth(self):
        self.assertIsInstance("setUp and tearDown are useful", str)

    def tearDown(self):
        cleanup_db()

Answer: In your test folder, you create __init__.py and initialize everything here.
// __init__.py
reset_database()
run_migration()
seed_data()

Noted that, you should configure your project running test from root folder. For example, if your test inside app/tests/api/sample_api.py, your test should be run  from app. In this case, __init__.py will always run before running your sample_api.py. Here is the command line I usually run for running all tests inside project:
python -m unittest discover


Overflow: Hidden is croping the text and button in Header/ Banner

Question: Let me preface my question with this: I'm a total beginner.I'm really sorry for the long code snippets and code.
I'm trying to make this "Header"/ "Banner" (see code) show everything inside them but by using "overflow: hidden", elements inside the "Header"/ "Banner" get cropped out.
Example: If I try to move my Button outside of these parameters that I obviously have set (without me knowing) it gets cropped out. I want to have more space between the text lines and the button without it getting cropped.
I just don't know to make it all visible even if I change the position of the button, like in the example.
I am at a loss, I tried changing every variable possible. This is probably obvious but I just can't seem to make my idea work.

/* default margin and padding for all elements */
* {
    margin: 0;
    padding: 0;
    outline: none;
    box-sizing: border-box;
    list-style: none;
    text-decoration: none;
}

/* decrese font size of the HTML file */
html {
    font-size: 62.5%;
}

/* Creating & styling hamburger menu */
.hamburger-menu {
    width: 3rem;
    height: 3rem;
    position: fixed;
    top: 5rem;
    right: 3rem;
    z-index: 200;
    /* create lines for menu */
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    cursor: pointer;
}

.line {
    width: 100%;
    height: 0.2rem;
    background-color: #FFF;
    box-shadow: 0.1rem 0.2rem rgba(0, 0, 0, 0.2);
}

/* Costomize header */
.header {
    width: 100%;
    height: 100vh;
/*Header: parent of banner--> set position to relative */
    position: relative;
}

/* Banner styling */
.banner {
    position: absolute;
    top: 20%;
    left: 5%;
    perspective: 300rem;
    overflow: hidden;
}

/* Styling h1 & h2 for banner */
.banner h1 {
    font-family: Lobster Two, serif;
    font-size: 8rem;
    font-weight: 300;
    color: darkred;
    text-shadow: 0.3rem 0.4rem rgba(0, 0, 0, 0.8);
    width: 100%;
    opacity: 0;
    animation: moveBanner 1s .7s forwards;

}

.banner1 h2 {
    font-family: 'Lobster Two', serif;
    font-size: 6rem;
    font-weight: 300;
    color: #FFF;
    text-shadow: 0.2rem 0.3rem rgba(0, 0, 0, 0.8);
    width: 100%;
    opacity: 0;
    animation: moveBanner 1s .7s forwards;
}

/* Paragraph styling for banner*/
.banner p {
    font-family: 'Mulish', serif;
    font-size: 4rem;
    font-size: 700;
    color: #FFF;
    text-shadow: 0.2rem 0.3rem rgba(0, 0, 0, 1);
    opacity: 0;
    animation: moveBanner 1s .7s forwards;
}

/* Styling Button */
.banner .btn button {
    width: 25rem;
    height: 7rem;
    background-color: darkred;
    border: none;
    font-family: 'Josefin Slab', serif;
    font-size: 2rem;
    font-weight: 700;
    text-transform: uppercase;
    color: #FFF;
    text-shadow: 0.2rem 0.3rem rgba(0, 0, 0, 0.5);
    box-shadow: 0.3rem 0.5rem rgba(0, 0, 0, 0.4);
    cursor: pointer;
    opacity: 0;
    animation: moveBanner 1s .9s forwards;
}

/* Banner animation */
@keyframes moveBanner {
    0% {
        transform: translateY(40rem) rotateY(-20deg);
    }
    100% {
        transform: translateY(0) rotateY(0);
        opacity: 1;
    }
}

Red String

Blah blah blah

I dont know what i should put here.

                    <button>Calculate now</button>

Comment: Being a beginner, have a look at [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/q/261592/3124333) :p
Comment: "I want to have more space between the text lines and the button without it getting cropped." How about adding some margin-bottom on the text above the button?
Answer: I don't know the context in which you need to have overflow hidden, usually you'd have a set height to enforce clipping? If you want to make sure the banner doesn't go outside the 100vh set on the header then you should put the overflow:hidden there. However it will always clip anything that goes outside its set height because that's what it's for..
But if you give your banner/parent container some padding, there will always be space around your child elements, including buttons to allow for effects like drop shadows etc. Then you can also move your button where-ever.

/* default margin and padding for all elements */
* {
    margin: 0;
    padding: 0;
    outline: none;
    box-sizing: border-box;
    list-style: none;
    text-decoration: none;
}

/* decrese font size of the HTML file */
html {
    font-size: 62.5%;
}

/* Creating & styling hamburger menu */
.hamburger-menu {
    width: 3rem;
    height: 3rem;
    position: fixed;
    top: 5rem;
    right: 3rem;
    z-index: 200;
    /* create lines for menu */
    display: flex;
    flex-direction: column;
    justify-content: space-evenly;
    cursor: pointer;
}

.line {
    width: 100%;
    height: 0.2rem;
    background-color: #FFF;
    box-shadow: 0.1rem 0.2rem rgba(0, 0, 0, 0.2);
}

/* Costomize header */
.header {
    width: 100%;
    height: 100vh;
/*Header: parent of banner--> set position to relative */
    position: relative;
}

/* Banner styling */
.banner {
background:#ccc;
/*just plopped this bg color in so we can see what's happening better */
padding:5%;
/*give your contents room to breathe with padding */
    position: absolute;
    top: 20%;
    left: 5%;
    perspective: 300rem;
    overflow: hidden;
}

/* Styling h1 & h2 for banner */
.banner h1 {
    font-family: Lobster Two, serif;
    font-size: 8rem;
    font-weight: 300;
    color: darkred;
    text-shadow: 0.3rem 0.4rem rgba(0, 0, 0, 0.8);
    width: 100%;
    opacity: 0;
    animation: moveBanner 1s .7s forwards;

}

.banner1 h2 {
    font-family: 'Lobster Two', serif;
    font-size: 6rem;
    font-weight: 300;
    color: #FFF;
    text-shadow: 0.2rem 0.3rem rgba(0, 0, 0, 0.8);
    width: 100%;
    opacity: 0;
    animation: moveBanner 1s .7s forwards;
}

/* Paragraph styling for banner*/
.banner p {
    font-family: 'Mulish', serif;
    font-size: 4rem;
    font-size: 700;
    color: #FFF;
    text-shadow: 0.2rem 0.3rem rgba(0, 0, 0, 1);
    opacity: 0;
    animation: moveBanner 1s .7s forwards;
}

/* Styling Button */
.banner .btn button {
    margin-top:2rem;
    width: 25rem;
    height: 7rem;
    background-color: darkred;
    border: none;
    font-family: 'Josefin Slab', serif;
    font-size: 2rem;
    font-weight: 700;
    text-transform: uppercase;
    color: #FFF;
    text-shadow: 0.2rem 0.3rem rgba(0, 0, 0, 0.5);
    box-shadow: 0.3rem 0.5rem rgba(0, 0, 0, 0.4);
    cursor: pointer;
    opacity: 0;
    animation: moveBanner 1s .9s forwards;
}

/* Banner animation */
@keyframes moveBanner {
    0% {
        transform: translateY(40rem) rotateY(-20deg);
    }
    100% {
        transform: translateY(0) rotateY(0);
        opacity: 1;
    }
}

Red String

Blah blah blah

I dont know what i should put here.

                    <button>Calculate now</button>

Comment: Thank you for the tip. I completely forgot about checking the size of my banner with the browser's dev tools (rookie mistake). I added "height" to the banner to make the visible parameter bigger. That solved my problem. I'll try the padding as an alternative. The past couple of days of struggling now seem unnecessary. To my defense, the last couple of days were rough... live and learn.


bind() call in tcp client

Question: I am trying to change the source ip address for a tcp packet. Code snippet as given bellow
 bzero(&clientaddr,sizeof(clientaddr));
 clientaddr.sin_family = AF_INET;
 clientaddr.sin_addr.s_addr=inet_addr("172.16.2.10");
 clientaddr.sin_port=htons(8080);
 if (bind(sockfd, (struct sockaddr *) &clientaddr,
   sizeof(clientaddr)) < 0)
{
    perror("bind");
}

Binding a particular port is working fine,
  but when i tried to bind with a diffrent ip adress, the bind is failing with error
bind: Cannot assign requested address

I also tried by setting the socket option as follows,]
setsockopt (sockfd, SOL_IP, IP_TRANSPARENT, &n1, sizeof(int));*

then also its failing with same error.
How could i change my source ip address for packet, originated from my PC.
Please help me, its for a proxy application.
OS :Linux 2.6.37-tproxy #1 SMP Wed Apr 3 23:34:00 IST 2013 x86_64 x86_64 x86_64 GNU/Linux
Thanks in advance.
Comment: No probs I guess, if your kernel supports it. I dont have much experience on this. Thought this system info would help others to help you..
Comment: Mention your kernel and OS version please..
Comment: Not sure, but you probably have to use raw sockets to do this.
Comment: @Barmar If am not wrong, I have seen this possible in CentOS/RHEL 6.0 in the same way OP did
Comment: @VoidPointer kernel version is 2.6.37
Comment: @VoidPointer I am using CentOS 6.3, is it a problem with this?
Comment: What is the IP Address with which it gives error?
Comment: Did you run your application as root or with a user having the CAP_NET_ADMIN capability? What was the errno error set by setsockopt, if any? I assume you have read [http://lxr.linux.no/#linux+v3.10/Documentation/networking/tproxy.txt](http://lxr.linux.no/#linux+v3.10/Documentation/networking/tproxy.txt) and are following it. I probably can not help much more, without some more exact error or more code (preferrably [SSCCE](http://www.sscce.org/)
Comment: yes, am running my aplication as root user only.
Comment: How about the rrno from setsockopt?
Answer: You will need to use a raw socket and create the ip and tcp headers (where you will be able to set the desired IP Address (spoofing).
raw_socket = socket(AF_INET, SOCK_RAW, IPPROTO_RAW);

You can check the linux manual page man 7 raw
Answer: You can only bind() to an IP address that is local to your computer, i.e. implemented by one of your network interfaces.
Comment: Are you familiar with the Linux transparent proxy functionality? See the tproxy.txt in kernel documenttion and `man 7 ip` at IP_TRANSPARENT option.

bind() call in tcp client


Appending a self constructed class in priority que gives TypeError: '<' not supported between instances of 'str' and 'Node'

Question: import sys
from queue import PriorityQueue

class Node(object):
    def __init__(self, data = None):
        self.value = data
        self.right = None
        self.left = None

class Huffman():
    def __init__(self, data):
        self.data = data

    def encoding(self):
        my_dict = {}
        for i in self.data:
            my_dict[i] = my_dict.get(i, 0)+1
        q = PriorityQueue()
        for i, j in my_dict.items():
            q.put((j,i))
        while q.qsize() >= 2:
            val_1 = q.get()
            val_2 = q.get()
            new_node_1 = Node(val_1[0]+val_2[0])
            if isinstance(val_1[1], str):
                new_node_1.left = val_1[1]
            else:
                new_node_1.left = val_1[1]
            if isinstance(val_2[1], str):
                new_node_1.right = val_2[1]
            else:
                new_node_1.right = val_2[1]
            q.put((new_node_1.value, new_node_1))

Herein, I am getting an error in while loop, after a few operations it fails to use the method q.get(), or q.put().
For example, Huffman('AADCIDCVUSHDUSHUSAHDIADHIAD').encoding()
I do not want to change entire code, but just want to change priorities such that it priorities entries on the basis of first element (which is integer) only.
Comment: You are adding a Node in a priority queue that accepts a string. That is the issue. I don't really know if you can fix it without changing a little your code.
Comment: @LucasBelfanti I can add a Node in a priority que that is not an issue. Issue arises when it tries to compare Node with string to decide priorities. Thus, it gives that comparison is not possible. Also, from the python's documentation we can find that comparison between two different class is not possible. My argument is that the container of priority que is allowing Node but the comparison operators are stopping it. For example, my priority que includes integer and string both rather just strings. Thanks!
Answer: You are right, the Priority Queue doesn't know how to compare a str with a Node. You have to override the comparator functions in your Node class to let the Priority Queue know how to compare two different types.
Example (change the comparators as you want):
class Node(object):
    def __init__(self, data=None):
        self.value = data
        self.right = None
        self.left = None

    def __lt__(self, obj):
        """self < obj."""
        return self.value < obj

    def __le__(self, obj):
        """self <= obj."""
        return self.value <= obj

    def __eq__(self, obj):
        """self == obj."""
        return self.value == obj

    def __ne__(self, obj):
        """self != obj."""
        return self.value != obj

    def __gt__(self, obj):
        """self > obj."""
        return self.value > obj

    def __ge__(self, obj):
        """self >= obj."""
        return self.value >= obj

Comment: Thanks, but I was looking for a better solution. Something which skip this entire process.
Comment: Well, maybe you could avoid the override of some of them, for example the `__ne__`, the `__eq__`, the `__ge__` and `__le__`. I mean you have to override the ones that the Priority Queue uses, but I'm afraid it's the most pythonic solution.
Comment: I want to return True for each operator by just two line of code, or just use an universal comparison operator. Like `def __cmp__(self,other)` `return cmp((self.left), (other.left))`. Or, change priority list such that it does not go through inner comparison. I have upvoted your solution, because it was helpful but looking forward for others.


Mean square error

Question: anyone can help me explane  :

I don't understand formula 2. Why transform from formula 1 to 2.
Thank you.
Answer: The MSE of an estimator, $\hat{\alpha}$, of an unknown parameter $\alpha$ is:
$$\text{MSE}(\hat{\alpha})=\mathbb{E}\Big[(\hat{\alpha}-\alpha)^{2}\Big]$$
We can formulate the other representation as follows:
$$\begin{align}
\text{MSE}(\hat{\alpha})&=\mathbb{E}\Big[(\hat{\alpha}-\alpha)^{2}\Big]\\
&=\mathbb{E}\Big[(\hat{\alpha}-\mathbb{E}[\hat{\alpha}]+\mathbb{E}[\hat{\alpha}]+\alpha)^{2}\Big]\\
&=\mathbb{E}\Big[\big(\hat{\alpha}-\mathbb{E}[\hat{\alpha}]\big)^{2}+2\big(\hat{\alpha}-\mathbb{E}[\hat{\alpha}]\big)\big(\mathbb{E}[\hat{\alpha}]-\alpha\big)+\big(\mathbb{E}[\hat{\alpha}]-\alpha\big)^{2}\Big]\\
&=\mathbb{E}\Big[\big(\hat{\alpha}-\mathbb{E}[\hat{\alpha}]\big)^{2}\Big]+\mathbb{E}\Big[2\big(\hat{\alpha}-\mathbb{E}[\hat{\alpha}]\big)\big(\mathbb{E}[\hat{\alpha}]-\alpha\big)\Big]+\mathbb{E}\Big[\big(\mathbb{E}[\hat{\alpha}]-\alpha\big)^{2}\Big]\\
&=\mathbb{E}\Big[\big(\hat{\alpha}-\mathbb{E}[\hat{\alpha}]\big)^{2}\Big]
+2\big(\mathbb{E}[\hat{\alpha}]-\alpha\big)\mathbb{E}\Big[\big(\hat{\alpha}-\mathbb{E}[\hat{\alpha}]\big)\Big]
+\big(\mathbb{E}[\hat{\alpha}]-\alpha\big)^{2}\\
&=\mathbb{E}\Big[\big(\hat{\alpha}-\mathbb{E}[\hat{\alpha}]\big)^{2}\Big]
+2\big(\mathbb{E}[\hat{\alpha}]-\alpha\big)\big(\mathbb{E}[\hat{\alpha}]-\mathbb{E}[\hat{\alpha}]\big)
+\big(\mathbb{E}[\hat{\alpha}]-\alpha\big)^{2}\\
&=\mathbb{E}\Big[\big(\hat{\alpha}-\mathbb{E}[\hat{\alpha}]\big)^{2}\Big]
+\big(\mathbb{E}[\hat{\alpha}]-\alpha\big)^{2}\\
&=\text{Var}(\hat{\alpha})+\text{Bias}(\hat{\alpha},\alpha)^{2}
\end{align}$$
Essentially, the purpose of the second representation is that it is a convenient way to calculate the MSE. It also tells us that in the case of unbiased estimators, the MSE and variance are the same.
Comment: @conannhoc If you're happy with the answer, you can mark it as accepted.

Mean square error


Async flow control without RxJS

Question: I'm working on a mobile app and I want it to be offline-first.
Let's say I want to show the "Company" page so I request the company datas.
Here's what I do, I look for the company data in the local storage (indexedDB in my case) and at the same time I call the server for the same data (to get the potential updates). In each callback I update the view with the datas fetched. First updated from local datas then from remote datas.
To avoid a race condition I have a boolean called "remoteDataAlreadyFetched" that I check in my local storage callback (in case remote datas arrive before the storage response)
My question is: how should I handle this ? 2 separate promises in my view controller (one for local, one for remote) ? Should I use an observable ? This looks overkill since there won't be more than 2 responses (local and remote). Am I missing something ?
Thanks a lot for your help
EDIT:
This is how I would do it with RxJS. Don't know if it's a bad practice to use Observables in this situation...
public static getOfflineFirstObservable(localCall, remoteCall): Observable<any> {
  const data$ = new BehaviorSubject(null);
  var hasFetchedRemoteData = false;

  localCall().then(localDatas => {
    if (!hasFetchedRemoteData) data$.next(localDatas);
  });

  remoteCall().then(remoteDatas => {
    data$.next(remoteDatas);
    hasFetchedRemoteData = true;
  });

  return data$.asObservable();
}

Answer: Very interesting problem, so you are trying to make sure about the order of your two async operations.
I implement something that realize this, check my code below or just run them ;)
// two promise with no guaranteed order:
var localPromise = new Promise(resolve => setTimeout(resolve, Math.random() * 1000))
var remotePromise = new Promise(resolve => setTimeout(resolve, Math.random() * 1000))

// wrap them
var localFirst = Promise.resolve(localPromise)
    // can also add your handler for localdata
    .then(() => Promise.resolve(remotePromise))
var remoteFirst = Promise.resolve(remotePromise)

// viola
Promise.race([localFirst, remoteFirst]).then(console.log)

Comment: I might not be helping here :(, but I think this problem should be generalized into some question like 'async flow control without rxjs' which might have a better clearance from a more constructive perspective.
Comment: Interesting. The thing is there's no way localFirst wins the race right ? So why use the Promise.race() ? Also the idea was to write this logic in my provider so I can have a clean call in my view controller. In this case it looks like I would have to pass a callback function AND use the returned Promise to handle the "offline first" behavior, right ?
Comment: I'm wrong somehow, regardless of my answer, I think that you DO have to use two handlers when local  comes first then remote come back, which reminds me of Rxjs as well :) tho I'm not that into Rxjs. If you can accept that there should be two handlers then I think we can fix this without using Rxjs
Comment: Arf, ok. A friend of mine told me I could use Service workers but iOS support is not there yet. Ok I'll rename the issue then, thx Octave :)
Answer: If you're offline then trying to get remote data will result in rejected promises (with promise.race). If all you're trying to do is get item from cache first (if it's there) and if it's not try to get it remote you can do the following:
const cacheBuilder = promises => fetcher => setFn => getFn => url => {
  //using url as key but can be url+JSON.stringify(parameters)+method(GET/POST)
  const key = url;
  //get from cache first if exist
  return getFn(key).catch(()=>{
    if(promises[key]){
      return promises[key];//return active promise
    }
    promises[key]=fetcher(url);
    return promises[key];

  })
  .then(
    result=>{
      if(!promises[key]){//update cache, this will cause requests to server
        fetcher(url).then(result=>setFn(key,result)).catch(ignore=>ignore);
      }
      promises[key]=undefined;
      setFn(key,result);
      return result;
    }
  );
}

const cacheFirst = cacheBuilder(
  {}//store active promises here
)(
  //fetch function (can be $.get or something else)
  //  I am only using url here but you could use (url,params,method,headers) as well
  url=>
    //remove "console.log ||" it's to show that multiple active fetches share promises
    //  asking for fetch("/") multiple times while first time is not resolved
    //  will not cause multiple requests
    console.log("fetching:",url) ||
    fetch(url)
    .then(response=>response.text())
    .then(result=>result.substr(0,10))
)(
  //how to set an item in local storage
  (key,value)=>{
    newStorage = JSON.parse(localStorage.getItem("netCache")||"{}");
    newStorage[key]=value;
    localStorage.setItem("netCache",JSON.stringify(newStorage));
  }
)(
  //how to get an item based on key (can be url or url + JSON.stringify(parameters) or url+params+method...)
  key=>
    Promise.resolve(
      JSON.parse(localStorage.getItem("netCache")||"{}")[key] ||
      Promise.reject("Not in cache")
    )
);

Promise.all([//should not cause multiple requests, should have only one request made
  cacheFirst("/"),
  cacheFirst("/"),
  cacheFirst("/"),
  cacheFirst("/")
]).then(
  ()=>cacheFirst("/")//should come from cache as well, no request made
)

Here is an example where all implementation is in one function without passing fetch, getter and setter:
const cacheFirst = (promises => url => {
  //using url as key but can be url+JSON.stringify(parameters)+method(GET/POST)
  const key = url;
  const fetcher = url=>
    fetch(url)
    .then(response=>response.text())
    .then(result=>result.substr(0,10));
  const setFn = (key,value)=>{
    newStorage = JSON.parse(localStorage.getItem("netCache")||"{}");
    newStorage[key]=value;
    localStorage.setItem("netCache",JSON.stringify(newStorage));
  }
  const getFn = key=>
    Promise.resolve(
      JSON.parse(localStorage.getItem("netCache")||"{}")[key] ||
      Promise.reject("Not in cache")
    );
  //get from cache first if exist
  return getFn(key).catch(()=>{
    if(promises[key]){
      return promises[key];//return active promise
    }
    promises[key]=fetcher(url);
    return promises[key];
  })
  .then(
    result=>{
      //update cache if result didn't came from request, this will cause requests to server
      if(!promises[key]){
        fetcher(url)
        .then(result=>setFn(key,result))
        .catch(ignore=>ignore);
      }
      promises[key]=undefined;
      setFn(key,result);
      return result;
    }
  );
})({})//IIFE passing in the promises object to store active promises

Comment: @Maslow updated the code to request the resource again when it came from cache and update the cache. If something goes wrong requesting the resource then the error is ignored and cache is not updated. Instead of passing in all the functions like fetcher, getter and setter you can code it into the function as well.
Comment: What I'm trying to do is make my app appear as fast as possible. To do that, I want to immediately show the user the cached datas during the remote call. If he's offline then the remote call will just not return but it's ok. If the remote call returns then I want to update the cached and displayed datas. Thanks for your answer, I'm gonna take a deeper look into it
Comment: I'm reading over and over again your code and I have some difficulties understanding it, to be honest ^^" That's some next level sh*t. Is that functional programming ?
Comment: Ok that's far easier to read. So you store all the running promises to avoid making the same call several times... setFn just set a value in LS, ok... Didn't get the substr(0, 10) in fetcher function tho... Finally your promise only returns once, right ? I won't have my 2-steps display (cache data immediately... then fetched data when the query returns). This piece of code is a way to avoid identical calls to be made. It's cool, but does not resolve my issue, I think
Comment: @Maslow If data is not available in cache it'll try to get from network, if it was in cache then that is returned and cache is updated with network data (check the comment: `//update cache if result didn't came`). The subsr is just so you can run it in the console here and do not have very large strings, I'm using [fetch](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API) but as the comment indicates you can use jQuery or anything here, it's just a function that makes a network request and returns the result.
Comment: I see. So the user won't see the updated data right away, right ? It will show the cached data, then update the cache and only _the next time_ the user sees the screen he will see the updated data. That's it ? It could do the job in some case. Thanks
Comment: @Maslow Yes, cache first and refresh cache, on next request cache first (so the previously refreshed one) then refresh ... Since the user can be offline the refresh is optional and errors are ignored. If you want to fetch local and update when/if remote comes in you may have unexpected behavior like user is scrolling through info and remote data comes in so changes the page. However; if this is what you want then promise is probably not the right way to go but instead use callback, you can call a callback multiple times; once for local and once for remote.
Comment: Yes that's what I figured... Thanks a lot for your help
Answer: I've finally decided to create 2 separate promises. I get the local data (if exists) on page load and immediately try to fetch the remote data. So the user can see a content right away but still see a spinner on the top right indicating that's remote data have been requested. When the request comes back the view is updated.
I've decided to do that because the page also has a pull to refresh so it seemed smarter to separate the 2 calls (local and remote) to be able to call the server as many time as I wanted.
Thanks for your answers.
@HMR Your solution is really interesting but didn't really fit my needs. Thanks a lot

Async flow control without RxJS


Prove $f(x)=3x+1$ is continuous at $x=a$

Question: Question:
Give the formal definition for a function to be continuous at $x=a$.
Prove, by using the formal definition, that $f(x)=3x+1$ is continuous at $x=a$, where a is any point on the real line.
I am able give the formal definition which is:
 For every $\epsilon>0$, there exists a $\delta>0$ (which depends on $\epsilon$) such that:
$|f(x)-L|<\epsilon$ wherever, $0<|x-a|<\delta(\epsilon)$
However, I am not sure how to go about the second part without a value for $L$, would anybody be able to help?
Comment: Which value of $L$ would be very logical?
Comment: Also that's not the definition of continuity in $a$. $L$ takes a very special value in the definition.
Comment: Oh I see, maybe that's where I'm going wrong, what is the definition of continuity in a?
Comment: Well, since you asked this question, the definition should be somewhere in your course notes or textbook, go take a look, think about it and try to solve the question.
Answer: You have cited the definition of the limit when $x$ tends to $a$; Continuity implies $L = f(a)$. Then, it is only a matter of proving the limit by epsilon-delta, which I assume that you are confident with
$$
 0<|x - a|<\delta \implies |f(x) - f(a)| = |3x+1 - 3a - 1| < \varepsilon, \qquad x \in \mathbf{R}
$$
Comment: Thank you very much, L=f(a) is somewhat missing from my course notes!


Bad performance when drawing bitmap to canvas on SurfaceView with rotated matrix.

Question: I use surface view to implement image viewer.
It works fine. But on some devices like htc new one , I got a bad performance.
I use a matrix to maintain what the image should show. (include translate ,scale , rotate).
And draw it with:
canvas.drawBitmap(mMainBitmap, mImageMatrix, mMainBitmapPaint);

If mImageMatrix's degree is 0 or 180 , the method test on Htc new One would cost around 5-10 ms. But other degree would cost 20-25 ms. But on Acer S1 it always cost 5-10 ms. And sometimes I need to draw many images at the same time , so I got a bad performance.
I think this is a device problem. But I wonder if there is any way to solve it.
Comment: What versions of Android run on these devices and can you post the whole of you `onDraw()` method?
Comment: Acer S1 is 4.2.2 and Htc new One is 4.4.2.
Comment: Sorry I can't post all my onDraw method. But the cost time what I say is only canvas.drawBitmap(mMainBitmap, mImageMatrix, mMainBitmapPaint). And I have removed other code in onDraw method for profile performance.
Answer: What about having hardwareAcclerated flag in the AndroidManifest.xml?


A and B can do a piece of work in 9 days, B and C in 12 days, A and C in 18 days. If all of them work together, then how much time will they take?

Question: This is how I did it.
$A+B=9  \tag 1$
$B+C=12  \tag 2$
$A+C=18  \tag 3$
Adding (1), (2) and (3) we get:
$A+B+B+C+A+C=9+12+18$
$2(A+B+C)=39$
$A+B+C=19.5$
So, they complete the work together in $19.5$ days.
But the book says this answer is wrong and the correct solution is:
Work done by $(A+B)$ in $1$ day = $\frac {1}{9}$
Work done by $(B+C)$ in $1$ day = $\frac {1}{12}$
Work done by $(A+C)$ in $1$ day = $\frac {1}{18}$
$(A+B)+(B+C)+(A+C)= \frac {1}{9} + \frac {1}{12} + \frac {1}{18}$
$A+B+C=\fracBE
 {1}{8}$
BE
So, all of them take $8$ days to complete the task.
Could anybody please tell me why my approach is wrong and the book's approach is right?
Comment: SO if $C$ stays home it takes $9$ days.  But if $C$ comes in any helps it will take ten days longer.  Just what is it that $C$ does that makes it take ten days longer.  Does she break windows?  Does she wander into the street and require a baby sitter?  Note: when two people work together it should take *less* time and not more time.  But *adding* is definitely *NOT* the way to do it.
Answer: Here your variables $A,B,C$ doesn't exactly represent what you want them to. Your first equation is $A+B=9$ . Now this line says that $A$ is that certain amount of work done by the person A in those 9 days.
Your third equation is however $A+C=18$ , but here $A$ represents a different amount of work the person has done in 18 days and thus the ambiguity.
First we need to understand that a person's capability of doing a certain work in a given context is fixed per day. So let $W_A$ units be the amount of work A does in 1 day alone, similarly let $W_B , W_C$ be defined.
Now the work they are trying to complete is worth say $N$ units. As we have defined their capabilities in units, so this is consistent.
A and B can together do $W_A+W_B$ units of work in a day, so in 9 days they complete the work. This gives us :
$$ 9(W_A+W_B)=N$$
Similarly for others we have,
$$ 12(W_B+W_C) = N$$
$$ 18(W_C+W_A)=N$$
Work done by all three in one day is $(W_A+W_B+W_C)$ units , so if $X$ days are required for them to complete the work we must have ,
$$ X(W_A+W_B+W_C)=N$$
Now it is straightforward from here to find $X$ using basic algebra.
Answer: Another solution that I like for this problem goes like so:
Imagine each of $A$, $B$, and $C$ has an identical twin, and all $6$ of the people go to work. In the $6$ people, we have one copy of each pair, $\{AB\}$, $\{AC\}$, and $\{BC\}$.
We will let them work for $36$ days, because $36=$lcm$(9,12,18)$.
In that time, $\{AB\}$ will complete $4$ jobs, $\{AC\}$ will complete $2$ jobs, and $\{BC\}$ will complete $3$ jobs. All together that is $9$ jobs in $36$ days, or $4$ days per job.
But since there are two of each person they can work twice as fast as normal. Thus $A$, $B$, and $C$ working together will complete a job in $8$ days.
Answer: When you wrote your three equations you have not clearly thought what you want to say with them. This kind of problem requires a careful choice of the used units and meanings of the unknowns.
Assume that $A$, $B$, and $C$ as single persons can do the fractions $a$, $b$, $c$ of the "piece of work" in one day. (The numbers $a$, $b$, $c$ are $\ll1$.) The first equation then would say
$$a+b={1\over 9}\ ,$$
because $A$ and $B$ together need $9$ days to complete it all. Similarly we get
$$b+c={1\over12},\qquad a+c={1\over18}\ .$$
Adding these three equations gives
$$2(a+b+c)={1\over9}+{1\over12}+{1\over18}={1\over4}\ ,$$
or $\>a+b+c={1\over8}$. This says that all three together can do ${1\over8}$ of the total work in one day. Therefore the three will need $8$ days to do the "piece of work".
Answer: Why are you adding them?
If I can clean a room it $2$ hours and you can clean a room in $3$ does it make sense to thing if we work together it would take us $5$ hours?  Why would you helping me make it take $3$ hours longer?  Shouldn't your helping me make it go faster?
So why are you adding the time?
So if we don't add what do we do?
Well, how many rooms can I clean in a day?  It takes $2$ hours per room and I have $24$ hours... that is $\frac {24}2=12$ rooms.  And how many room can you clean in a day?  It take you $3$ hours per room you can clean $\frac{24}3=8$ rooms.  So together how many room can we do?  Well, I can do $12$ any you can do $8$ so together we can to $20$.
Note:  YOu don't add how long it takes you! you add how much work you can do in an ammount of time!
And if it takes us $24$ hours to do $20$ rooms how long does it take us to do $1$ room?  Well $\frac {24}{20} = 1.2$.  So together it takes us $1.2$ hours to do one rooom.  Notice that is less time than either of us.
So ... how do we do this if we don't want to just guess?
If I can do a job in $m$ time.  Then I can to $\frac 1m$ of the job in one unit of time.  And you can do a job in $n$ time then you can do a $\frac 1n$ of the job in one unit of time.  Togethere we can do $\frac 1m + \frac n = \frac {n+m}{mn}$ of the job in $1$ unit of time.
So how many units of time does it take to do the whole job?  We need $x$ units of time and we can to $\frac {n+m}{nm}\cdot x = 1$ job the those units of time so it takes us $x = \frac {nm}{n+m}$ time to do one job.
Ex:  If I take $2$ hours I can do $\frac 12$ a job in an hour.  You take $3$ hours so you can do $\frac 13$ a job in an hour.  Together we can do $\frac 12 + \frac 13 = \frac 56$ of the job in an hour.  After $x$ hours we can to $\frac 56 x$ jobs.  To do one job exactly we have $\frac 56 x = 1$ so $x = \frac 65=1.2$ hours.
So your problem.  $A$ and $B$ together take $9$ days.  so Together $A$ and $B$ can to $\frac 19$ of the job in $1$ day.  $B$ and $C$ together can do the job in $12$ days so together they can do $\frac 1{12}$ of the job in $1$ day.  And $A$ and $C$ together can do the job in $18$ days$ so together they can do $\frac 1{18}$ of the job in $1$ day.
If you cloned them all and had two copies of them working together then 2$Anne$s and 2$Bernie$s and 2$Claudia$s can do $\frac 1{9} + \frac 1{12} + \frac 1{18} = \frac 4{36} + \frac 3{36} +\frac 2{36} = \frac 9{36} = \frac 14$.  So two copies of the three people can do $\frac 14$ of the work in a day.
So one copy of the three people to do $\frac 12\frac 14 = \frac 18$ of the work in a day.
So how many days does it take to do on full job if the can do $\frac 18$ in a day? Then in $x$ days then can do $\frac 18 x = 1$ job.  SO $x = 8$ it takes them eight days working together.


Proving a system of n linear equations has only one solution

Question: I have been given the system:
$-x_1 + 2x_2 + ... + 2x_{n-1} + 2x_n = 1$
$2x_1 - x_2 + ... 2x_{n-1} + 2x_n = 2$
$.$
$.$
$.$
$2x_1 + 2x_2 + ... + 2x_{n-1} - x_n = n$
And the assignment to prove that it has only one solution. I am aware of the existence of discriminants and their role of solving system of linear equations, although I have no idea on how to use that to prove this system has only one solution. (And I currently lack materials on infinite determinants and recurrent relations, any links would be appreciated).
Could anyone provide suggestions or hints on how to prove this system has exactly one solution?
Answer: Your equation is of the form $Ax = b$ where $$A = \begin{bmatrix}-1 & 2 & 2 & 2 & 2 & \cdots & 2 & 2\\ 2 & - 1 & 2 & 2 & 2 &\cdots & 2 & 2\\ 2 & 2 & -1 & 2 & 2 &\cdots & 2 & 2\\ 2 & 2 & 2 & -1 & 2 &\cdots & 2 & 2\\ 2 & 2 & 2 & 2 & -1 &\cdots & 2 & 2\\ \vdots & \vdots & \vdots & \vdots & \vdots &\ddots & \vdots & \vdots\\ 2 & 2 & 2 & 2 & 2 &\cdots & -1 & 2\\ 2 & 2 & 2 & 2 & 2 &\cdots & 2 & -1 \end{bmatrix}$$
We then have
$$A = -3I_{n \times n} + 2 \begin{bmatrix} 1\\ 1\\ 1\\ 1\\ 1\\ \vdots\\ 1\\ 1\end{bmatrix} \begin{bmatrix} 1& 1& 1& 1& 1& \cdots& 1& 1\end{bmatrix}$$
By Sherman-Morrison, we have
$$A^{-1} = -\dfrac13 I_{n \times n}-\dfrac2{3(3-2n)}\begin{bmatrix} 1\\ 1\\ 1\\ 1\\ 1\\ \vdots\\ 1\\ 1\end{bmatrix}\begin{bmatrix} 1& 1& 1& 1& 1& \cdots& 1& 1\end{bmatrix}$$
Clearly, $A^{-1}$ exists for all $n$.
Comment: For those like who did not know there was name for that: [Sherman-Morrison formula](http://en.wikipedia.org/wiki/Sherman%E2%80%93Morrison_formula). Nicely done, +1.
Comment: @julien There is a more general one named [Woodbury formula](http://en.wikipedia.org/wiki/Woodbury_matrix_identity). A very useful identity to know.
Comment: Thanks, Marvis. As I see it, it is also a generalization of the neat: $I+AB$ is invertible if and only if $I+BA$ is invertible.
Comment: @julien Yes. I have used this identity quite a few times in my research and it is really helpful. :)
Comment: May I ask what your area of research is?
Comment: @julien Fast algorithms/Numerical linear algebra.
Comment: Interesting. For sure, you must know what a useful formula is!
Answer: Symmetrize!  Add up all the equations. You will find an expression for $x_1+\cdots+x_n$.
Now it is easy to write down the solution.
Details: Let $s=x_1+\cdots+x_n$. Adding up the equations, we get
$$(2n-3)s=1+2+\cdots+n=\frac{n(n+1)}{2}.$$
The $k$-th equation can be written as $2s-3x_k=k$. It follows that
$$x_k=\frac{1}{3}\left(\frac{n(n+1)}{2n-3}-k\right).$$
Answer: The system can  be written in matrix form $Ax=b$ where $A$ is the matrix
$$
A=2J-3I
$$
with J the matrix with all entries 1 and $I$ the identity matrix.
Show that the matrix $A$ is  invertible (equivalently all eigenvalues of $A$ are non zero) therefore the system has the unique solution $A^{-1}b$.
This answer is relevant.
Answer: There is a very nice way to see this using the algebra of circulant matrices. Define
$$\rm X = \left[\begin{array}{}
0 & 1 & 0 & 0 &\cdots& 0\\
0 & 0 & 1 & 0 &\cdots& 0\\
0 & 0 & 0 & 1 &\cdots& 0\\
 & & & & \cdots &\\
0 & 0 & 0 & 0 &\cdots& 1\\
1 & 0 & 0 & 0 &\cdots& 0\end{array}\right]\ \Rightarrow\
X^2\! = \left[\begin{array}{}
0 & 0 & 1 & 0 &\cdots& 0\\
0 & 0 & 0 & 1 &\cdots& 0\\
 & & & & \cdots &\\
0 & 0 & 0 & 0 &\cdots& 1\\
1 & 0 & 0 & 0 &\cdots& 0\\
0 & 1 & 0 & 0 &\cdots& 0\\\end{array}\right]\ \Rightarrow\ \cdots\ \Rightarrow\ X^n = 1$$
Your circulant matrix is $\rm\:M = f(X)\, =\, -1\!+\!2X\!+\!2X^2\!+\,\cdots\,+2X^{n-1}.\,$ One easily checks (see below) that $\rm\:f(x)\:$ is coprime to $\rm\:x^n-1,\:$ so by the Euclidean algorithm there is a Bezout identity
$$\rm a(x)\ f(x) + b(x)\ (x^n\!-1)\, =\ 1$$
Since $\rm\:X^n=1,\:$ evaluating above at $\rm\: x = X\:$ yields $\rm\:a(X)\,f(X)\, =\, 1,\:$ so $\rm\ M = f(X)\:$ is invertible.
For coprimality, let $\rm\:g = 1\!+\!x\!+\cdots+\!x^{n-1}.\:$ Then $\rm\:f = 2g\!-\!3\:$ is coprime to $\rm\:g\:$ since $\rm\:2g-f = 3,\:$ and $\rm\:f\:$ is coprime to $\rm\:x\!-\!1\:$ (else $\rm\:x\!-\!1\mid f\:\Rightarrow\:0=f(1) = 2n\!-\!3).\:$ Therefore, by Euclid's Lemma, we deduce that $\rm\:f\:$ coprime to both $\rm\:g\:$ and $\rm\,x\!-\!1\:\Rightarrow\:f\:$ coprime to their product $\rm\:(x\!-\!1)g = x^n\!-\!1.$
Answer: Note that  the system can be written as $(2J-3I)x=(1,2,\ldots ,n)^t$, where $x=(x_1,\ldots ,x_n)$, $J$ is the matrix with all entries $1$ and $I$ is the identity matrix. Now the eigen values of $J$ are $n$ with mutiplicity $1$ and $0$ with multiplicity $n-1$ (this follows from the fact that rank of $J$ is $1$, which is also the number of non-zero eigen values, and the sum of the eigen values is $n$). Hence the eigen values of $2J-3I$ are $2n-3$ with mutiplicity $1$ and $-3$ with multiplicity $n-1$, so all the eigen values are non-zero and hence the rank of $2J-3I$ is $n$. Therefore the system has a unique soloution.


Serverless query in synapse fails

Question: new to Synapse, built a pipeline to ingest data from on prem sql server to Data Lake gen 2 as a csv file.  Pipelines runs fine.  on the Data hub I can see my file.  In order to simplify things, i changed my source query to..  select top 10 PKId from myTable. I can right click and preview the data.
When I right click and select, select top 100 rows, i get a sql script.  I added a with statement.
<code>    SELECT
    TOP 100 *
FROM
    OPENROWSET(
        BULK 'https://sy     egen2fs/Raw/*.csv',
        FORMAT = 'CSV',
        PARSER_VERSION = '2.0')
    WITH
    (
    UserID int
    ) AS [result];
</code>
when I run the query, i get a header column, no data and the error...  Error handling external file: 'waitIOCompletion error. HRESULT = 0x80070005(offset = 0, bytes requested = 78).'. File/External table name: 'http
I have not created any databases or tables or views within synapse.  I am just trying to query the file.  I have found some articles on recreating a Master database Key...  but don't think that applies to me, since just tryinng to read file.
Any help appreciated
Answer: I was able to get this to work by explicitly giving permissions to the file I am trying to query, but I was thinking the file would inherit permissions on the folder where my pipeline creates the csv file.
At least I have narrowed my issue down to permissions.
Answer: The underlying reason for the error is unclear, in general, the error message WaitIOCompletion indicates that the query failed while waiting to complete the IO operation that reads data from the Azure Data Lake.
Make sure that you can access this file. If your file is protected with SAS key or custom identity, you would need to set up server-level credentials for SQL login.  Refer to this document to know more.
I have tried it in my lab and worked fine for me. Hear I included header as my file contains a header row.
<code>SELECT top 10 *
FROM OPENROWSET(
  BULK 'https://vnmoola0121adls2.blob.core.windows.net/container1/test/*.csv',
  FORMAT = 'CSV',
  PARSER_VERSION = '2.0',
  HEADER_ROW = TRUE)
WITH
(
 UserID int
) AS [result];
</code>
Comment: On the data hub, I can see my data lake storage where I can navigate to the folder where my csv lives, right click the file and preview.  In the data hub I also see my data lake storage as a linked service, where I can also navigate to my file, right click, preview and see my data.

I basically just created the synapse resource and didn't do anything to protect the file..  just imported it.

It also sounds like, I should not have to create a data base just to read a csv file.
Comment: In synapse, I can issue queries...  select 1 works, select SYSTEM_USER returns my login properly.  On the Data tab, I select my storage account, select the sub folder underneath (primary), right click manage access and can see the same user returned by "select system_user".
Comment: I was able to get this to work by explicitly giving permissions to the file I am trying to query, but I was thinking the file would inherit permissions on the folder where my pipeline creates the csv file.

At least I have narrowed my issue down to permissions.
Answer: Understand access control helped me figure out permissions.  I assumed child files of my parent folder would inherit permissions by default.  They do not.  I had to update access control properties and set permissions for "default".

Serverless query in synapse fails


Question about limit of Stochastic Process

Question: Given $\mu_t$ continuous stochastic process that satisfies $\int_0^t \mu_s^2\;ds<\infty$. Define $X_t\equiv \int_0^t \mu_s\;ds$. Let $|\cdot|$ denote floor function. Then where does $\sum_{n=1}^{|t/\Delta|}(X_{n\Delta}-X_{(n-1)\Delta})^2$ converge to in Mean Square as $\Delta\rightarrow 0$?
This is not  HW. My attempt has been to write $\sum_{n=1}^{|t/\Delta|}(X_{n\Delta}-X_{(n-1)\Delta})^2$ as $\sum_{n=1}^{|t/\Delta|} (\int_{(n-1)\Delta}^{n\Delta} \mu_s\;ds)^2$ and then I'm not sure how to proceed, despite knowing the definition of MS convergence.
Comment: Related:http://math.stackexchange.com/q/727614/
Answer: If $\mu$ is predictable and Lebesgue integrable, this converges to $0$. This is an Ito process with $\sigma =0$.
Quadratic Variation of Ito process


Custom module pages not rendering when added to admin menu

Question: I have a custom module that outputs some sql reports in a table with a csv button.  These are SQL tables that are not accessible via views which is why I had to make this module.
Now when these links are accessible through the frontend (ie do not have 'admin' in the path ) the page and table's contents render just fine.
$items['custom_report/glp_report'] = array(
'title' => 'GLP Report',
'description' => 'Report for Guided Learning Pathways.',
'page callback' => 'op_reports_page',
'access callback' => 'op_reports_permission',
 //'theme callback' => 'op_theme',
'type' => MENU_NORMAL_ITEM,
);

When I switch this to an admin path only the table headers render but no content.
$items['admin/custom_report/glp_report'] = array(
'title' => 'GLP Report',
'description' => 'Report for Guided Learning Pathways.',
'page callback' => 'op_reports_page',
'access callback' => 'op_reports_permission',
 //'theme callback' => 'op_theme',
'type' => MENU_NORMAL_ITEM,
);

Theme_debug is on and I can see that on the frontend the bootstrap block.tpl serves the table correctly

however on the admin page it loads block/block.tpl

Hypothesis
Drupal Admin theme is different than the frontend theme.  For whatever reason, this new theme uses a different template and that different template can't render my output.
Approach 1 Create custom template for the page
So I wanted to force a custom template hoping that would fix the module override:
Here is the page callback:
function op_reports_page() {
$page = drupal_render(drupal_get_form('op_reports_form', 'glp'));
$page .= op_reports_table('glp');

$page = array
(
'op_reports_page' => array
(
// Note - we will register theme_my_page in the next step
'#theme' => 'glp_reports',
'#contents' => $page,
),
);

return $page;
}

Here is the theme_hook:
function op_reports_theme()
{
  return array
  (
    'glp_reports' => array
    (
      'variables' => array('contents' => array()),
      'template' => 'op_theme', // don't add .tpl.php
    ),
  );
}

Template file:

<?php print t('My Page'); ?>

  <?php print render($contents); ?>

Outcome
While this renders for frontend, on the admin I get a blank content section.
Approach 2 force the theme through the hook_menu
Using the theme callback you can tell Drupal how the page should be rendered
Hook Menu:
  $items['admin/custom_report/glp_report'] = array(
    'title' => 'GLP Report',
    'description' => 'Report for Guided Learning Pathways.',
    'page callback' => 'op_reports_page',
    'access callback' => 'op_reports_permission',
    'theme callback' => 'op_theme', //name of bootstrap extended theme
    'type' => MENU_NORMAL_ITEM,
  );

Outcome
Blank page on admin page
Approach 3 hook_custom_theme
Hook_custom_theme should override any theme with the machine name theme
  function op_reports_custom_theme(){
    return 'op_theme';
  }

Outcome
Blank page on admin page
Ask
So while I appreciate getting stripes on my Drupal white belt, I would really just like to know the best way to make my custom module render output on an admin path.
Answer: All I can suggest is to look at page callbacks that already render on administrative pages (like the ones in core). There should be nothing special between a core or third-party module in this respect.
More thoughts:

You should not call drupal_render() in a page callback. Return the render array and let core do the rendering
No need for 'theme callback' in a menu definition here
Answer: Do not name your access callback op_reports_permission().  The conventional name is op_reports_access().  You accidentally implemented hook_permission(), and I bet you get some warnings when you drush cc all.
I think you have misdiagnosed the problem.  If the table headers are rendering, but not the table body, then I think something is going wrong in generating the table.  You have not shown us the contents of op_reports_form() nor op_reports_table(), and I suspect that is where the problem is.
I have created a test module for this issue at https://github.com/benjifisher/test-drupal-module.  Note that I have tagged two releases:  v1.0.0 is the minimal example, and v1.0.1 uses a custom theme function as in your first approach.  Feel free to send a pull request!
Standard rules of debugging apply.  Make the simplest example you can that reproduces the problem.

These are SQL tables that are not accessible via views which is why I had to make this module.

It may be easier to tell View how to handle these tables by implementing hook_views_data().  A little Google search turns up this blog post.  (I cannot vouch for its accuracy, but it looks like what you need.)


After configuring a Linux kernel, can I safely make bzImage and modules at the same time?

Question: I noticed that my processors were, in total, in use only about 50% of the time while making a Linux kernel.
I usually make the kernel, then make the modules.
I have just started a make bzImage in one terminal and a make modules in another and see that both my processors are in full use. I expect the total compile time will be a lot quicker as I'm compiling in parallel instead of serial.
Are there any "gotya's" that make this unsafe?
Answer: Just use make -j 3 and it should compile in paralell, and will ensure any dependencies are properly handeled, this is the "official" way to do it.
Comment: @asdmin - Because of the way make does paralellism, with <= 4 cores it's better to do N+1, above that there's not as much benefit as IO becomes the bottleneck.
Comment: on a two-core system (50% utilization suggests this) -j 2 would be a better idea. With -j 3, system constantly forced to context changes by enforcing 3 jobs on 2 processor threads. BTW the questioner's correct answer is "make -j 2 bzImage modules"
Answer: And no, you should not start building two objects in the same directory that are likely to try and compile the same code at the same time.


Hyperplane in a reflexive Banach space achieves its minimum norm

Question: Let $X$ be a reflexive Banach space, and $X'$ it's dual space. Let $f \in X'$, $f \neq 0$ and $\alpha\in\mathbb{F}$. The hyperplane in $X$ defined by $f$ and $\alpha$ is the set
$$H:=\{x\in X:f(x)=\alpha\}.$$
Show that there exists a $z\in H$ such that $\inf_{h\in H}\lVert h\rVert=\lVert z\rVert$.
Since we know that $X$ is reflexive I tried using the fact that for every $f \in X'$ there exists an $x \in X$ with $\lVert x \rVert = 1$, such that $f(x) = \lVert f \rVert$, but I still can't prove the fact that $x$ is an element of $H$.
Comment: Does this answer your question? [nonempty closed convex subset of reflexive Banach space achieves its minimum norm](https://math.stackexchange.com/questions/3312973/nonempty-closed-convex-subset-of-reflexive-banach-space-achieves-its-minimum-nor)
Comment: Thanks for the quick response but I'm preferably looking to prove this statement without using weak convergence/weakly closed.
Answer: There is no reason why $f(x)$ should be equal to $\alpha$, and as a consequence, no reason why $x$ should belong to $H$.
Still, your idea is a good starting point. What we can do is find a vector $z$ colinear to $x$ and belonging to $H$. If $z = \lambda x \in H$, then $f(z) = \lambda f(x) = \lambda \|f\| = \alpha$, so the right choice is
$$z = \frac{\alpha}{\|f\|} x.$$
By construction, $z \in H$, and in addition, $\|z\| = \frac{|\alpha| \|x\|}{\|f\|} = \frac{|\alpha|}{\|f\|}$.
All is left is to check that $z$ realizes the minimum to the distance to $0$, or, in other words, that $\|h\| \geq \frac{|\alpha|}{\|f\|}$ whenever $h \in H$. But, for any $h \in H$,
$$\alpha = f(h)$$
$$|\alpha| = |f(h)| \leq \|f\| \|h\|,$$
and thus $\|h\| \geq \frac{|\alpha|}{\|f\|}$, as desired.
Comment: It is a bit disappointing that this issue arises, because 1) the OP had some good ideas on how to tackle this problem, which were ignored ; and 2) the OP clearly commented on why the related thread was not satisfactory, comment which was also ignored.
Comment: Disclosure: I saw this question in my closing queue, marked as duplicate of a similar question for closed convex subsets. It is obviously not a duplicate. The question is more specialized, which also opens different ways of answering it (note that my post would not be a satisfactory answer of the more general question!).


Is there a name to this common state manegement pattern with rxjs? Does it have limitations?

Question: In Angular applications, we typically do something like this to manage shared states:
<code>import { BehaviorSubject } from 'rxjs';

interface User {
  id: number;
}

class UserService {
  private _users$ = new BehaviorSubject([]);

  users$ = this._users$.asObservable();

  deleteUser(user: User) {
    const users = this._users$.getValue();
    this._users$.next(users.filter(user => user.id !== user.id));
  }

  addUser(user: User) {
    const users = this._users$.getValue();
    this._users$.next([...users, user]);
  }

  updateUser(updatedUser: User) {
    const users = this._users$.getValue();
    this._users$.next(users.map(user => user.id === updatedUser.id ? updatedUser : user));
  }
}
</code>
This basically solves the same problem that, fundamentally, Flux-based and Redux-based patterns (like ngRx and redux itself) try to solve: how can we update shared state so that view components can act reactively to changes and will aways be able to show the true current state. But it is simpler than those patterns.
My question is: does this pattern have a known name? Do we have any advantage in using libraries like ngRx(or even redux in react) that would cover any limitation of this pattern?
Comment: I've heard this referred to as "Subject-as-a-Service", although I generally just go with "store pattern" or "redux pattern". Are there advantages to NgRx? I'd say yes: they provide all kinds of optimizations (memoized selectors being a big example) that would take too long to implement and maintain. I strongly advise NgRx over its competitors (like Ngxs or Akita) because I've found it offers the most flexibility once you get over the learning curve.
Answer: That's a valid pattern, and that's why we also have introduced ngrx/component-store (https://ngrx.io/guide/component-store).
The docs also provide pro/cons of both "ways": https://ngrx.io/guide/component-store/comparison


How can I turn one specific audio file on or off with CheckBox or toggle button from one activity to another in android?

Question: import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;

public class Settings_Menu extends Activity {
private MediaPlayer mp;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_settings_menu);

    TurnSoundOff();
}

private void TurnSoundOff() {
    final CheckBox TurnSoundOff= (CheckBox) findViewById(R.id.StartupsoundoffBox);
    TurnSoundOff.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (TurnSoundOff.isChecked()){
                mp = MediaPlayer.create(MainActivity.class, R.raw.soundfile); //errors at .create since I can't use a class
                mp.stop();
            }else{
                mp = MediaPlayer.create(MainActivity.class, R.raw.soundfile);
                mp.start();
            }
        }});
}

}
Here is my code, i'm just trying to shutoff or turn on a designated audio file from when the app opens. I have the Checkbox or toggle button in another activity. I'm using media player and some what new to android coding thanks for reading. I setup a settings action from tapping overflow then the settings button to go to activity and I want the audio shutoff or back on in the MainActivity.xml when the check is click from the settings activity. thanks again for reading and help in advance. It errors at .create since I can't use a class
Answer: You have to do this using shared preferences . It is very simple.. Instead of making an activity make a preference screen.. Follow these steps..:-
1) Go to resource folder.
2) make a new folder called 'xml'.
3) In xml folder you created make a xml file called 'prefs.xml'.
in that sdd the following code..:-
 <PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android" >

<CheckBoxPreference
    android:defaultValue="false"
    android:key="music"
    android:summary="Tick to listen the music"
    android:title="Intro Music" >
</CheckBoxPreference>
</PreferenceScreen>

now go to ur activity that plays the song..
  ourSong = MediaPlayer.create(Splash.this, R.raw.splash_sound);

    SharedPreferences getPrefs = PreferenceManager
            .getDefaultSharedPreferences(getBaseContext());
    boolean music = getPrefs.getBoolean("music", true);
    if (music == true)
        ourSong.start();

    Thread timer = new Thread() {
        public void run() {
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {

            }
        }
    };
    timer.start();

this thread is used for the timer of your activity.. if u dnt want any timer delete the thread.. the value in the sleep(****) is the time in miliseconds.
add this function also to stop the song after the activity is changed..
@Override
protected void onPause() {
    // TODO Auto-generated method stub
    super.onPause();
    finish();
    ourSong.release();
}

To get the overflow menu :-
1)make a new folder called menu
2)make a xml file.. add the following code.
    <?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >

<item android:title="Preferences"
    android:id="@+id/preferences" />
<item android:title="Exit"
    android:id="@+id/exit" />
</menu>

In you actvity add the following code..So that prefernece could be called
@Override
public boolean onCreateOptionsMenu(android.view.Menu menu) {
    // TODO Auto-generated method stub
    super.onCreateOptionsMenu(menu);
    MenuInflater blowUp = getMenuInflater();
    blowUp.inflate(R.menu.cool_menu, menu);
    return true;
}

@Override
public boolean onMenuItemSelected(int featureId, MenuItem item) {
    // TODO Auto-generated method stub
    switch (item.getItemId()) {

    case R.id.preferences:
        Intent b = new Intent("com.example.code.PREFS");
                    //instead of 'com.example.code' write your package name
        startActivity(b);
        break;
    case R.id.exit:
        finish();
        break;
    }
    return false;
}

And in the end make a class called Prefs and add the following code..
import android.os.Bundle;
import android.preference.PreferenceActivity;

   public class Prefs extends PreferenceActivity{

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    addPreferencesFromResource(R.xml.prefs);
}

}

Finally add the class in the manifest.. code for that..
 <activity
        android:name="com.example.code.Prefs"
        android:label="Preferences" >
        <intent-filter>
            <action android:name="com.example.code.PREFS" />

            <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
    </activity>

your action name should be same as u mentioned in the intent in onMenuItemSelected()...
This would do the trick... :) Peace...
Comment: I'm not sure whats going on now, having problem. Is there a video I can watch I had it working but when the button was ticked or unticked sound still played
Comment: Okay now I got it down where should I add the code so preferences can be called which activity?
Comment: dnt forget to tick if u got ur answer.
Comment: I have all code implemented but when I tick to check it still plays the sound when it shouldn't, I have it set as main.xml the file you had me create and its all setup just having a problem with it stopping the sound thanks for your help again.
Comment: i have tested it myself and it is working fine.. but no probs u just give me ur email i will send u the project .. u just need to import it in your eclipse.. :)
Comment: I got it to work thanks I realized it has to be clicked to play the sound thanks! Is there a way to switch this for future preference? Is there a way to have the box checked to turn sound off? currently its check to turn sound on. Thanks again for help!
Comment: In the second code I posted there is a line. If (music==true) change that to if (music == false)..  this may do wht u want..


Multivariable chain rule to solve a third order derivative

Question: I came across this problem and I don't know how I should go about solving it:
"Express $\frac{\partial^3f}{\partial x^2\partial y}f(4x^2 + y, x + 1)$ in terms of partial derivatives of the function f"
I'm having a hard time grasping how these multivariable partial derivatives work. Earlier I had
$f(x, y) = g(u(x,y), v(x,y))$
For which i had to express
$\frac{\partial ^2f}{\partial x\partial y}$
In terms of partial derivatives of g, u and v and I got the following result:
$\frac{\partial ^2g}{\partial x\partial u} \frac{\partial ^2u}{\partial x\partial y} + \frac{\partial ^2g}{\partial x\partial v}\frac{\partial ^2v}{\partial x\partial y}$
But I'm very much doubting that this is correct, considering that I dont really understand this topic yet and my Calculus book doesn't seem to help me understand it.
Answer: Define the auxiliary function $g(x,y)=f(4x^2+y,x+1)$ and let $u=4x^2+y$ and $v=x+1$. Then $g(x,y)=f(u,v)$ and the chain rule give
$$\frac{\partial g}{\partial y}=\frac{\partial f}{\partial u}\frac{\partial u}{\partial y}+\frac{\partial f}{\partial v}\frac{\partial v}{\partial y}=\frac{\partial f}{\partial u}(1)+\frac{\partial f}{\partial v}(0)=\frac{\partial f}{\partial u}$$
Then, \begin{align*}\frac{\partial^2g}{\partial x\partial y}&=\frac{\partial }{\partial x}\left(\frac{\partial g}{\partial y}\right)\\&=\frac{\partial}{\partial x}\left(\frac{\partial f}{\partial u}\right)\\&=\frac{\partial}{\partial u}\left(\frac{\partial f}{\partial u}\right)\frac{\partial u}{\partial x}+\frac{\partial}{\partial v}\left(\frac{\partial f}{\partial u}\right)\frac{\partial v}{\partial x}\\
&=\frac{\partial^2f}{\partial u^2}(8x)+\frac{\partial^2f}{\partial v\partial u}(1)\end{align*}
by the chain rule apply to $\frac{\partial f}{\partial u}$.
Then try to find
\begin{align*}
\frac{\partial^3g}{\partial x^2\partial y}&=\frac{\partial}{\partial x}\left(\frac{\partial^2g}{\partial x\partial y}\right)\\
&=\frac{\partial}{\partial x}\left(\frac{\partial^2f}{\partial u^2}(8x)+\frac{\partial^2f}{\partial v\partial u}(1)\right)
\end{align*}
And use chain rule to $\frac{\partial^2 f}{\partial u^2}$ and $\frac{\partial^2f}{\partial u\partial v}$ and the product rule.
I'll let you fill in the missing details.


C++ protobuf SerializedData

Question: I need to get serializedData (like in C#) in C++ for google::protobuf::FileDescriptor object.
In C++ code I have google::protobuf::FileDescriptor object. And I need to get something like ByteString SerializedData in C# (The original serialized binary form of this descriptor.)
Does anyone know how to do it? Thank you.
Answer: You can use FileDescriptor::CopyTo(FileDescriptorProto * proto) to copy the contents to a FileDescriptorProto, which is a regular Message that you can serialize using any of the SerializeTo... functions.
Comment: By the way. Maybe you know why I have difference between C# and C++ array data? I use: google::protobuf::FileDescriptorProto proto; ... proto.SerializeToArray(arr, size); arr differs from c# array.
Comment: Actually diff is small. C++ data size is 110, C# data size is 107. Most symbols are equals. In the middle of sequence I have difference.
Comment: Try deserializing the proto, then serializing it to text format ([`TextFormat::PrintToString`](https://developers.google.com/protocol-buffers/docs/reference/cpp/google.protobuf.text_format#TextFormat.PrintToString.details)), so you can see what the actual difference is. `protoc` can also do this conversion for you, when passed the path to the original `.proto` files that describe the message (`FileDescriptorProto` etc.).

C++ protobuf SerializedData


How works a string variable parsed into an int

Question: I have a project that I didn't made myself and I'm trying to understand how it works.
In a file, I have this code :
int nbClasses = PersystConfiguration.getInt(PersystConstantes.NB_CLASSES_DISTRIBUTION);

The method getInt is just a method to parse in an int. But I don't understand the attribut NB_CLASSES_DISTRIBUTION of the class PersystConstantes. This class is :
String NB_CLASSES_DISTRIBUTION = "persyst.nb.classes.distribution";

I really don't understand how this string can be parse into an int.
Can somebody help me by telling me how work this kind of variable please ?
Comment: It's very likely fetching a property from somewhere, where `persyst.nb.classes.distribution` is the key and the value is a `String` representing an integer value. You may be able to look for that file (and the value) by grepping for the property key in your resource path. Or it could be some system property set somewhere else. Bottomline, parsing actual `"persyst.nb.classes.distribution"` will throw a `NumberFormatException`, so that's not likely what happens here.
Comment: Why don't you just look inside the `PersystConfiguration.getInt` method and analyze how the String parameter is handled there?
Comment: @Mena You're right, it is a system property. I found a `System.getProperty(key);` where the key is `persyst.nb.classes.distribution`. But where can I found it ? Is it a path or something ? Because I don't find any "distributiion" file :/
Comment: @Erlaunis likely some code actually sets it programmatically: `System.setProperty((String)theKey, (String)theValue)` (although it's not the only way).
Comment: what is `getInt` method ? it really depends on its code.
Answer: The function PersystConfiguration.getInt(String argument1) returns int. Inside the function, its logic must be like, check the argument1 and returns an intcorresponding/according to that. For e-g  the below function definition is possible.
/* Don't Ever Tell anyone I wrote this below code */
    class PersystConfiguration {
        public static Map<String,Integer> Property = new HashMap<String,Integer>();

        public static void setProperties() {
            Property.put("persyst.nb.classes.distribution", 0);
            Property.put("persyst.nb.classes.distribution1", 1);
            Property.put("persyst.nb.classes.distribution2", 2);
        }

        public static int getInt(String argument) {
            return Property.get(argument);
        }
   }


Gradle build running demorando uma eternidade

Question: O Android Studio não está mais copilando o projeto. Já desinstalei e instalei novamente mas não resolve, fica só nessa de "Gradle build running" e nunca finaliza.
22:21:33 Gradle sync started
22:23:58 Gradle sync completed
22:24:00 Executing tasks: [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies]

Também ja fui em "File > Settings Build,Execution,Deployment> Build Tools>" Gradle e habilitei o opção "Offline work" e também não deu nada.
O que faço?
Comment: o nome do dominio é algo como: com.seudominio.seupacote, abre a pasta "app/main/seudominio/seupacote" ai está o nome completo que voce precisa usar, geralmente, o nome do pacote no manifest é o nome do dominio e do pacote composto
Comment: olá @Léo, eu tive esse problema aqui, resolvi ele criando um projeto novo com o mesmo nome e copiando os arquivos e pastas pertinentes do antigo para o novo, por pertinentes digo, os arquivos da pasta "src/main/seudominio/seuprojeto/*.java" e a pasta "res". avisa se funcionou
Comment: Será que vai da algum problema para meus usuários atualizar? meu app está na Play store.
Comment: voce precisa fazer tudo igual, o nome do projeto, o nome do dominio, o nome do pacote, em fim, faz um zerado como se tivesse fazendo pela primeira vez, e tambem lembre-se de por a versão correta e copia a tua signed key, outra coisa importante, melhor se voce copiar do seu gerenciador de arquivos e colar pelo proprio studio, clicando nos locais onde voce quer colar
Comment: infelizmente, a forma como eu consegui resolver isso foi assim, pois tentei de tudo, tentei resetar o cache, apaqguei o sdk, apaguei a pasta ".studio" e nem com uma instalação nova do android studio funcionou, dai fiz isso e resolveu.
Comment: Outra coisa, não lembro bem o nome de domínio do meu App, sabe onde acho em algum  arquivo? só lembro do pacote
Comment: Ok, vou tentar aqui e ti aviso! Obrigado!
Comment: Conseguir resolver aqui e vou postar uma resposta!
Answer: Conseguir resolver esse problema, no Windows 10.
A eternidade mostra um erro no logs em Gradle console.
Então, vá em Meu Computador > Propriedades > Mostrar configurações avançadas > Variável de ambiente.
Clique no botão Novo e coloque os detalhes abaixo:
Nome da Variável: SLAVE_AAPT_TIMEOUT
Valor: 50

Vale lembrar que o Java está sendo bloqueado pelo o firewall, sendo do Windows ou de terceiro. No meu caso, eu uso o anti-vírus Kaspersky Lab, então desativei e quando fui recompilar, o firewall do Windows avisou que o Java queria permissão para acessar internet.

A solução é permitir, então permiti em ambos firewall e a gradle compilou com sucesso em uns 7 minutos!
Comment: De fato @Léo, eu tbn me cansei de camelar com isso e fui atras da solução para linux, o que me resolveu isso, foi instalar as bibliotecas para 32 bits na minha maquina que é 64 bits, dai, o caso é instalar essas libs: `sudo yum install zlib.i686 ncurses-libs.i686 bzip2-libs.i686`, aqui eu uso SCL 7 (RHEL), para uma distro baseado no debian, tem de fazer: `sudo apt-get install libc6:i386 libncurses5:i386 libstdc++6:i386 lib32z1 libbz2-1.0:i386`. dai funcionou redondinho.
Comment: vixe, fica entaum os meus comentários para quem usa outros SO's, por enquanto serve como um atalho para nós que abolimos o windows, pois eu uso linux já de há muito e se alguém aqui tiver uma solução parecida com a do amigo @Leo ae, mas para para os outros sistemas operacionais, seria muito bem vinda
Comment: Eu ia fazer do jeito que você explicou, como vi que era muito trabalhoso, vi um atalho do **Gradle console** e teve as mensagens de erro, foi assim que conseguir resolver. Tenta ver a mensagem de erro e faz uma pergunta, quê alguém que usa Linux deve ti ajudar! Muito obrigado pelo os seus comentários!


How to build a reusable configurable form

Question: How could I build a reusable form that can be reconfigured for each location in which it is used? It would have the same fields, however select list values would be different depending on what the user thinks it should contain based on its location in the site.
Locations include blocks and panels across many pages and sites, and potentially
multiple locations on the same page.
Answer: In a custom module, use the FormAPI to build your form and create variables to store your #options for example (in the case you mentioned of select lists that change). Set the variable according to the context and you should be good to go.
/**
 * Implements hook_form();
 */
function mymodule_form($form, &$form_state) {

  // For inspecting information about entity and id:
  kpr(arg(0));
  kpr(arg(1));

  $form['selected'] = array(
    '#type' => 'select',
    '#title' => t('Selected'),
    '#options' => $variable_according_to_context,
    '#default_value' => $category['selected'],
    '#description' => t('Varies according to context.'),
  return $form;
}

The $variable_according_to_context will hold the options of your select list. You can set this variable to different options according to the context you are in. You can use arg(0) or arg(1) to get the node or entity type the form is in. I hope that was clear enough on how I would approach this.
Comment: In this case, is variable according to context referring to the site location?
Comment: I've edited the answer to give more info about how to get hints on the context the form is in. Hope that helps


Condição com o teclado

Question: Estou querendo fazer uma condição através das teclas que o usuário apertar. Por exemplo, se ele apertar 'ENTER' o script continua e se apertar 'ESC' o script para. Procurei na internet mas nao achei nada específico. Alguma sugestão de biblioteca?
ps: Estou programanndo em Python.
Comment: Você pode usar o biblioteca `keyboard` e definir eventos para cada tecla.
Answer: <code>from pynput import *
from pynput.keyboard import Key, Listener

def on_release(key):
    if key == Key.enter:
        _thread.start_new_thread(iniciar,())
    if key == Key.esc:
        exit()

with Listener(on_release=on_release) as listener:   listener.join()
</code>

Condição com o teclado


Fetching data attributes from instagram hashtag

Question: I want to fetch data(the images in each post) stored in https://www.instagram.com/explore/tags/selfie/?__a=1, but all I get when I decode and var_dump this is NULL.
$obj = json_decode("https://www.instagram.com/explore/tags/selfie/?__a=1", true);
var_dump($obj);

Comment: How do I fetch the "profile_pic_url"?
Answer: Before decoding json you have to first fetch api response.
$obj = json_decode(file_get_contents("https://www.instagram.com/explore/tags/selfie/?__a=1"), true);

Answer: You're trying to json_decode the STRING
https://www.instagram.com/explore/tags/selfie/?__a=1
What you need to do is to fetch the URL first.  I suggest using file_get_contents, which takes a URL and returns the contents at the end of that URL.
Try this:
$json = file_get_contents("https://www.instagram.com/explore/tags/selfie/?__a=1");
$obj = json_decode($json, true);
var_dump($obj);

Comment: That's a different question about traversing a JSON structure.  I'd accept the best answer here, then ask another question for that.
Answer: The argument to the function json_decode(), $html must be plaintext/string.
This should work.
$url = "https://www.instagram.com/explore/tags/selfie/?__a=1";
$html = file_get_contents($url);
$obj = json_decode($html,true);
var_dump($obj);

See this in action here


Cast to the interface when using Socket in Java

Question: I got a really unfathomable problem. So I created two different projects and decided to test my socket applications which tries to send an interface over network. Here is my client side code:
package calculable;

import java.io.*;
import java.net.*;

public class ClientToSendCalculable
{
    public ClientToSendCalculable(int port)
    {
        try
        (
            Socket s = new Socket("localhost", port);
            ObjectOutputStream writer = new ObjectOutputStream(s.getOutputStream());
            ObjectInputStream reader = new ObjectInputStream(s.getInputStream());
        )
        {
            System.out.println("Connection was established!");

            Calculable addition = new Addition(5, 7);

            writer.writeObject(addition);
            double res = (Double)reader.readObject();

            System.out.println(res);
        }
        catch(Exception e)
        {
            e.printStackTrace();
        }
    }

    public static void main(String[] args)
    {
        new ClientToSendCalculable(7777);
    }
}

Here is my server side code:
package calculable;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class ServerToGetCalculable
{
    public ServerToGetCalculable(int port)
    {
        while(true)
        {
            try
                    (
                            ServerSocket ss = new ServerSocket(port);
                            Socket s = ss.accept();
                            ObjectOutputStream writer = new ObjectOutputStream(s.getOutputStream());
                            ObjectInputStream reader = new ObjectInputStream(s.getInputStream());
                    )
            {
                System.out.println("Got a client!");

                Calculable calcObj = (Calculable) reader.readObject();
                double res = calcObj.calc();
                writer.writeObject(res);
            }catch(Exception e)
            {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args)
    {new ServerToGetCalculable(7777);}
}

Here is interface Calculable:
package calculable;

import java.io.Serializable;

public interface Calculable extends Serializable
{
    double calc();
}

I have Calculable interface in both projects. But I have Addition class only in client side project. Here is Addition class:
package calculable;

import java.io.Serializable;

public class Addition implements Calculable, Serializable
{
    private double firstAddendum, secondAddendum;

    public Addition(double firstAddendum, double secondAddendum)
    {
        this.firstAddendum = firstAddendum;
        this.secondAddendum = secondAddendum;
    }

    public double calc()
    {
        return firstAddendum + secondAddendum;
    }
}

When I start server.main class first and client.main class after I got such exceptions:
exception on the server side:
"C:\Program Files\Java\jdk1.8.0_91\bin\java" -Didea.launcher.port=7544 "-Didea.launcher.bin.path=C:\Program Files (x86)\JetBrains\IntelliJ IDEA 2016.3.3\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_91\jre\lib\charsets.jar;C:\Program .....E:\Cloud\JavaIdea\ForCalculablePractice\out\production\ForCalculablePractice;C:\Program Files (x86)\JetBrains\IntelliJ IDEA 2016.3.3\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain calculable.ServerToGetCalculable
Got a client!
java.lang.ClassNotFoundException: calculable.Addition
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:331)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at java.lang.Class.forName0(Native Method)
    at java.lang.Class.forName(Class.java:348)
    at java.io.ObjectInputStream.resolveClass(ObjectInputStream.java:628)
    at java.io.ObjectInputStream.readNonProxyDesc(ObjectInputStream.java:1620)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1521)
    at java.io.ObjectInputStream.readOrdinaryObject(ObjectInputStream.java:1781)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1353)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373)
    at calculable.ServerToGetCalculable.<init>(ServerToGetCalculable.java:24)
    at calculable.ServerToGetCalculable.main(ServerToGetCalculable.java:36)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

exception on the client side:
"C:\Program Files\Java\jdk1.8.0_91\bin\java" -Didea.launcher.port=7545 "-Didea.launcher.bin.path=C:\Program Files (x86)\JetBrains\IntelliJ IDEA 2016.3.3\bin" -Dfile.encoding=UTF-8 -classpath "C:\Program Files\Java\jdk1.8.0_91\jre\lib\charsets.jar;.....E:\Cloud\JavaIdea\SocketPractice\out\production\SocketPractice;C:\Program Files (x86)\JetBrains\IntelliJ IDEA 2016.3.3\lib\idea_rt.jar" com.intellij.rt.execution.application.AppMain calculable.ClientToSendCalculable
Connection was established!
java.io.EOFException
    at java.io.ObjectInputStream$BlockDataInputStream.peekByte(ObjectInputStream.java:2626)
    at java.io.ObjectInputStream.readObject0(ObjectInputStream.java:1321)
    at java.io.ObjectInputStream.readObject(ObjectInputStream.java:373)
    at calculable.ClientToSendCalculable.<init>(ClientToSendCalculable.java:22)
    at calculable.ClientToSendCalculable.main(ClientToSendCalculable.java:34)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)

Process finished with exit code 0

Answer: You do not send interfaces - that is a misconception on your end. The fact that you put down:
Calculable addition = new Addition(5, 7);

doesn't mean that you put an "interface" object on the wire.
You send a serialized object. That objects contains a hard link to its specific class. See here for more details.
You can't fix this in code. You have to make sure that the **class* of your serialized object is available to the JVM where you intend to de-serialize. It is that simple.
Comment: Can you provide me with an appropriate code changes that I have to do in order for my program to work with server and client being in different projects, please?
Comment: @Yaroslav Just copy your addition class.
Comment: @GhostCat, I just upvoted. Thanks a lot for the help!
Answer: You're sending an object that the server has no knowledge of.  You need add the class files for for the additions object, including Addition and Calculable to the server's classpath (or your project if using an IDE).


Help with, finding x from :$ 3\sin(x) + 4\cos(x) = 5$ , using $A \sin(x + \theta)$

Question: I am having lots of trouble following my notes , the answer I have is :
$$x= - \left(\arctan{\frac{4}{3}}\right) + \left(\frac{\pi}{2}\right) + 2n\pi,n = 0 \pm 1 \pm 2\dots$$
How I have arrived at this point is very vague to me, I realise this is a fairly long question, therefore If writing it out is too long, please can somebody attach a link to a video or website showing how to do it step by step.
To give an idea of what I am already familiar with
I have been using this to try to get to the answer.

However after getting to $$5\sin(x + 53.1)$$
The next line is
 $$5\sin(x + 53.1) = \left(\frac{1}{5}\right)$$
then
$$x + 53.1 = \left(\frac{\pi}{2}\right) n\pi$$
then
$$x= - \left(\arctan{\frac{4}{3}}\right) + \left(\frac{\pi}{2}\right) + 2n\pi $$
It is these three lines of work I am unfamiliar with.
As my tutor has not specified what this kind of question is called I find it difficult to search for online.
Any help is greatly appreciated.
Comment: Related : http://math.stackexchange.com/questions/757497/how-to-solve-4-sin-theta-3-cos-theta-5
Answer: you have $$ \sin x \; \; \cdot \frac{3}{5} + \cos x \; \; \cdot \frac{4}{5} = 1. $$
Since
$$ \left( \frac{3}{5} \right)^2 +  \left( \frac{4}{5} \right)^2 = \frac{25}{25} = 1, $$ we know there is an angle $\theta$ with
$$ \cos \theta =   \frac{3}{5} , \; \;  \sin \theta =   \frac{4}{5} .$$ in fact,
$$ \tan \theta = (4/5)/ (3/5) = 4/3, $$ and
$$  \theta = \arctan \frac{4}{3}.  $$ Then your original is
$$ \sin x \cos \theta + \cos x \sin \theta = 1, $$
$$ \sin \left( x + \theta \right) = 1. $$
So far, we have
$$ \sin \left( x + \arctan \frac{4}{3} \right) = 1. $$
The sine of something can be equal to $1$ when the thing is $\pi/2,$ or $5 \pi/2,$ or $-3\pi/2,$ in general $\frac{\pi}{2} + 2 n \pi.$ Meaning that the collection of values of $x$ becomes
$$  x + \arctan \frac{4}{3} = \frac{\pi}{2} + 2 n \pi$$ with integer $n,$ and
$$  x = - \arctan \frac{4}{3} + \frac{\pi}{2} + 2 n \pi$$
At this point i would add the fact that
$$  \frac{\pi}{2} - \arctan \frac{4}{3} =  \arctan \frac{3}{4}, $$
so that we can write
$$ \color{blue}{ x =   \arctan \frac{3}{4} + 2 n \pi }$$
Show you how to confirm: given
$$ \beta =  \arctan \frac{3}{4}, $$
let us use the identity
$$ 1 + \tan^2 \beta = \operatorname{sec}^2 \beta,   $$ giving
$$ 1 + \left(  \frac{3}{4} \right)^2 = \operatorname{sec}^2 \beta. $$ Then
$$   \frac{25}{16} = \operatorname{sec}^2 \beta, $$
$$   \frac{16}{25} = \cos^2 \beta. $$ Since $\beta$ is in the first quadrant,
$$ \cos \beta = \frac{4}{5}, $$ therefore
$$ \sin \beta = \frac{3}{5}. $$ Then
$$ x = \beta + 2 n \pi, $$
$$ \cos x = \frac{4}{5}, $$
$$ \sin x = \frac{3}{5}. $$
$$ 3 \sin x + 4 \cos x = 3 \frac{3}{5} + 4 \frac{4}{5} = \frac{25}{5} = 5 $$
Answer: You have $\frac 35\sin x+\frac 45\cos x=1$ which is $\sin x\cos \alpha+\cos x\sin \alpha=1$ where $\alpha$ is the angle in the figure below whose tangent is equal to $\frac43$.

Furthermore you know that $\sin x\cos \alpha+\cos x\sin \alpha=\sin (\alpha+x)$
You have then $\alpha+x=\frac {\pi}{2}+2n\pi$ and $x= -tan^{-1}(4/3) + (π/2) + 2nπ$


about integral logarithm

Question: I would to ask for a logarithm integral, used for Gauss. I read that he uses it to calculate the number of primes, less than a given natural number. It is like:
$Li= \int_{0}^x(dt/lnt)$
I read that he uses this to calculate these quantities, but I don't know
which kind of expression results from this integral. Some aproximation?
thanks a lot!
Comment: It's not clear what you're asking for.  $li(x) = \int_0^x \frac{dt}{\ln(t)}$ is the [logarithmic integral function](https://en.wikipedia.org/wiki/Logarithmic_integral_function).  What do you want to know about it?
Answer: Yes we can approximate it:
$$\text{li} (e^x)=\text{Pv} \int_{0}^{e^x} \frac{1}{\ln t} dt$$
$$\text{li} (e^x)=\lim_{\epsilon \to 0^+} \left(\int_{0}^{1-\epsilon} \frac{dt}{\ln t} +\int_{1+\epsilon}^{e^x} \frac{dt}{\ln t}\right)$$
Now the substitution $t=e^x$ so $dt=e^xdx$. Note I did a mistake before with the bounds as it is a bit hard to see but let's say $e^x=1=t$ then $x=\ln 1$:
$$\text{li} (t)=\lim_{\epsilon_0 \to 0^+} \left(\int_{-\infty}^{-\epsilon_0} \frac{e^x}{x}dx +\int_{\epsilon_0}^{\ln t} \frac{e^x}{x} dx\right)$$
And Taylor series yields:
$$\text{li}(t)=\gamma+\ln |\ln t|+\sum_{n=1}^{\infty} \frac{(\ln t)^n}{n(n!)}$$
Which holds for $t >0$ note $t=e^x>0$.
Comment: I guess in a sense it comes from a cancellation around the singularity at $x=1$.  Notice that the left endpoint did not properly get substituted.
Comment: What's the $+c$ for?  It's a definite integral.
Comment: thanks a lot, now I need a lot of time to underestand everyting.

about integral logarithm


MySQL: One database slave, multiple masters

Question: My question is:
Am I able to have one database server as slave to more than one master servers with different databases. So for example:

DB-Server-1 contains database Apple
DB-Server-2 contains database Banana
I want to replicate them to my DB-Server-3 as Apple-Slave and Banana-Slave

If I'm able, can you tell me how to achieve this with MySQL 5.7?
Answer: In MySQL jargon that is called "multi-source replication" and that is a supported configuration in MySQL 5.7.
The MySQL manual comes with a complete tutorial:
https://dev.mysql.com/doc/refman/5.7/en/replication-multi-source.html

MySQL Multi-Source Replication enables a replication slave to receive transactions from multiple sources simultaneously. Multi-source replication can be used to:

back up multiple servers to a single server,
to merge table shards,
consolidate data from multiple servers to a single server.

Multi-source replication does not implement any conflict detection or resolution when applying the transactions, and those tasks are left to the application if required. In a multi-source replication topology, a slave creates a replication channel for each master that it should receive transactions from.

etc.


Loading nodes that are only available to the current user

Question: How do I programmatically load nodes that are available to the current user?
I used node_load_multiple(), but it seems to directly load nodes from the database, bypassing permissions.
Answer: You need to use the EntityFieldQuery class. The following is example code to load all the published nodes whose content type is Article.
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED);

$result = $query->execute();
if (isset($result['node'])) {
  $nids = array_keys($result['node']);
  $nodes = entity_load('node', $nids);
}

EntityFieldQuery returns only the nodes to which the currently logged-in user has access. In the case you would get all the nodes for which you know the author user ID, you should use the following code.
$query = new EntityFieldQuery();
$query->entityCondition('entity_type', 'node')
  ->entityCondition('bundle', 'article')
  ->propertyCondition('status', NODE_PUBLISHED)
  ->propertyCondition('uid', $uid);

$result = $query->execute();
if (isset($result['node'])) {
  $nids = array_keys($result['node']);
  $nodes = entity_load('node', $nids);
}

That code returns all the nodes created in the site. To get only 10 nodes, it sufficient to add a call to $query->range(0, 10) before calling $query->execute().


Licence billing

Question: My question is regarding the recurring payment for drupal commerce.
I use Commerce Licence with 'Licence role' and Commerce Licence Billing to make my users pay for a monthly subscription.
The question I have is, how does the recurring system work?

Does the licence Role expire after given time, but gets re-acitvated if a payment is made?
Does the recurring payment happen automatically, or does my user have to buy a licence every month?
Does the previous question depend on my "Payment Gateway"?

What I want to do is make my users buy a licence(Role) once, and then never have to buy a licence again.  But they have to pay a monthly fee otherwise the licence will expire.  So in other words the site much purchase a licence for the user in the background when the previous one expires, but charge them the monthly fee.
It's a tedious process to go and buy a licence(role) every month to keep using the site.
Thanks
Answer: I discovered this module today and i am having same questions :) I have understand quite things.
A partof the answer in the documentation of the module :
After a license is renewed, the queue "commerce_license_billing_cycle_close" will set the "Recurring: Payment pending" status to the order.
<code>$order->status = 'recurring_payment_pending';
commerce_order_save($order);
</code>
If you use commerce card on file module, a default rules will try to charge the user credit card and then the Order will have a "Completed" status.
Otherwise, user will have to pay line items through the site to have the order completed.
To answer your first question, if i understand, the module will renew license without manage the payment but will create corresponding orders with a specific status. Either you charge your client with a specific rule or tell your client to pay different orders.
For the second question, your customer will get the license every months automatically and will have to pay (if you don't do it via a rule) after.

Licence billing