qid int64 1 74.7M | question stringlengths 15 58.3k | date stringlengths 10 10 | metadata list | response_j stringlengths 4 30.2k | response_k stringlengths 11 36.5k |
|---|---|---|---|---|---|
5,724 | I studied math and economics at a poorly ranked university, and I will graduate in the near future. I have a position lined up at a prestigious, data-heavy research institution, where I'll work with numerous economists for a few years before applying to top PhD programs (Berkeley, Chicago, MIT, Harvard, etc.) I took two courses in analysis and did well, although per the quality of my institution, the courses were not challenging.
I also worked as a research assistant and conducted self-guided researched (not published outside my university), so I have several professors willing to write detailed recommendations for me. Apart from a few hiccups in non math/econ courses, my grades are perfect.
Will the fact that my undergraduate degree comes from an unranked institution affect my chances of attending a top PhD program? Will it affect my chances even though my experience after undergrad should speak in my favor? | 2012/12/13 | [
"https://academia.stackexchange.com/questions/5724",
"https://academia.stackexchange.com",
"https://academia.stackexchange.com/users/4317/"
] | I have been in your situation several years ago (in 2011). I graduated BA in Economics and Business Adminsitration from anranked university from one of the developing countries in Eastern Europe. But then I enrolled in Master's Program where I had a chance to meet highly respected Economists who were professors in US programs as well. Neither my Master's Program was ranked. They were just funded by the World Bank and had enough money to invite US professors. By getting As and A-s in all of their courses and being engaged with the professors I earned quite good reputation and showed them that I was motivated and knowledgeable enough to study in some 30-40 US programs. Despite the fact that my school was not ranked after getting recommendation letters from these well-known US professors I was admitted in top 30 programs in the US.
The take away from my story is that the rank of the university does not as far as you get strong recommendation letters from well-known and well-published economists, researchers. | I would advise to develop a relationship via email with professors at your target schools. Dig in and learn about their research and show how interested you are in working with them. Also target assistant and associate professors at those schools as they are more likely to be in the admissions committee paying their dues. They might be the difference if everything else is good.
I know Penn accepts some students from schools I had never heard at all. They try to diversify, just the odds might be different. |
43,983,161 | There are a lot of questions regarding this on here and none of them specifically answers it.
---
I used `git log` and I want to go back to a specific commit without removing any previous history. I just want to create a new commit of that old revision.
I read the answers on here and most of them said to use `git reset HARD <commit hash>`, however, other answers said not to use this as it is not good practice since it will remove history.
I also used `git checkout <commit hash>` and that is only a read only option.
All I want to do is go back to a previous commit without altering any previous history.
[per Q&A in comments, edited somewhat]
>
> * Q: *If you have commits "A, B, C, D, E" and HEAD is now at E, and you want HEAD to be at C, do you want "A, B, C" or do you want "A, D, E, B, C"?*
> * A: It should still exist and remain the same so my new published work will be "A, B, C, D, E, C" where C is HEAD now.
>
>
> | 2017/05/15 | [
"https://Stackoverflow.com/questions/43983161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7143216/"
] | ### TL;DR answer
Make sure your repository is clean (`git status` says nothing to commit, etc), and that you are at the top of your work-tree (where the hidden `.git` directory lives). Then:
```
git checkout master
git rm -rf -- . # remove it all: the scary step :-)
git checkout <hash-of-C> -- . # but this puts everything back
git commit
```
(for the last command, you can optionally add `-C <hash-of-C>` again, to re-use `C`'s log message). Use `git log` or similar to find a suitable hash ID for commit `C`.
There's a slightly shorter way, and in a lot of cases you don't need the `git rm -rf -- .` step at all, but I'll leave that for after the explanation.
There are several other ways to do this, but the above is the most straightforward.
### Explanation
Git is all about *adding new commits* while *keeping everything already committed, forever*.
Hence, suppose you have a repository with just five commits, which you made by starting with one commit `A`:
```
A <--master
```
and then adding a second commit `B` that looks back at `A`:
```
A <-B <--master
```
and then a third commit `C`:
```
A <-B <-C <--master
```
and so on to eventually end up with:
```
A--B--C--D--E <-- master
```
In each case here, we've used a single-uppercase-letter ID (A, B, ... Z) for our commits, which means we'd run out after just 26. Git uses those incomprehensible hash IDs instead, so it will [never run out of unique IDs for its objects](https://stackoverflow.com/a/34804006/1256452), but the downside is that they're incomprehensible and we have to just cut-and-paste them or whatever. Moreover, *Git* assigns them; we have no control over the hash IDs; we just make commits and suddenly there's a new hash.
Note also that `A` does not point to *any* earlier commit, because it *can't:* there is no earlier commit. All other commits, however, point back to their parent. The name `master` simply points to the latest commit on branch `master`. That, in fact, is how Git knows that it's the latest commit—and how Git finds the earlier commits, too!
Again, Git is all about *adding new commits*. If you have seen some of the Star Trek episodes with [the Borg](https://en.wikipedia.org/wiki/Borg_(Star_Trek)), I like to call Git the Borg of Source Control: when you commit, it will add your technological distinctiveness to its collective. You run `git commit`, Git saves everything in the new commit, and Git makes the current branch (`master`, in this case) point to the new commit. The new commit automatically points back to whatever *was* the tip of the branch before.
What you want, then, is to make a new commit that "looks just like `C`" except for one thing: it points back to `E`, rather than to `C`. All the rest then happens automatically:
```
A--B--C--D--E--C' <-- master
```
where the name `C'` means "looks and smells a lot like `C`, but not quite the same" (because it points back to `E`, not to `B`—and it probably has a different date-stamp too).
That's all fine for defining the goal, but how do you make this new commit that "looks and smells a lot like C"? Well, each commit has an attached *source tree*. When you make a commit, Git turns what Git calls the *index* into the attached source tree. This is why you have to `git add` things after you edit them in your work-tree: `git add` means "copy the updated version I put in my work-tree, into the index." This overwrites the old, un-edited index version, so now the updated file is ready to commit.
This is a key fact about Git: **The index is where you build the *next* commit you will make.**
In normal usage, you just `git checkout` a branch, which sets your index and work-tree to match the *tip commit* of that branch—such as `E` for `master`. Then you edit some file(s), `git add` them to copy them back into this hidden index, and `git commit` to make the new commit out of them.
In *this* case, though, you want to get all your files back *the way they were at commit `C`*. The `git checkout` command can do this: instead of:
```
git checkout <hash-or-branch>
```
we need the longer form (which ideally should have been a different Git command, but it isn't):
```
git checkout <hash-or-branch> -- <files>
```
This tells Git: *go look in the hash I gave you* (if you give it a branch name, it turns the branch name into a hash ID) *and then copy each of its files to my work-tree, writing that file "through" the index*.
If your commit `C` has six files (`README` and five others), each of those files is copied into the index and then on into your work-tree. So now your work-tree `README`, and the other files, are updated to match commit `C`. They're also already staged for committing: you don't have to `git add` them to the index because `git checkout` copied them *through* the index.
The reason we might need to `git rm -rf -- .` first is that commit `E` might have *seven* files: maybe in `D` or `E`, you `git add`-ed a file `new.ext` that didn't exist in commit `C`. If that's the case, `git checkout <hash-of-C> -- .` won't remove `new.ext` at all. Hence, we do a first pass to empty out the index and work-tree entirely, so that the `git checkout <hash-of-C> -- .` re-populates the index and work-tree from commit `C` without leaving anything behind from `E`.
Now you're ready to commit as usual, making a new commit as usual. Adding the `-C` flag to `git commit` tells Git to retrieve the initial commit message from an existing commit (it's a bit of eerie or maybe sad coincidence that we're copying a commit we have been calling `C`, and using a `-C` flag, but it's just coincidence).
Note that if you now `git show` this new commit `C'`, what Git will do is extract commit `E`, then extract `C'`, and then diff the two. What you will get is Git's instructions for "how to convert the contents of commit `E` into the contents of commit `C`". This is another key item about Git: **a `git diff *old* *new*` produces a set of instructions, Git's way of telling you how to convert commit *`old`* into commit *`new`*.** It's not necessarily how *you* did it, it's just some way *to* do it. When you compare adjacent commits, like `A`-vs-`B` or `D`-vs-`E`, you see an approximation of what you did. When you compare distant ones, like `A` vs `E`, you get Git's description of how to go straight from `A` to `E`. But each commit itself has a complete snapshot of *every* file, as it was in the index at the time you ran `git commit`.
### The slightly shorter way
If you've read this far, you might want to know a short-cut that avoids doing `git rm -rf -- .`. Instead of the four commands above, we can use three:
```
git checkout master
git read-tree --reset -u <hash-of-C>
git commit
```
The first and last are the same; it's the middle one that's mysterious. The `git read-tree` command is an internal Git command—one of what Git calls *plumbing* commands, meant for use in scripts—that manipulates the index, given particular commit or tree hash IDs (really, anything that Git can *convert to* a tree hash). The `--reset` option means "throw out the current index and replace it with the result of reading". The `-u` flag means "update the work-tree based on what happened in the index."
This means that if there are seven files in the index now, but the commit we read has just six, Git will *remove* the extra file (from the index and, with `-u`, the work-tree). So it accomplishes the removal as well as the refilling, all in one step. | If you only want to revisit a specific commit, then use `git checkout <SHA>`. From there you'll enter into **detached HEAD** mode, which won't alter your commit history at all.
If you want to save your changes, you'll need to create a branch based on that specific SHA with `git checkout -b`. |
43,983,161 | There are a lot of questions regarding this on here and none of them specifically answers it.
---
I used `git log` and I want to go back to a specific commit without removing any previous history. I just want to create a new commit of that old revision.
I read the answers on here and most of them said to use `git reset HARD <commit hash>`, however, other answers said not to use this as it is not good practice since it will remove history.
I also used `git checkout <commit hash>` and that is only a read only option.
All I want to do is go back to a previous commit without altering any previous history.
[per Q&A in comments, edited somewhat]
>
> * Q: *If you have commits "A, B, C, D, E" and HEAD is now at E, and you want HEAD to be at C, do you want "A, B, C" or do you want "A, D, E, B, C"?*
> * A: It should still exist and remain the same so my new published work will be "A, B, C, D, E, C" where C is HEAD now.
>
>
> | 2017/05/15 | [
"https://Stackoverflow.com/questions/43983161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7143216/"
] | ### TL;DR answer
Make sure your repository is clean (`git status` says nothing to commit, etc), and that you are at the top of your work-tree (where the hidden `.git` directory lives). Then:
```
git checkout master
git rm -rf -- . # remove it all: the scary step :-)
git checkout <hash-of-C> -- . # but this puts everything back
git commit
```
(for the last command, you can optionally add `-C <hash-of-C>` again, to re-use `C`'s log message). Use `git log` or similar to find a suitable hash ID for commit `C`.
There's a slightly shorter way, and in a lot of cases you don't need the `git rm -rf -- .` step at all, but I'll leave that for after the explanation.
There are several other ways to do this, but the above is the most straightforward.
### Explanation
Git is all about *adding new commits* while *keeping everything already committed, forever*.
Hence, suppose you have a repository with just five commits, which you made by starting with one commit `A`:
```
A <--master
```
and then adding a second commit `B` that looks back at `A`:
```
A <-B <--master
```
and then a third commit `C`:
```
A <-B <-C <--master
```
and so on to eventually end up with:
```
A--B--C--D--E <-- master
```
In each case here, we've used a single-uppercase-letter ID (A, B, ... Z) for our commits, which means we'd run out after just 26. Git uses those incomprehensible hash IDs instead, so it will [never run out of unique IDs for its objects](https://stackoverflow.com/a/34804006/1256452), but the downside is that they're incomprehensible and we have to just cut-and-paste them or whatever. Moreover, *Git* assigns them; we have no control over the hash IDs; we just make commits and suddenly there's a new hash.
Note also that `A` does not point to *any* earlier commit, because it *can't:* there is no earlier commit. All other commits, however, point back to their parent. The name `master` simply points to the latest commit on branch `master`. That, in fact, is how Git knows that it's the latest commit—and how Git finds the earlier commits, too!
Again, Git is all about *adding new commits*. If you have seen some of the Star Trek episodes with [the Borg](https://en.wikipedia.org/wiki/Borg_(Star_Trek)), I like to call Git the Borg of Source Control: when you commit, it will add your technological distinctiveness to its collective. You run `git commit`, Git saves everything in the new commit, and Git makes the current branch (`master`, in this case) point to the new commit. The new commit automatically points back to whatever *was* the tip of the branch before.
What you want, then, is to make a new commit that "looks just like `C`" except for one thing: it points back to `E`, rather than to `C`. All the rest then happens automatically:
```
A--B--C--D--E--C' <-- master
```
where the name `C'` means "looks and smells a lot like `C`, but not quite the same" (because it points back to `E`, not to `B`—and it probably has a different date-stamp too).
That's all fine for defining the goal, but how do you make this new commit that "looks and smells a lot like C"? Well, each commit has an attached *source tree*. When you make a commit, Git turns what Git calls the *index* into the attached source tree. This is why you have to `git add` things after you edit them in your work-tree: `git add` means "copy the updated version I put in my work-tree, into the index." This overwrites the old, un-edited index version, so now the updated file is ready to commit.
This is a key fact about Git: **The index is where you build the *next* commit you will make.**
In normal usage, you just `git checkout` a branch, which sets your index and work-tree to match the *tip commit* of that branch—such as `E` for `master`. Then you edit some file(s), `git add` them to copy them back into this hidden index, and `git commit` to make the new commit out of them.
In *this* case, though, you want to get all your files back *the way they were at commit `C`*. The `git checkout` command can do this: instead of:
```
git checkout <hash-or-branch>
```
we need the longer form (which ideally should have been a different Git command, but it isn't):
```
git checkout <hash-or-branch> -- <files>
```
This tells Git: *go look in the hash I gave you* (if you give it a branch name, it turns the branch name into a hash ID) *and then copy each of its files to my work-tree, writing that file "through" the index*.
If your commit `C` has six files (`README` and five others), each of those files is copied into the index and then on into your work-tree. So now your work-tree `README`, and the other files, are updated to match commit `C`. They're also already staged for committing: you don't have to `git add` them to the index because `git checkout` copied them *through* the index.
The reason we might need to `git rm -rf -- .` first is that commit `E` might have *seven* files: maybe in `D` or `E`, you `git add`-ed a file `new.ext` that didn't exist in commit `C`. If that's the case, `git checkout <hash-of-C> -- .` won't remove `new.ext` at all. Hence, we do a first pass to empty out the index and work-tree entirely, so that the `git checkout <hash-of-C> -- .` re-populates the index and work-tree from commit `C` without leaving anything behind from `E`.
Now you're ready to commit as usual, making a new commit as usual. Adding the `-C` flag to `git commit` tells Git to retrieve the initial commit message from an existing commit (it's a bit of eerie or maybe sad coincidence that we're copying a commit we have been calling `C`, and using a `-C` flag, but it's just coincidence).
Note that if you now `git show` this new commit `C'`, what Git will do is extract commit `E`, then extract `C'`, and then diff the two. What you will get is Git's instructions for "how to convert the contents of commit `E` into the contents of commit `C`". This is another key item about Git: **a `git diff *old* *new*` produces a set of instructions, Git's way of telling you how to convert commit *`old`* into commit *`new`*.** It's not necessarily how *you* did it, it's just some way *to* do it. When you compare adjacent commits, like `A`-vs-`B` or `D`-vs-`E`, you see an approximation of what you did. When you compare distant ones, like `A` vs `E`, you get Git's description of how to go straight from `A` to `E`. But each commit itself has a complete snapshot of *every* file, as it was in the index at the time you ran `git commit`.
### The slightly shorter way
If you've read this far, you might want to know a short-cut that avoids doing `git rm -rf -- .`. Instead of the four commands above, we can use three:
```
git checkout master
git read-tree --reset -u <hash-of-C>
git commit
```
The first and last are the same; it's the middle one that's mysterious. The `git read-tree` command is an internal Git command—one of what Git calls *plumbing* commands, meant for use in scripts—that manipulates the index, given particular commit or tree hash IDs (really, anything that Git can *convert to* a tree hash). The `--reset` option means "throw out the current index and replace it with the result of reading". The `-u` flag means "update the work-tree based on what happened in the index."
This means that if there are seven files in the index now, but the commit we read has just six, Git will *remove* the extra file (from the index and, with `-u`, the work-tree). So it accomplishes the removal as well as the refilling, all in one step. | Have you thought about just checking out the commit in question?
```
git checkout sv6e5uj566
```
where `sv6e5uj566` is replaced with the hash of the commit you're interested in. Then you can create a branch from there with
```
git checkout -b your-new-branch-name
```
and start making changes from there. This won't affect your history at all, but allows you to go back to that specific commit and branch from there. |
43,983,161 | There are a lot of questions regarding this on here and none of them specifically answers it.
---
I used `git log` and I want to go back to a specific commit without removing any previous history. I just want to create a new commit of that old revision.
I read the answers on here and most of them said to use `git reset HARD <commit hash>`, however, other answers said not to use this as it is not good practice since it will remove history.
I also used `git checkout <commit hash>` and that is only a read only option.
All I want to do is go back to a previous commit without altering any previous history.
[per Q&A in comments, edited somewhat]
>
> * Q: *If you have commits "A, B, C, D, E" and HEAD is now at E, and you want HEAD to be at C, do you want "A, B, C" or do you want "A, D, E, B, C"?*
> * A: It should still exist and remain the same so my new published work will be "A, B, C, D, E, C" where C is HEAD now.
>
>
> | 2017/05/15 | [
"https://Stackoverflow.com/questions/43983161",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7143216/"
] | ### TL;DR answer
Make sure your repository is clean (`git status` says nothing to commit, etc), and that you are at the top of your work-tree (where the hidden `.git` directory lives). Then:
```
git checkout master
git rm -rf -- . # remove it all: the scary step :-)
git checkout <hash-of-C> -- . # but this puts everything back
git commit
```
(for the last command, you can optionally add `-C <hash-of-C>` again, to re-use `C`'s log message). Use `git log` or similar to find a suitable hash ID for commit `C`.
There's a slightly shorter way, and in a lot of cases you don't need the `git rm -rf -- .` step at all, but I'll leave that for after the explanation.
There are several other ways to do this, but the above is the most straightforward.
### Explanation
Git is all about *adding new commits* while *keeping everything already committed, forever*.
Hence, suppose you have a repository with just five commits, which you made by starting with one commit `A`:
```
A <--master
```
and then adding a second commit `B` that looks back at `A`:
```
A <-B <--master
```
and then a third commit `C`:
```
A <-B <-C <--master
```
and so on to eventually end up with:
```
A--B--C--D--E <-- master
```
In each case here, we've used a single-uppercase-letter ID (A, B, ... Z) for our commits, which means we'd run out after just 26. Git uses those incomprehensible hash IDs instead, so it will [never run out of unique IDs for its objects](https://stackoverflow.com/a/34804006/1256452), but the downside is that they're incomprehensible and we have to just cut-and-paste them or whatever. Moreover, *Git* assigns them; we have no control over the hash IDs; we just make commits and suddenly there's a new hash.
Note also that `A` does not point to *any* earlier commit, because it *can't:* there is no earlier commit. All other commits, however, point back to their parent. The name `master` simply points to the latest commit on branch `master`. That, in fact, is how Git knows that it's the latest commit—and how Git finds the earlier commits, too!
Again, Git is all about *adding new commits*. If you have seen some of the Star Trek episodes with [the Borg](https://en.wikipedia.org/wiki/Borg_(Star_Trek)), I like to call Git the Borg of Source Control: when you commit, it will add your technological distinctiveness to its collective. You run `git commit`, Git saves everything in the new commit, and Git makes the current branch (`master`, in this case) point to the new commit. The new commit automatically points back to whatever *was* the tip of the branch before.
What you want, then, is to make a new commit that "looks just like `C`" except for one thing: it points back to `E`, rather than to `C`. All the rest then happens automatically:
```
A--B--C--D--E--C' <-- master
```
where the name `C'` means "looks and smells a lot like `C`, but not quite the same" (because it points back to `E`, not to `B`—and it probably has a different date-stamp too).
That's all fine for defining the goal, but how do you make this new commit that "looks and smells a lot like C"? Well, each commit has an attached *source tree*. When you make a commit, Git turns what Git calls the *index* into the attached source tree. This is why you have to `git add` things after you edit them in your work-tree: `git add` means "copy the updated version I put in my work-tree, into the index." This overwrites the old, un-edited index version, so now the updated file is ready to commit.
This is a key fact about Git: **The index is where you build the *next* commit you will make.**
In normal usage, you just `git checkout` a branch, which sets your index and work-tree to match the *tip commit* of that branch—such as `E` for `master`. Then you edit some file(s), `git add` them to copy them back into this hidden index, and `git commit` to make the new commit out of them.
In *this* case, though, you want to get all your files back *the way they were at commit `C`*. The `git checkout` command can do this: instead of:
```
git checkout <hash-or-branch>
```
we need the longer form (which ideally should have been a different Git command, but it isn't):
```
git checkout <hash-or-branch> -- <files>
```
This tells Git: *go look in the hash I gave you* (if you give it a branch name, it turns the branch name into a hash ID) *and then copy each of its files to my work-tree, writing that file "through" the index*.
If your commit `C` has six files (`README` and five others), each of those files is copied into the index and then on into your work-tree. So now your work-tree `README`, and the other files, are updated to match commit `C`. They're also already staged for committing: you don't have to `git add` them to the index because `git checkout` copied them *through* the index.
The reason we might need to `git rm -rf -- .` first is that commit `E` might have *seven* files: maybe in `D` or `E`, you `git add`-ed a file `new.ext` that didn't exist in commit `C`. If that's the case, `git checkout <hash-of-C> -- .` won't remove `new.ext` at all. Hence, we do a first pass to empty out the index and work-tree entirely, so that the `git checkout <hash-of-C> -- .` re-populates the index and work-tree from commit `C` without leaving anything behind from `E`.
Now you're ready to commit as usual, making a new commit as usual. Adding the `-C` flag to `git commit` tells Git to retrieve the initial commit message from an existing commit (it's a bit of eerie or maybe sad coincidence that we're copying a commit we have been calling `C`, and using a `-C` flag, but it's just coincidence).
Note that if you now `git show` this new commit `C'`, what Git will do is extract commit `E`, then extract `C'`, and then diff the two. What you will get is Git's instructions for "how to convert the contents of commit `E` into the contents of commit `C`". This is another key item about Git: **a `git diff *old* *new*` produces a set of instructions, Git's way of telling you how to convert commit *`old`* into commit *`new`*.** It's not necessarily how *you* did it, it's just some way *to* do it. When you compare adjacent commits, like `A`-vs-`B` or `D`-vs-`E`, you see an approximation of what you did. When you compare distant ones, like `A` vs `E`, you get Git's description of how to go straight from `A` to `E`. But each commit itself has a complete snapshot of *every* file, as it was in the index at the time you ran `git commit`.
### The slightly shorter way
If you've read this far, you might want to know a short-cut that avoids doing `git rm -rf -- .`. Instead of the four commands above, we can use three:
```
git checkout master
git read-tree --reset -u <hash-of-C>
git commit
```
The first and last are the same; it's the middle one that's mysterious. The `git read-tree` command is an internal Git command—one of what Git calls *plumbing* commands, meant for use in scripts—that manipulates the index, given particular commit or tree hash IDs (really, anything that Git can *convert to* a tree hash). The `--reset` option means "throw out the current index and replace it with the result of reading". The `-u` flag means "update the work-tree based on what happened in the index."
This means that if there are seven files in the index now, but the commit we read has just six, Git will *remove* the extra file (from the index and, with `-u`, the work-tree). So it accomplishes the removal as well as the refilling, all in one step. | To go back in history, just do a git checkout providing the ID of the revision you want to go back to. You can then commit there and, if you want, you can create a branch there. Or you can create the branch on the revision you want to go back to, then check it out and then commit. |
35,689,206 | Often there is the need to transform results for a query like:
```
select category, count(*)
from table
group by category
```
to a map in which keys are categories and values are count of records belonging to the same category.
Many persistence frameworks return the results of such a query as `List<Object[]>`, where object arrays contain two elements (category and the count for each returned result set row).
I am trying to find the most readable way to convert this list to the corresponding map.
Of course, traditional approach would involve creating the map and putting the entries manually:
```
Map<String, Integer> map = new HashMap<>();
list.stream().forEach(e -> map.put((String) e[0], (Integer) e[1]));
```
The first one-liner that came to my mind was to utilize the out of the box available `Collectors.toMap` collector:
```
Map<String, Integer> map = list.stream().collect(toMap(e -> (String) e[0], e -> (Integer) e[1]));
```
However, I find this `e -> (T) e[i]` syntax a bit less readable than traditional approach. To overcome this, I could create a util method which I can reuse in all such situations:
```
public static <K, V> Collector<Object[], ?, Map<K, V>> toMap() {
return Collectors.toMap(e -> (K) e[0], e -> (V) e[1]);
}
```
Then I've got a perfect one-liner:
```
Map<String, Integer> map = list.stream().collect(Utils.toMap());
```
There is even no need to cast key and value because of type inference. However, this is a bit more difficult to grasp for other readers of the code (`Collector<Object[], ?, Map<K, V>>` in the util method signature, etc).
I am wondering, is there anything else in the java 8 toolbox that could help this to be achieved in a more readable/elegant way? | 2016/02/28 | [
"https://Stackoverflow.com/questions/35689206",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4754790/"
] | I think your current 'one-liner' is fine as is. But if you don't particularly like the magic indices built into the command then you could encapsulate in an enum:
```
enum Column {
CATEGORY(0),
COUNT(1);
private final int index;
Column(int index) {
this.index = index;
}
public int getIntValue(Object[] row) {
return (int)row[index]);
}
public String getStringValue(Object[] row) {
return (String)row[index];
}
}
```
Then you're extraction code gets a bit clearer:
```
list.stream().collect(Collectors.toMap(CATEGORY::getStringValue, COUNT::getIntValue));
```
Ideally you'd add a type field to the column and check the correct method is called.
While outside the scope of your question, ideally you would create a class representing the rows which encapsulates the query. Something like the following (skipped the getters for clarity):
```
class CategoryCount {
private static final String QUERY = "
select category, count(*)
from table
group by category";
private final String category;
private final int count;
public static Stream<CategoryCount> getAllCategoryCounts() {
list<Object[]> results = runQuery(QUERY);
return Arrays.stream(results).map(CategoryCount::new);
}
private CategoryCount(Object[] row) {
category = (String)row[0];
count = (int)row[1];
}
}
```
That puts the dependency between the query and the decoding of the rows into the same class and hides all the unnecessary details from the user.
Then creating your map becomes:
```
Map<String,Integer> categoryCountMap = CategoryCount.getAllCategoryCounts()
.collect(Collectors.toMap(CategoryCount::getCategory, CategoryCount::getCount));
``` | Instead of hiding the class cast, I would make couple of functions to help with readability:
```
Map<String, Integer> map = results.stream()
.collect(toMap(
columnToObject(0, String.class),
columnToObject(1, Integer.class)
));
```
Full example:
```
package com.bluecatcode.learning.so;
import com.google.common.collect.ImmutableList;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import static java.lang.String.format;
import static java.util.stream.Collectors.toMap;
public class Q35689206 {
public static void main(String[] args) {
List<Object[]> results = ImmutableList.of(
new Object[]{"test", 1}
);
Map<String, Integer> map = results.stream()
.collect(toMap(
columnToObject(0, String.class),
columnToObject(1, Integer.class)
));
System.out.println("map = " + map);
}
private static <T> Function<Object[], T> columnToObject(int index, Class<T> type) {
return e -> asInstanceOf(type, e[index]);
}
private static <T> T asInstanceOf(Class<T> type, Object object) throws ClassCastException {
if (type.isAssignableFrom(type)) {
return type.cast(object);
}
throw new ClassCastException(format("Cannot cast object of type '%s' to '%s'",
object.getClass().getCanonicalName(), type.getCanonicalName()));
}
}
``` |
29,041,360 | I have multiple samples with R1 and R2 reads in fastq.gz format (these files are complementary to each other) I want to run BWA mem paired end parallel on all the files once finished each R1 and R2 complementary file should produce one sam file. Right now I am making two sam file from the two reads
This is what I have come up with but it’s not doing what I need it to do
```
for i in `find -maxdepth 2 -iname *fastq.gz -type f`; do
echo "bwa mem -t 12 /H.Sapiens/ucsc.hg19.fasta ${i}_R1_001.fastq.gz ${i}_R2_001.fastq.gz > ${i}_R1_R2.sam"
done
```
when it runs it looks like this
```
bwa mem -t 12 /H.Sapiens/ucsc.hg19.fasta ./Sample_0747/0747_CGG_L001_R2_001.fastq.gz_R1_001.fastq.gz ./Sample_0747/0747_CGG_L001_R2_001.fastq.gz_R2_001.fastq.gz > ./Sample_0747/0747_CGG_L001_R2_001.fastq.gz_R1_R2.sam
bwa mem -t 12 H.Sapiens/ucsc.hg19.fasta ./Sample_0748/0748_CCA_L001_R1_001.fastq.gz_R1_001.fastq.gz ./Sample_0748/0748_CCA_L001_R1_001.fastq.gz_R2_001.fastq.gz > ./Sample_0748/0748_CCA_L001_R1_001.fastq.gz_R1_R2.sam
-bash-4.1$
```
I understand the problem is in iname but how do I fixit?
Thank you so much | 2015/03/13 | [
"https://Stackoverflow.com/questions/29041360",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2976800/"
] | The actual location is reported by brew. For me it was:
```
==> Caveats
LLVM executables are installed in /usr/local/opt/llvm/bin.
Extra tools are installed in /usr/local/opt/llvm/share/llvm.
```
Then, e.g.:
```
LLVM_CONFIG=/usr/local/opt/llvm/bin/llvm-config pip install numba
``` | Ok, I needed to install llvm first. My problem was that I was installing LLVMLITE not LLVM.
So `brew install llvm` and then locating llvm-config in the `Cellar` directory solved my problem. |
22,475,433 | tIt seems that I did as it is in example [here](http://prinzhorn.github.io/skrollr/examples/bg_constant_speed_more.html) but my background moving faster than text. What did I do wrong?
My HTML:
```
<div id="loader-bg" data-0="background-position:0px 0px;" data-100000="background-position:0px -50000px;"></div>
<div id="skrollr-body">
Content text...
</div>
``` | 2014/03/18 | [
"https://Stackoverflow.com/questions/22475433",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/373978/"
] | The demo uses `background-attachment:fixed` to get full control of the movement. | Maybe you forgot to set the class attribute on your loader-bg div
```
class="skrollable skrollable-between"
``` |
6,818,980 | I'd like to generate 40-bit values, which are unique and non [so easily] guessable.
How can I do it? Any suggestions?
-edit-
I'm interested in an algorithm, C# or Java would be the cherry in the top of the cake!
-edit2-
I'm able to store previous values but I wouldn't like to have to check the whole list everytime I generate a new number | 2011/07/25 | [
"https://Stackoverflow.com/questions/6818980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/861926/"
] | What platform are you on? On unix-ish systems, just read 40bits from /dev/random (blocks if insufficient entropy is available) or /dev/urandom (doesn't block, but also produces lower-quality random numbers if entropy is limited). | usign what? in general random =unqiue,so use random. or
date|md5sum|cut -b 4-9
something like that |
6,818,980 | I'd like to generate 40-bit values, which are unique and non [so easily] guessable.
How can I do it? Any suggestions?
-edit-
I'm interested in an algorithm, C# or Java would be the cherry in the top of the cake!
-edit2-
I'm able to store previous values but I wouldn't like to have to check the whole list everytime I generate a new number | 2011/07/25 | [
"https://Stackoverflow.com/questions/6818980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/861926/"
] | get first 12 bit(upto max 4095) as day from first release of ur program(will be unique part), other 38 bit use from random system call/function.
so u have recheck last day only values for unique.
sorry, no way GRANT unique from non-predictable(random) value.
u can use more part from date, upto seconds for example. u can shafle predictable(date) bits, but it will nto add security.
anyway u have to balance between unique check time/random quality. to increase speed of check, can use binary tree or other technics.
also u can use timer value upto miliseconds.. for busy system it will be unique(if do thread lock+ 50ms sleep) and not so predictable in multithreaded environment. | usign what? in general random =unqiue,so use random. or
date|md5sum|cut -b 4-9
something like that |
6,818,980 | I'd like to generate 40-bit values, which are unique and non [so easily] guessable.
How can I do it? Any suggestions?
-edit-
I'm interested in an algorithm, C# or Java would be the cherry in the top of the cake!
-edit2-
I'm able to store previous values but I wouldn't like to have to check the whole list everytime I generate a new number | 2011/07/25 | [
"https://Stackoverflow.com/questions/6818980",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/861926/"
] | What platform are you on? On unix-ish systems, just read 40bits from /dev/random (blocks if insufficient entropy is available) or /dev/urandom (doesn't block, but also produces lower-quality random numbers if entropy is limited). | get first 12 bit(upto max 4095) as day from first release of ur program(will be unique part), other 38 bit use from random system call/function.
so u have recheck last day only values for unique.
sorry, no way GRANT unique from non-predictable(random) value.
u can use more part from date, upto seconds for example. u can shafle predictable(date) bits, but it will nto add security.
anyway u have to balance between unique check time/random quality. to increase speed of check, can use binary tree or other technics.
also u can use timer value upto miliseconds.. for busy system it will be unique(if do thread lock+ 50ms sleep) and not so predictable in multithreaded environment. |
38,233,228 | I'm curious! To my knowledge, HDFS needs datanode processes to run, and this is why it's only working on servers. Spark can run locally though, but needs winutils.exe which is a component of Hadoop. But what exactly does it do? How is it, that I cannot run Hadoop on Windows, but I can run Spark, which is built on Hadoop? | 2016/07/06 | [
"https://Stackoverflow.com/questions/38233228",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2897989/"
] | I know of at least one usage, it is for running shell commands on Windows OS. You can find it in `org.apache.hadoop.util.Shell`, other modules depends on this class and uses it's methods, for example `getGetPermissionCommand()` method:
```java
static final String WINUTILS_EXE = "winutils.exe";
...
static {
IOException ioe = null;
String path = null;
File file = null;
// invariant: either there's a valid file and path,
// or there is a cached IO exception.
if (WINDOWS) {
try {
file = getQualifiedBin(WINUTILS_EXE);
path = file.getCanonicalPath();
ioe = null;
} catch (IOException e) {
LOG.warn("Did not find {}: {}", WINUTILS_EXE, e);
// stack trace comes at debug level
LOG.debug("Failed to find " + WINUTILS_EXE, e);
file = null;
path = null;
ioe = e;
}
} else {
// on a non-windows system, the invariant is kept
// by adding an explicit exception.
ioe = new FileNotFoundException(E_NOT_A_WINDOWS_SYSTEM);
}
WINUTILS_PATH = path;
WINUTILS_FILE = file;
WINUTILS = path;
WINUTILS_FAILURE = ioe;
}
...
public static String getWinUtilsPath() {
if (WINUTILS_FAILURE == null) {
return WINUTILS_PATH;
} else {
throw new RuntimeException(WINUTILS_FAILURE.toString(),
WINUTILS_FAILURE);
}
}
...
public static String[] getGetPermissionCommand() {
return (WINDOWS) ? new String[] { getWinUtilsPath(), "ls", "-F" }
: new String[] { "/bin/ls", "-ld" };
}
``` | Though Max's answer covers the actual place where it's being referred. Let me give a brief background on why it needs it on Windows -
From Hadoop's Confluence Page itself -
>
> Hadoop requires native libraries on Windows to work properly -that
> includes accessing the file:// filesystem, where Hadoop uses some
> Windows APIs to implement posix-like file access permissions.
>
>
> This is implemented in HADOOP.DLL and WINUTILS.EXE.
>
>
> In particular, %HADOOP\_HOME%\BIN\WINUTILS.EXE must be locatable
>
>
>
And , I think you should be able to run both Spark and Hadoop on Windows. |
34,585,477 | I'm trying to determine why some of my code isn't working, even though it appears to be very straight forward.
As you can see below, I'm determining that the img tag has contains the class size-full, and then the intention is to find the closest `p` element (which is the element that houses the `img` element) b and add that the class `CM-blog-image`. Why isn't this working?
```
if($('.entry-content p img').hasClass('size-full')) {
$(this).closest('p').addClass('CM-blog-image');
}
```
**HTML**
```
<div class="entry-content" itemprop="text">
<p> // <-- Need to add class to this p element
<img src="/example.jpg" class='size-full'>
</p>
</div>
``` | 2016/01/04 | [
"https://Stackoverflow.com/questions/34585477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3775937/"
] | I assume you want to add class to each element found.
```
$('.entry-content p img').each(function(){
if($(this).hasClass('size-full'))
$(this).closest('p').addClass('CM-blog-image');
});
``` | If you have p tag and image tag immediate next of entry-content class. Use like below. it should work.
```
if($('.entry-content > p > img').hasClass('size-full')) {
$(this).closest('p').addClass('CM-blog-image');
}
``` |
34,585,477 | I'm trying to determine why some of my code isn't working, even though it appears to be very straight forward.
As you can see below, I'm determining that the img tag has contains the class size-full, and then the intention is to find the closest `p` element (which is the element that houses the `img` element) b and add that the class `CM-blog-image`. Why isn't this working?
```
if($('.entry-content p img').hasClass('size-full')) {
$(this).closest('p').addClass('CM-blog-image');
}
```
**HTML**
```
<div class="entry-content" itemprop="text">
<p> // <-- Need to add class to this p element
<img src="/example.jpg" class='size-full'>
</p>
</div>
``` | 2016/01/04 | [
"https://Stackoverflow.com/questions/34585477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3775937/"
] | You can simply use like this:
```
$('.entry-content img.size-full').parent().addClass('CM-blog-image');
//or you may use ^^ closest('p')
``` | If you have p tag and image tag immediate next of entry-content class. Use like below. it should work.
```
if($('.entry-content > p > img').hasClass('size-full')) {
$(this).closest('p').addClass('CM-blog-image');
}
``` |
34,585,477 | I'm trying to determine why some of my code isn't working, even though it appears to be very straight forward.
As you can see below, I'm determining that the img tag has contains the class size-full, and then the intention is to find the closest `p` element (which is the element that houses the `img` element) b and add that the class `CM-blog-image`. Why isn't this working?
```
if($('.entry-content p img').hasClass('size-full')) {
$(this).closest('p').addClass('CM-blog-image');
}
```
**HTML**
```
<div class="entry-content" itemprop="text">
<p> // <-- Need to add class to this p element
<img src="/example.jpg" class='size-full'>
</p>
</div>
``` | 2016/01/04 | [
"https://Stackoverflow.com/questions/34585477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3775937/"
] | You can achieve it using simple traversal methods. No need to use `.each()`
```
$('.entry-content p img.size-full') //Find image with the class
.closest('p') //Traverse up to paragraph element
.addClass('CM-blog-image'); //Add the required class
``` | If you have p tag and image tag immediate next of entry-content class. Use like below. it should work.
```
if($('.entry-content > p > img').hasClass('size-full')) {
$(this).closest('p').addClass('CM-blog-image');
}
``` |
34,585,477 | I'm trying to determine why some of my code isn't working, even though it appears to be very straight forward.
As you can see below, I'm determining that the img tag has contains the class size-full, and then the intention is to find the closest `p` element (which is the element that houses the `img` element) b and add that the class `CM-blog-image`. Why isn't this working?
```
if($('.entry-content p img').hasClass('size-full')) {
$(this).closest('p').addClass('CM-blog-image');
}
```
**HTML**
```
<div class="entry-content" itemprop="text">
<p> // <-- Need to add class to this p element
<img src="/example.jpg" class='size-full'>
</p>
</div>
``` | 2016/01/04 | [
"https://Stackoverflow.com/questions/34585477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3775937/"
] | You can simply use like this:
```
$('.entry-content img.size-full').parent().addClass('CM-blog-image');
//or you may use ^^ closest('p')
``` | I assume you want to add class to each element found.
```
$('.entry-content p img').each(function(){
if($(this).hasClass('size-full'))
$(this).closest('p').addClass('CM-blog-image');
});
``` |
34,585,477 | I'm trying to determine why some of my code isn't working, even though it appears to be very straight forward.
As you can see below, I'm determining that the img tag has contains the class size-full, and then the intention is to find the closest `p` element (which is the element that houses the `img` element) b and add that the class `CM-blog-image`. Why isn't this working?
```
if($('.entry-content p img').hasClass('size-full')) {
$(this).closest('p').addClass('CM-blog-image');
}
```
**HTML**
```
<div class="entry-content" itemprop="text">
<p> // <-- Need to add class to this p element
<img src="/example.jpg" class='size-full'>
</p>
</div>
``` | 2016/01/04 | [
"https://Stackoverflow.com/questions/34585477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3775937/"
] | You can achieve it using simple traversal methods. No need to use `.each()`
```
$('.entry-content p img.size-full') //Find image with the class
.closest('p') //Traverse up to paragraph element
.addClass('CM-blog-image'); //Add the required class
``` | I assume you want to add class to each element found.
```
$('.entry-content p img').each(function(){
if($(this).hasClass('size-full'))
$(this).closest('p').addClass('CM-blog-image');
});
``` |
34,585,477 | I'm trying to determine why some of my code isn't working, even though it appears to be very straight forward.
As you can see below, I'm determining that the img tag has contains the class size-full, and then the intention is to find the closest `p` element (which is the element that houses the `img` element) b and add that the class `CM-blog-image`. Why isn't this working?
```
if($('.entry-content p img').hasClass('size-full')) {
$(this).closest('p').addClass('CM-blog-image');
}
```
**HTML**
```
<div class="entry-content" itemprop="text">
<p> // <-- Need to add class to this p element
<img src="/example.jpg" class='size-full'>
</p>
</div>
``` | 2016/01/04 | [
"https://Stackoverflow.com/questions/34585477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3775937/"
] | I assume you want to add class to each element found.
```
$('.entry-content p img').each(function(){
if($(this).hasClass('size-full'))
$(this).closest('p').addClass('CM-blog-image');
});
``` | ```
//select img with class size-full
var elm = $('.entry-content p img.size-full');
// add CM-blog-image to closest parent p
elm.closest('p').addClass('CM-blog-image');
``` |
34,585,477 | I'm trying to determine why some of my code isn't working, even though it appears to be very straight forward.
As you can see below, I'm determining that the img tag has contains the class size-full, and then the intention is to find the closest `p` element (which is the element that houses the `img` element) b and add that the class `CM-blog-image`. Why isn't this working?
```
if($('.entry-content p img').hasClass('size-full')) {
$(this).closest('p').addClass('CM-blog-image');
}
```
**HTML**
```
<div class="entry-content" itemprop="text">
<p> // <-- Need to add class to this p element
<img src="/example.jpg" class='size-full'>
</p>
</div>
``` | 2016/01/04 | [
"https://Stackoverflow.com/questions/34585477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3775937/"
] | You can simply use like this:
```
$('.entry-content img.size-full').parent().addClass('CM-blog-image');
//or you may use ^^ closest('p')
``` | You can achieve it using simple traversal methods. No need to use `.each()`
```
$('.entry-content p img.size-full') //Find image with the class
.closest('p') //Traverse up to paragraph element
.addClass('CM-blog-image'); //Add the required class
``` |
34,585,477 | I'm trying to determine why some of my code isn't working, even though it appears to be very straight forward.
As you can see below, I'm determining that the img tag has contains the class size-full, and then the intention is to find the closest `p` element (which is the element that houses the `img` element) b and add that the class `CM-blog-image`. Why isn't this working?
```
if($('.entry-content p img').hasClass('size-full')) {
$(this).closest('p').addClass('CM-blog-image');
}
```
**HTML**
```
<div class="entry-content" itemprop="text">
<p> // <-- Need to add class to this p element
<img src="/example.jpg" class='size-full'>
</p>
</div>
``` | 2016/01/04 | [
"https://Stackoverflow.com/questions/34585477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3775937/"
] | You can simply use like this:
```
$('.entry-content img.size-full').parent().addClass('CM-blog-image');
//or you may use ^^ closest('p')
``` | ```
//select img with class size-full
var elm = $('.entry-content p img.size-full');
// add CM-blog-image to closest parent p
elm.closest('p').addClass('CM-blog-image');
``` |
34,585,477 | I'm trying to determine why some of my code isn't working, even though it appears to be very straight forward.
As you can see below, I'm determining that the img tag has contains the class size-full, and then the intention is to find the closest `p` element (which is the element that houses the `img` element) b and add that the class `CM-blog-image`. Why isn't this working?
```
if($('.entry-content p img').hasClass('size-full')) {
$(this).closest('p').addClass('CM-blog-image');
}
```
**HTML**
```
<div class="entry-content" itemprop="text">
<p> // <-- Need to add class to this p element
<img src="/example.jpg" class='size-full'>
</p>
</div>
``` | 2016/01/04 | [
"https://Stackoverflow.com/questions/34585477",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3775937/"
] | You can achieve it using simple traversal methods. No need to use `.each()`
```
$('.entry-content p img.size-full') //Find image with the class
.closest('p') //Traverse up to paragraph element
.addClass('CM-blog-image'); //Add the required class
``` | ```
//select img with class size-full
var elm = $('.entry-content p img.size-full');
// add CM-blog-image to closest parent p
elm.closest('p').addClass('CM-blog-image');
``` |
2,546,210 | I have a question about a performance of stored procedures in the ADS. I created a simple database with the following structure:
```
CREATE TABLE MainTable
(
Id INTEGER PRIMARY KEY,
Name VARCHAR(50),
Value INTEGER
);
CREATE UNIQUE INDEX MainTableName_UIX ON MainTable ( Name );
CREATE TABLE SubTable
(
Id INTEGER PRIMARY KEY,
MainId INTEGER,
Name VARCHAR(50),
Value INTEGER
);
CREATE INDEX SubTableMainId_UIX ON SubTable ( MainId );
CREATE UNIQUE INDEX SubTableName_UIX ON SubTable ( Name );
CREATE PROCEDURE CreateItems
(
MainName VARCHAR ( 20 ),
SubName VARCHAR ( 20 ),
MainValue INTEGER,
SubValue INTEGER,
MainId INTEGER OUTPUT,
SubId INTEGER OUTPUT
)
BEGIN
DECLARE @MainName VARCHAR ( 20 );
DECLARE @SubName VARCHAR ( 20 );
DECLARE @MainValue INTEGER;
DECLARE @SubValue INTEGER;
DECLARE @MainId INTEGER;
DECLARE @SubId INTEGER;
@MainName = (SELECT MainName FROM __input);
@SubName = (SELECT SubName FROM __input);
@MainValue = (SELECT MainValue FROM __input);
@SubValue = (SELECT SubValue FROM __input);
@MainId = (SELECT MAX(Id)+1 FROM MainTable);
@SubId = (SELECT MAX(Id)+1 FROM SubTable );
INSERT INTO MainTable (Id, Name, Value) VALUES (@MainId, @MainName, @MainValue);
INSERT INTO SubTable (Id, Name, MainId, Value) VALUES (@SubId, @SubName, @MainId, @SubValue);
INSERT INTO __output SELECT @MainId, @SubId FROM system.iota;
END;
CREATE PROCEDURE UpdateItems
(
MainName VARCHAR ( 20 ),
MainValue INTEGER,
SubValue INTEGER
)
BEGIN
DECLARE @MainName VARCHAR ( 20 );
DECLARE @MainValue INTEGER;
DECLARE @SubValue INTEGER;
DECLARE @MainId INTEGER;
@MainName = (SELECT MainName FROM __input);
@MainValue = (SELECT MainValue FROM __input);
@SubValue = (SELECT SubValue FROM __input);
@MainId = (SELECT TOP 1 Id FROM MainTable WHERE Name = @MainName);
UPDATE MainTable SET Value = @MainValue WHERE Id = @MainId;
UPDATE SubTable SET Value = @SubValue WHERE MainId = @MainId;
END;
CREATE PROCEDURE SelectItems
(
MainName VARCHAR ( 20 ),
CalculatedValue INTEGER OUTPUT
)
BEGIN
DECLARE @MainName VARCHAR ( 20 );
@MainName = (SELECT MainName FROM __input);
INSERT INTO __output SELECT m.Value * s.Value FROM MainTable m INNER JOIN SubTable s ON m.Id = s.MainId WHERE m.Name = @MainName;
END;
CREATE PROCEDURE DeleteItems
(
MainName VARCHAR ( 20 )
)
BEGIN
DECLARE @MainName VARCHAR ( 20 );
DECLARE @MainId INTEGER;
@MainName = (SELECT MainName FROM __input);
@MainId = (SELECT TOP 1 Id FROM MainTable WHERE Name = @MainName);
DELETE FROM SubTable WHERE MainId = @MainId;
DELETE FROM MainTable WHERE Id = @MainId;
END;
```
Actually, the problem I had - even so light stored procedures work very-very slow (about 50-150 ms) relatively to plain queries (0-5ms). To test the performance, I created a simple test (in F# using ADS ADO.NET provider):
```
open System;
open System.Data;
open System.Diagnostics;
open Advantage.Data.Provider;
let mainName = "main name #";
let subName = "sub name #";
// INSERT
let cmdTextScriptInsert = "
DECLARE @MainId INTEGER;
DECLARE @SubId INTEGER;
@MainId = (SELECT MAX(Id)+1 FROM MainTable);
@SubId = (SELECT MAX(Id)+1 FROM SubTable );
INSERT INTO MainTable (Id, Name, Value) VALUES (@MainId, :MainName, :MainValue);
INSERT INTO SubTable (Id, Name, MainId, Value) VALUES (@SubId, :SubName, @MainId, :SubValue);
SELECT @MainId, @SubId FROM system.iota;";
let cmdTextProcedureInsert = "CreateItems";
// UPDATE
let cmdTextScriptUpdate = "
DECLARE @MainId INTEGER;
@MainId = (SELECT TOP 1 Id FROM MainTable WHERE Name = :MainName);
UPDATE MainTable SET Value = :MainValue WHERE Id = @MainId;
UPDATE SubTable SET Value = :SubValue WHERE MainId = @MainId;";
let cmdTextProcedureUpdate = "UpdateItems";
// SELECT
let cmdTextScriptSelect = "
SELECT m.Value * s.Value FROM MainTable m INNER JOIN SubTable s ON m.Id = s.MainId WHERE m.Name = :MainName;";
let cmdTextProcedureSelect = "SelectItems";
// DELETE
let cmdTextScriptDelete = "
DECLARE @MainId INTEGER;
@MainId = (SELECT TOP 1 Id FROM MainTable WHERE Name = :MainName);
DELETE FROM SubTable WHERE MainId = @MainId;
DELETE FROM MainTable WHERE Id = @MainId;";
let cmdTextProcedureDelete = "DeleteItems";
let cnnStr = @"data source=D:\DB\test.add; ServerType=local; user id=adssys; password=***;";
let cnn = new AdsConnection(cnnStr);
try
cnn.Open();
let cmd = cnn.CreateCommand();
let parametrize ix prms =
cmd.Parameters.Clear();
let addParam = function
| "MainName" -> cmd.Parameters.Add(":MainName" , mainName + ix.ToString()) |> ignore;
| "SubName" -> cmd.Parameters.Add(":SubName" , subName + ix.ToString() ) |> ignore;
| "MainValue" -> cmd.Parameters.Add(":MainValue", ix * 3 ) |> ignore;
| "SubValue" -> cmd.Parameters.Add(":SubValue" , ix * 7 ) |> ignore;
| _ -> ()
prms |> List.iter addParam;
let runTest testData =
let (cmdType, cmdName, cmdText, cmdParams) = testData;
let toPrefix cmdType cmdName =
let prefix = match cmdType with
| CommandType.StoredProcedure -> "Procedure-"
| CommandType.Text -> "Script -"
| _ -> "Unknown -"
in prefix + cmdName;
let stopWatch = new Stopwatch();
let runStep ix prms =
parametrize ix prms;
stopWatch.Start();
cmd.ExecuteNonQuery() |> ignore;
stopWatch.Stop();
cmd.CommandText <- cmdText;
cmd.CommandType <- cmdType;
let startId = 1500;
let count = 10;
for id in startId .. startId+count do
runStep id cmdParams;
let elapsed = stopWatch.Elapsed;
Console.WriteLine("Test '{0}' - total: {1}; per call: {2}ms", toPrefix cmdType cmdName, elapsed, Convert.ToInt32(elapsed.TotalMilliseconds)/count);
let lst = [
(CommandType.Text, "Insert", cmdTextScriptInsert, ["MainName"; "SubName"; "MainValue"; "SubValue"]);
(CommandType.Text, "Update", cmdTextScriptUpdate, ["MainName"; "MainValue"; "SubValue"]);
(CommandType.Text, "Select", cmdTextScriptSelect, ["MainName"]);
(CommandType.Text, "Delete", cmdTextScriptDelete, ["MainName"])
(CommandType.StoredProcedure, "Insert", cmdTextProcedureInsert, ["MainName"; "SubName"; "MainValue"; "SubValue"]);
(CommandType.StoredProcedure, "Update", cmdTextProcedureUpdate, ["MainName"; "MainValue"; "SubValue"]);
(CommandType.StoredProcedure, "Select", cmdTextProcedureSelect, ["MainName"]);
(CommandType.StoredProcedure, "Delete", cmdTextProcedureDelete, ["MainName"])];
lst |> List.iter runTest;
finally
cnn.Close();
```
And I'm getting the following results:
>
> Test 'Script -Insert' - total: 00:00:00.0292841; per call: 2ms
>
>
> Test 'Script -Update' - total: 00:00:00.0056296; per call: 0ms
>
>
> Test 'Script -Select' - total: 00:00:00.0051738; per call: 0ms
>
>
> Test 'Script -Delete' - total: 00:00:00.0059258; per call: 0ms
>
>
> Test 'Procedure-Insert' - total: 00:00:01.2567146; per call: 125ms
>
>
> Test 'Procedure-Update' - total: 00:00:00.7442440; per call: 74ms
>
>
> Test 'Procedure-Select' - total: 00:00:00.5120446; per call: 51ms
>
>
> Test 'Procedure-Delete' - total: 00:00:01.0619165; per call: 106ms
>
>
>
The situation with the remote server is much better, but still a great gap between plaqin queries and stored procedures:
>
> Test 'Script -Insert' - total: 00:00:00.0709299; per call: 7ms
>
>
> Test 'Script -Update' - total: 00:00:00.0161777; per call: 1ms
>
>
> Test 'Script -Select' - total: 00:00:00.0258113; per call: 2ms
>
>
> Test 'Script -Delete' - total: 00:00:00.0166242; per call: 1ms
>
>
> Test 'Procedure-Insert' - total: 00:00:00.5116138; per call: 51ms
>
>
> Test 'Procedure-Update' - total: 00:00:00.3802251; per call: 38ms
>
>
> Test 'Procedure-Select' - total: 00:00:00.1241245; per call: 12ms
>
>
> Test 'Procedure-Delete' - total: 00:00:00.4336334; per call: 43ms
>
>
>
Is it any chance to improve the SP performance? Please advice.
ADO.NET driver version - 9.10.2.9
Server version - 9.10.0.9 (ANSI - GERMAN, OEM - GERMAN)
Thanks! | 2010/03/30 | [
"https://Stackoverflow.com/questions/2546210",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/154896/"
] | The [Advantage v10 beta](http://marketing.ianywhere.com/forms/ADS10Beta?title=Medallion&content_id_display=1069112&navId=83531&click=bannerad) includes a variety of performance improvements directly targeting stored procedure performance. Here are some things to consider with the current shipping version, however:
In your CreateItems procedure it would likely be more efficient to replace
```
@MainName = (SELECT MainName FROM __input);
@SubName = (SELECT SubName FROM __input);
@MainValue = (SELECT MainValue FROM __input);
@SubValue = (SELECT SubValue FROM __input);
```
with the use of a single cursor to retrieve all parameters:
```
DECLARE input CURSOR;
OPEN input as SELECT * from __input;
FETCH input;
@MainName = input.MainName;
@SubName = input.SubName;
@MainValue = input.MainValue;
@SubValue = input.SubValue;
CLOSE input;
```
That will avoid 3 statement parse/semantic/optimize/execute operations just to retrieve the input parameters (I know, we really need to eliminate the \_\_input table altogether).
The SelectItems procedure is rarely ever going to be as fast as a select from the client, especially in this case where it really isn't doing anything except abstracting a parameter value (which can easily be done on the client). Remember that because it is a JOIN, the SELECT to fill the \_\_output table is going to be a static cursor (meaning an internal temporary file for the server to create and fill), but now in addition you have the \_\_output table which is yet another temporary file for the server, plus you have additional overhead to populate this \_\_output table with data that has already been place in the static cursor temp table, just for the sake of duplicating it (server could do a better job of detecting this and replacing \_\_output with the existing static cursor reference, but it currently doesn't).
I will try to make some time to try your procedures on version 10. If you have the test tables you used in your testing feel free to zip them up and send them to Advantage@iAnywhere.com and put attn:JD in the subject. | There is one change that would help with the `CreateItems` procedure. Change the following two statements:
```
@MainId = (SELECT MAX(Id)+1 FROM MainTable);
@SubId = (SELECT MAX(Id)+1 FROM SubTable );
```
To this:
```
@MainId = (SELECT MAX(Id) FROM MainTable);
@MainId = @MainId + 1;
@SubId = (SELECT MAX(Id) FROM SubTable );
@SubId = @SubId + 1;
```
I looked at the query plan information (in Advantage Data Architect) for the first version of that statement. It looks like the optimizer does not break that `MAX(id)+1` into the component pieces. The statement `select max(id) from maintable` can be optimized using the index on the ID field. It appears that `max(id)+1` is not optimized. So making that change would be fairly significant particularly as the table grows.
Another thing that might help is to add a [`CACHE PREPARE ON;`](http://devzone.advantagedatabase.com/dz/webhelp/Advantage9.1/advantage_sql/sql_psm__script_/cache.htm) statement to the top of each script. This can help with certain procedures when running them multiple times.
**Edit** The [Advantage v10 beta](http://www.sybase.com/products/databasemanagement/advantagedatabaseserver) was released today. So I ran your `CreateItems` procedure with both v9.1 and the new beta version. I ran 1000 iterations against the remote server. The speed difference was significant:
```
v9.1: 101 seconds
v10 beta: 2.2 seconds
```
Note that I ran a version with the `select max(id)` change I described above. This testing was on my fairly old development PC. |
27,904,854 | In my PHP app I use PHP's CURL and openssl, to connect and talk using SOAP.
Until now, remote server supported SSL and TLS but because of "poodle" bug, admin decided to disable SSL and use TLS only.
SSL is supported until the end of January.
I changed my code by adding:
```
curl_setopt($objCurl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
```
That in theory should force curl to use TLSv1.2.
But that's theory - I need to verify that it actually uses TLS - is there any method for that?
There is a method called curl\_getinfo(), but info it returns is not useful for me:
```
[url] => https://www.example.com/soap/MessagingPort
[content_type] => text/xml;charset=utf-8
[http_code] => 200
[header_size] => 293
[request_size] => 882
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0.164487
[namelookup_time] => 3.4E-5
[connect_time] => 3.4E-5
[pretransfer_time] => 0.000122
[size_upload] => 604
[size_download] => 178
[speed_download] => 1082
[speed_upload] => 3672
[download_content_length] => 178
[upload_content_length] => 604
[starttransfer_time] => 0.164477
[redirect_time] => 0
```
Big Thanks in advance | 2015/01/12 | [
"https://Stackoverflow.com/questions/27904854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3887244/"
] | **Short Answer**
Make a request with curl to <https://www.howsmyssl.com/>
```
<?php
$ch = curl_init('https://www.howsmyssl.com/a/check');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
$json = json_decode($data);
echo $json->tls_version;
```
that should output what TLS version was used to connect.
**Digging Deeper**
Curl relies on the underlying OpenSSL (or NSS) library to do the negotiation of the secure connection. So I believe the right question to ask here is what is the OpenSSL library capable of. If it can handle a TLS connection, then curl can handle a TLS connection.
So how to figure out what the openssl (or NSS) library is capable of?
```
<?php
$curl_info = curl_version();
echo $curl_info['ssl_version'];
```
which is going to dump out something like
```
OpenSSL/1.0.1k
```
Then you can go and have a look at the release notes for that version and see if it includes TLS support.
OpenSSL Release notes - <https://www.openssl.org/news/changelog.html>
NSS Release notes - <https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/NSS_Releases>
**Spoiler Alert**
* openssl includes support for TLS v1.1 and TLS v1.2 in OpenSSL 1.0.1
[14 Mar 2012]
* NSS included support for TLS v1.1 in 3.14
* NSS included
support for TLS v1.2 in 3.15 | Use <https://tlstest.paypal.com>:
For example:
```
$ curl https://tlstest.paypal.com/
ERROR! Connection is using TLS version lesser than 1.2. Please use TLS1.2
$ ./src/curl https://tlstest.paypal.com/
PayPal_Connection_OK
``` |
27,904,854 | In my PHP app I use PHP's CURL and openssl, to connect and talk using SOAP.
Until now, remote server supported SSL and TLS but because of "poodle" bug, admin decided to disable SSL and use TLS only.
SSL is supported until the end of January.
I changed my code by adding:
```
curl_setopt($objCurl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
```
That in theory should force curl to use TLSv1.2.
But that's theory - I need to verify that it actually uses TLS - is there any method for that?
There is a method called curl\_getinfo(), but info it returns is not useful for me:
```
[url] => https://www.example.com/soap/MessagingPort
[content_type] => text/xml;charset=utf-8
[http_code] => 200
[header_size] => 293
[request_size] => 882
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0.164487
[namelookup_time] => 3.4E-5
[connect_time] => 3.4E-5
[pretransfer_time] => 0.000122
[size_upload] => 604
[size_download] => 178
[speed_download] => 1082
[speed_upload] => 3672
[download_content_length] => 178
[upload_content_length] => 604
[starttransfer_time] => 0.164477
[redirect_time] => 0
```
Big Thanks in advance | 2015/01/12 | [
"https://Stackoverflow.com/questions/27904854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3887244/"
] | **Short Answer**
Make a request with curl to <https://www.howsmyssl.com/>
```
<?php
$ch = curl_init('https://www.howsmyssl.com/a/check');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$data = curl_exec($ch);
curl_close($ch);
$json = json_decode($data);
echo $json->tls_version;
```
that should output what TLS version was used to connect.
**Digging Deeper**
Curl relies on the underlying OpenSSL (or NSS) library to do the negotiation of the secure connection. So I believe the right question to ask here is what is the OpenSSL library capable of. If it can handle a TLS connection, then curl can handle a TLS connection.
So how to figure out what the openssl (or NSS) library is capable of?
```
<?php
$curl_info = curl_version();
echo $curl_info['ssl_version'];
```
which is going to dump out something like
```
OpenSSL/1.0.1k
```
Then you can go and have a look at the release notes for that version and see if it includes TLS support.
OpenSSL Release notes - <https://www.openssl.org/news/changelog.html>
NSS Release notes - <https://developer.mozilla.org/en-US/docs/Mozilla/Projects/NSS/NSS_Releases>
**Spoiler Alert**
* openssl includes support for TLS v1.1 and TLS v1.2 in OpenSSL 1.0.1
[14 Mar 2012]
* NSS included support for TLS v1.1 in 3.14
* NSS included
support for TLS v1.2 in 3.15 | If you want to test which protocol is being used for a specific url (like a payment api endpoint) you can [log curl's verbose output](https://stackoverflow.com/a/14436877/1767412) and see it there. Here's a quick example:
```
$url = 'https://example.com/';
$ch = curl_init($url);
$out = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_STDERR, $out);
curl_exec($ch);
curl_close($ch);
rewind($out);
$debug = stream_get_contents($out);
if (preg_match('/SSL connection.*/', $debug, $match)) {
echo '<pre>' . $url . PHP_EOL . $match[0];
}
```
For me that gives output like:
```none
https://example.com/
SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384
``` |
27,904,854 | In my PHP app I use PHP's CURL and openssl, to connect and talk using SOAP.
Until now, remote server supported SSL and TLS but because of "poodle" bug, admin decided to disable SSL and use TLS only.
SSL is supported until the end of January.
I changed my code by adding:
```
curl_setopt($objCurl, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
```
That in theory should force curl to use TLSv1.2.
But that's theory - I need to verify that it actually uses TLS - is there any method for that?
There is a method called curl\_getinfo(), but info it returns is not useful for me:
```
[url] => https://www.example.com/soap/MessagingPort
[content_type] => text/xml;charset=utf-8
[http_code] => 200
[header_size] => 293
[request_size] => 882
[filetime] => -1
[ssl_verify_result] => 0
[redirect_count] => 0
[total_time] => 0.164487
[namelookup_time] => 3.4E-5
[connect_time] => 3.4E-5
[pretransfer_time] => 0.000122
[size_upload] => 604
[size_download] => 178
[speed_download] => 1082
[speed_upload] => 3672
[download_content_length] => 178
[upload_content_length] => 604
[starttransfer_time] => 0.164477
[redirect_time] => 0
```
Big Thanks in advance | 2015/01/12 | [
"https://Stackoverflow.com/questions/27904854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3887244/"
] | Use <https://tlstest.paypal.com>:
For example:
```
$ curl https://tlstest.paypal.com/
ERROR! Connection is using TLS version lesser than 1.2. Please use TLS1.2
$ ./src/curl https://tlstest.paypal.com/
PayPal_Connection_OK
``` | If you want to test which protocol is being used for a specific url (like a payment api endpoint) you can [log curl's verbose output](https://stackoverflow.com/a/14436877/1767412) and see it there. Here's a quick example:
```
$url = 'https://example.com/';
$ch = curl_init($url);
$out = fopen('php://temp', 'w+');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_STDERR, $out);
curl_exec($ch);
curl_close($ch);
rewind($out);
$debug = stream_get_contents($out);
if (preg_match('/SSL connection.*/', $debug, $match)) {
echo '<pre>' . $url . PHP_EOL . $match[0];
}
```
For me that gives output like:
```none
https://example.com/
SSL connection using TLSv1.3 / TLS_AES_256_GCM_SHA384
``` |
15,589,258 | I have a template file **node-contenttype.tpl.php**. There I´m trying to print the comments of that node via
```
print render($content['comments']);
```
but only the comment form is rendered. So im looking into the comment-wrapper.tpl.php and the comment.tpl.php. When im writing something in the **comment-wrapper.tpl.php**, for example a little bit of dummy text, it is printed. But when im doing this in the **comment.tpl.php**, nothing happens.
Inside the **comment-wrapper.tpl.php** is the call
```
print render($content['comments']);
```
but no comment is rendered.
So the problem seems to bee that the **comment.tpl.php** is not called. I have find out that the comment Array in **comment-wrapper.tpl.php** is empty, too.
Can anybody help please? | 2013/03/23 | [
"https://Stackoverflow.com/questions/15589258",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1551356/"
] | Maybe Not the best way forward, but you can also use this in node-contenttype.tpl.php
```
<?php
echo "<pre>";
$node_view = node_view($node);
foreach($node_view['comments']['comments'] as $key=>$value)
{
if(is_numeric($key))
{
print_r($value['comment_body']['#object']->comment_body['und'][0]['safe_value']);
}
}
echo "</pre>";
?>
``` | It was a language problem. The language was set to "english", i have set to undefined and now the comments are rendered.
But i have no idea why.. |
20,367,854 | If I have a list, which contains the 4 nodes ("this"; "test example"; "is something of"; "a small") and I want to find every string that has "is" (only 1 positive with this list). This topic has been posted a large number of times, which I have used to help get me this far. However, I can't see anywhere how I omit "this" from a positive result. I could probably use string::c\_str, then find it myself, after I've reduced my much larger list. Or is there a way I could use string::find\_first\_of? It would seem there's a better way. Thanks.
EDIT: I know that I can omit a particular string, but I'm looking for bigger picture b/c my list is quite large (ex: poem).
```
for(it = phrases.begin(); it != phrases.end(); ++it)
{
found = it->find(look);
if(found != string::npos)
cout << i++ << ". " << *it << endl;
else
{
i++;
insert++;
}
}
``` | 2013/12/04 | [
"https://Stackoverflow.com/questions/20367854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2608071/"
] | Just to clarify: what are you struggling with?
What you want to do is check if what you have found is the start of a word (or the phrase) and is also the end of a word (or the phrase)
ie. check if:
* `found` is equal to `phrases.begin` OR the element preceding `found` is a space
* AND two elements after `found` is a space OR `phrases.end`
EDIT: You can access the character that was found by using `found` (replace X with the length of the string you're finding (look.length)
```
found = it->find(look);
if(found!=string::npos)
{
if((found==0 || it->at(found-1)==' ')
&& (found==it->length-X || it->at(found+X)==' '))
{
// Actually found it
}
} else {
// Do whatever
}
``` | I didn't realize you only wanted to match "is". You can do this by using an std::istringstream to tokenize it for you:
```
std::string term("is");
for(std::list<std::string>::const_iterator it = phrases.begin();
it != phrases.end(); ++it)
{
std::istringstream ss(*it);
std::string token;
while(ss >> token)
{
if(token == term)
std::cout << "Found " << token << "\n";
}
}
``` |
20,367,854 | If I have a list, which contains the 4 nodes ("this"; "test example"; "is something of"; "a small") and I want to find every string that has "is" (only 1 positive with this list). This topic has been posted a large number of times, which I have used to help get me this far. However, I can't see anywhere how I omit "this" from a positive result. I could probably use string::c\_str, then find it myself, after I've reduced my much larger list. Or is there a way I could use string::find\_first\_of? It would seem there's a better way. Thanks.
EDIT: I know that I can omit a particular string, but I'm looking for bigger picture b/c my list is quite large (ex: poem).
```
for(it = phrases.begin(); it != phrases.end(); ++it)
{
found = it->find(look);
if(found != string::npos)
cout << i++ << ". " << *it << endl;
else
{
i++;
insert++;
}
}
``` | 2013/12/04 | [
"https://Stackoverflow.com/questions/20367854",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2608071/"
] | Just to clarify: what are you struggling with?
What you want to do is check if what you have found is the start of a word (or the phrase) and is also the end of a word (or the phrase)
ie. check if:
* `found` is equal to `phrases.begin` OR the element preceding `found` is a space
* AND two elements after `found` is a space OR `phrases.end`
EDIT: You can access the character that was found by using `found` (replace X with the length of the string you're finding (look.length)
```
found = it->find(look);
if(found!=string::npos)
{
if((found==0 || it->at(found-1)==' ')
&& (found==it->length-X || it->at(found+X)==' '))
{
// Actually found it
}
} else {
// Do whatever
}
``` | We can use boost regex for searching regular expressions. Below is an example code. Using regular expression complex seacrh patterns can be created.
```
#include <boost/regex.hpp>
#include <string>
#include <iostream>
#include <boost/tokenizer.hpp>
using namespace boost;
using namespace std;
int main()
{
std::string list[4] = {"this","hi how r u ","is this fun is","no"};
regex ex("^is");
for(int x =0;x<4;++x)
{
string::const_iterator start, end;
boost::char_separator<char> sep(" ");
boost::tokenizer<boost::char_separator<char> > token(list[x],sep);
cout << "Search string: " << list[x] <<"\n"<< endl;
int x = 0;
for(boost::tokenizer<boost::char_separator<char> >::iterator itr = token.begin();
itr!=token.end();++itr)
{
start = (*itr).begin();
end = (*itr).end();
boost::match_results<std::string::const_iterator> what;
boost::match_flag_type flags = boost::match_default;
if(boost::regex_search(start, end, what, ex, flags))
{
++x;
cout << "Found--> " << what.str() << endl;
}
}
cout<<"found pattern "<<x <<" times."<<endl<<endl;
}
return 0;
}
```
Output:
>
> Search string: this
>
>
> found pattern 0 times.
>
>
> Search string: hi how r u
>
>
> found pattern 0 times.
>
>
> Search string: is this fun is
>
>
> Found--> is Found--> is found pattern 2 times.
>
>
> Search string: no
>
>
> found pattern 0 times.
>
>
> |
69,165,947 | Elixir source may be injected using Code.eval\_string/3. I don't see mention of running raw Erlang code in the docs:
<https://hexdocs.pm/elixir/Code.html#eval_string/3>
I am coming from a Scala world in which Java objects are callable using Scala syntax, and Scala is compiled into Java and visible by intercepting the compiler output (directly generated with scalac).
I get the sense that Elixir does not provide such interoperating features, nor allow injection of custom Erlang into the runtime. Is this the case? | 2021/09/13 | [
"https://Stackoverflow.com/questions/69165947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2580891/"
] | You can use the erlang standard library modules from Elixir, as described [here](https://elixir-lang.org/getting-started/erlang-libraries.html) or [here](https://elixirschool.com/en/lessons/advanced/erlang/#erlang-packages).
For example:
```
def random_integer(upper) do
:rand.uniform(upper) # rand is an erlang library
end
```
You can also add erlang packages to your `mix.exs` dependencies and use them in your project, as long as these packages are published on `hex` or on github.
You can also use erlang and elixir code together in a project as described [here](https://dev.to/wesleimp/elixir-and-erlang-code-in-the-same-project-2l83).
So yeah, it's perfectly possible to call erlang code from elixir.
Vice-versa is also possible, see [here](https://elixir-lang.org/crash-course.html#adding-elixir-to-existing-erlang-programs) for more information:
>
> Elixir compiles into BEAM byte code (via Erlang Abstract Format). This
> means that Elixir code can be called from Erlang and vice versa,
> without the need to write any bindings.
>
>
> | Expanding what @zwippie have written:
**All** remote function calls (by that I mean calling function with explicitly set module/alias) are in form of:
```
<atom with module name>.<function name>(<arguments>)
# Technically it is the same as:
# apply(module, function_name_as_atom, [arguments])
```
And all "upper case module names" in Elixir are just atoms:
```
is_atom(Foo) == true
Foo == :"Elixir.Foo" # => true
```
So from Elixir viewpoint there is no difference between calling Erlang functions and Elixir functions. It is just different atom passed as the receiving module.
So you can easily call Erlang modules from Elixir. That mean that without much of the hassle you should be able to compile Erlang AST from within Elixir as well:
```
"rand:uniform(100)"
|> :merl.quote()
|> :erl_eval.expr(#{})
```
No need for any mental translation.
---
Additionally you can without any problems mix Erlang and Elixir code in single Mix project. With tree structure like:
```
.
|`- mix.exs
|`- src
| `- example.erl
`- lib
`- example.ex
```
Where `example.erl` is:
```erlang
-module(example).
-export([hello/0]).
hello() -> <<"World">>.
```
And `example.ex`:
```
defmodule Example do
def print_hello, do: IO.puts(:example.hello())
end
```
You can compile project and run it with
```
mix run -e "Example.print_hello()"
```
And see that Erlang module was successfully compiled and executed from within Elixir code in the same project without problems. |
69,165,947 | Elixir source may be injected using Code.eval\_string/3. I don't see mention of running raw Erlang code in the docs:
<https://hexdocs.pm/elixir/Code.html#eval_string/3>
I am coming from a Scala world in which Java objects are callable using Scala syntax, and Scala is compiled into Java and visible by intercepting the compiler output (directly generated with scalac).
I get the sense that Elixir does not provide such interoperating features, nor allow injection of custom Erlang into the runtime. Is this the case? | 2021/09/13 | [
"https://Stackoverflow.com/questions/69165947",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2580891/"
] | You can use the erlang standard library modules from Elixir, as described [here](https://elixir-lang.org/getting-started/erlang-libraries.html) or [here](https://elixirschool.com/en/lessons/advanced/erlang/#erlang-packages).
For example:
```
def random_integer(upper) do
:rand.uniform(upper) # rand is an erlang library
end
```
You can also add erlang packages to your `mix.exs` dependencies and use them in your project, as long as these packages are published on `hex` or on github.
You can also use erlang and elixir code together in a project as described [here](https://dev.to/wesleimp/elixir-and-erlang-code-in-the-same-project-2l83).
So yeah, it's perfectly possible to call erlang code from elixir.
Vice-versa is also possible, see [here](https://elixir-lang.org/crash-course.html#adding-elixir-to-existing-erlang-programs) for more information:
>
> Elixir compiles into BEAM byte code (via Erlang Abstract Format). This
> means that Elixir code can be called from Erlang and vice versa,
> without the need to write any bindings.
>
>
> | One more thing to watch for when calling erlang code from elixir. erlang uses charlists for strings. When you call a erlang function that takes a string, convert the string to a charlist and convert returned string to a string.
Examples:
```
iex(17)> :string.to_upper "test"
** (FunctionClauseError) no function clause matching in :string.to_upper/1
The following arguments were given to :string.to_upper/1:
# 1
"test"
(stdlib 3.15.1) string.erl:2231: :string.to_upper/1
iex(17)> "test" |> String.to_charlist() |> :string.to_upper
'TEST'
iex(18)> "test" |> String.to_charlist() |> :string.to_upper |> to_string
"TEST"
iex(19)>
``` |
50,064 | I need to show somebody a website running on my local machine tomorrow. Normally I'd accomplish this by port forwarding on my local router but thanks to failing hardware and its replacement being awful, my current router doesn't let me do port forwarding.
So stuck with this delay and not wanting to push the whole thing onto a proper server, I had a crazy idea: **Can I just forward my port to an external server over SSH?**
I've done port tunnelling before but I usually do it the right way around:
* I connect to a remote box and ask that port 12345 shows up on my local machine at port 12345.
* I start something on P12345 on the remote machine
* I can access it via localhost:12345
What I *want* to do:
* Connect to a remote PC and ask that that *its* local P12345 fetch things from my local P12345 (over the tunnel)
* I start something on my local computer on P12345
* Other people can access remote:12345 and see my localhost:12345 | 2011/06/22 | [
"https://askubuntu.com/questions/50064",
"https://askubuntu.com",
"https://askubuntu.com/users/449/"
] | The command for forwarding port 80 from your local machine (`localhost`) to the remote host on port 8000 is:
```
ssh -R 8000:localhost:80 oli@remote-machine
```
This requires an additional tweak on the SSH server, add the lines to `/etc/ssh/sshd_config`:
```
Match User oli
GatewayPorts yes
```
Next, reload the configuration by server executing `sudo reload ssh`.
The setting `GatewayPorts yes` causes SSH to bind port 8000 on the wildcard address, so it becomes available to the public address of `remote-machine` (`remote-machine:8000`).
If you need to have the option for not binding everything on the wildcard address, change `GatewayPorts yes` to `GatewayPorts clientspecified`. Because `ssh` binds to the loopback address by default, you need to specify an empty `bind_address` for binding the wildcard address:
```
ssh -R :8000:localhost:80 oli@remote-machine
```
The `:` before `8000` is mandatory if `GatewayPorts` is set to `clientspecified` and you want to allow public access to `remote-machine:8000`.
Relevant manual excerpts:
[ssh(1)](http://manpages.ubuntu.com/manpages/natty/en/man1/ssh.1.html)
>
> -R [bind\_address:]port:host:hostport
>
> Specifies that the given port on the remote (server) host is to be forwarded to the given host and port on the local side. This works by allocating a socket to listen to port on the remote side, and whenever a connection is made to this port, the connection is forwarded over the secure channel, and a connection is made to host port hostport from the local machine. **By default, the listening socket on the server will be bound to the loopback interface only.** This may be overridden by specifying a bind\_address. **An empty bind\_address, or the address ‘\*’, indicates that the remote socket should listen on all interfaces.** Specifying a remote bind\_address will only succeed if the server's GatewayPorts option is enabled (see sshd\_config(5)).
>
>
>
[sshd\_config(5)](http://manpages.ubuntu.com/manpages/natty/en/man5/sshd_config.5.html)
>
> GatewayPorts
>
> Specifies whether remote hosts are allowed to connect to ports forwarded for the client. GatewayPorts can be used to specify that sshd should allow remote port forwardings to bind to non-loopback addresses, thus allowing other hosts to connect. **The argument may be 'no' to force remote port forwardings to be available to the local host only, 'yes' to force remote port forwardings to bind to the wildcard address, or 'clientspecified' to allow the client to select the address to which the forwarding is bound.** The default is 'no'.
>
>
>
See also:
* [How to create a restricted SSH user for port forwarding?](https://askubuntu.com/q/48129/6969) | If the server has `GatewayPorts no`, you can achieve the same result by executing `ssh -g -L 8001:localhost:8000 oli@remote-machine` on the server once you have executed `ssh -R` command on the client. This will make loopback port 8000 on the server accessible on all interfaces on port 8001. |
3,805,516 | I was writing a bunch of code a few months ago and now I'm adding stuff to it. I realized I wrote a bunch of functions that descend from a class that has about 2/3rds of its functions abstract and the remaining 1/3rd virtual.
I'm pretty much sick of seeing:
```
function descendent.doSomething() : TList;
begin
inherited;
end;
```
when I've got this for the base class:
```
function descendent.doSomething() : TList;
begin
result := nil;
end;
```
and would hate to wind up with:
```
function descendent.doSomething() : TList;
begin
end;
```
and then wonder why something didn't work.
I like using abstract functions because the compiler will let you know if you're liable to get an abstract error because you didn't implement some functions.
My question is, because I'm still a relatively new Delphi programmer and I've never had to maintain anything 8 years hence, is it worth taking the time to [prune your code](https://softwareengineering.stackexchange.com/questions/6055/awesomest-programming-plant/6062#6062) in this manner (i.e. remove functions that just have inherited in them and change your base class functions from abstract to concrete) | 2010/09/27 | [
"https://Stackoverflow.com/questions/3805516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765/"
] | It depends on the problem as always. I use interfaces to define the user interface for the set of classes. At least when I know I will have more than one implementation of the underlying actual class. For instance You can have something like this:
```
IAllInterfaced = interface(IInterface)
procedure ImplementMeEverywhere_1(const Params: TParams);
procedure ImplementMeEverywhere_2(const Params: TParams);
procedure ImplementMeEverywhere_3(const Params: TParams);
end;
TAllInterfaced_ClassA = class(TInterfacedObject, IAllInterfaced)
public
procedure ImplementMeEverywhere_1(const Params: TParams);
procedure ImplementMeEverywhere_2(const Params: TParams);
procedure ImplementMeEverywhere_3(const Params: TParams);
end;
TAllInterfaced_ClassB = class(TInterfacedObject, IAllInterfaced)
public
procedure ImplementMeEverywhere_1(const Params: TParams);
procedure ImplementMeEverywhere_2(const Params: TParams);
procedure ImplementMeEverywhere_3(const Params: TParams);
end;
```
Here you dont have a common ancestor. Each class only implements the interface and has no common underlying structure in a form of a common base class. This is possible if implementations are so different that they do not share anything, but he interface itself. You still need to use the same interface so you are consistent towards the users of the derived classes.
The second option is:
```
IAllAbstract = interface(IInterface)
procedure ImplementMeEverywhere_1(const Params: TParams);
procedure ImplementMeEverywhere_2(const Params: TParams);
procedure ImplementMeEverywhere_3(const Params: TParams);
end;
TAllAbstract_Custom = (TInterfacedObject, IAllAbstract)
private
...
public
procedure ImplementMeEverywhere_1(const Params: TParams); virtual; abstract;
procedure ImplementMeEverywhere_2(const Params: TParams); virtual; abstract;
procedure ImplementMeEverywhere_3(const Params: TParams); virtual; abstract;
end;
TAllAbstract_ClassA = class(TAllAbstract_Custom)
public
procedure ImplementMeEverywhere_1(const Params: TParams); override;
procedure ImplementMeEverywhere_2(const Params: TParams); override;
procedure ImplementMeEverywhere_3(const Params: TParams); override;
end;
TAllAbstract_ClassB = class(TAllAbstract_Custom)
public
procedure ImplementMeEverywhere_1(const Params: TParams); override;
procedure ImplementMeEverywhere_2(const Params: TParams); override;
procedure ImplementMeEverywhere_3(const Params: TParams); override;
end;
```
Here you have a base class for all the classes. In that class you can have common properties or event other classes etc... But all procedures are marked as abstract because they do not perform any common tasks. Abstract ensures the they will be implemented in the derived classes, but you do not need to implement "FieldA" in every class, you only implement it in the "TAllAbstract\_Custom". This ensures that the DRY principle is used.
The last option is:
```
IAllVirtual = interface(IInterface)
procedure ImplementMeEverywhere_1(const Params: TParams);
procedure ImplementMeEverywhere_2(const Params: TParams);
procedure ImplementMeEverywhere_3(const Params: TParams);
end;
TAllVirtual_Custom = (TInterfacedObject, IAllVirtual)
private
...
public
procedure ImplementMeEverywhere_1(const Params: TParams); virtual;
procedure ImplementMeEverywhere_2(const Params: TParams); virtual;
procedure ImplementMeEverywhere_3(const Params: TParams); virtual;
end;
TAllVirtual_ClassA = class(TAllVirtual_Custom)
public
procedure ImplementMeEverywhere_1(const Params: TParams); override;
procedure ImplementMeEverywhere_2(const Params: TParams); override;
procedure ImplementMeEverywhere_3(const Params: TParams); override;
end;
TAllVirtual_ClassB = class(TAllVirtual_Custom)
public
procedure ImplementMeEverywhere_1(const Params: TParams); override;
procedure ImplementMeEverywhere_2(const Params: TParams); override;
procedure ImplementMeEverywhere_3(const Params: TParams); override;
end;
```
Here all derived classes have a common base virtual procedure. This ensures you do not have to implement every single procedure at the level of the derived classes. You can only override some parts of the code or none at all.
Naturally this are all edge cases, there is room in beetwen them. You can have a mix of those concepts.
Just remember:
1. Interfaces are powerfull tool to ensure that you hide implementation from the user and that you have a common usage point (interface). They also force some norms to be used, because interface needs to be implemented in full.
2. Abstract is a good tool so you do not have to use empty stubs for procedures where there is no real need for them. On the other side they force you to implement them in derived classes.
3. Virtual comes in handy when you have common code that must be implemented by every class and that ensures the clean OP and DRY principle. They are also welcome when you have procedures that not every derived class has or needs.
Sorry for a long answer but I could not give an easy explanation here because there is none. It all depends on the problem at hand. It is a balance between how much do the derived classes have in common and how different their implementations are. | If the code is really simple and you find it difficult to read and error-prone, then it's probably difficult to read and error-prone. (On the other hand, if the code is *complicated* and you find it hard to read, it could be your lack of experience. But not something like this.) You'd probably do well to refactor it now, while the issue is still fresh in your mind. |
3,805,516 | I was writing a bunch of code a few months ago and now I'm adding stuff to it. I realized I wrote a bunch of functions that descend from a class that has about 2/3rds of its functions abstract and the remaining 1/3rd virtual.
I'm pretty much sick of seeing:
```
function descendent.doSomething() : TList;
begin
inherited;
end;
```
when I've got this for the base class:
```
function descendent.doSomething() : TList;
begin
result := nil;
end;
```
and would hate to wind up with:
```
function descendent.doSomething() : TList;
begin
end;
```
and then wonder why something didn't work.
I like using abstract functions because the compiler will let you know if you're liable to get an abstract error because you didn't implement some functions.
My question is, because I'm still a relatively new Delphi programmer and I've never had to maintain anything 8 years hence, is it worth taking the time to [prune your code](https://softwareengineering.stackexchange.com/questions/6055/awesomest-programming-plant/6062#6062) in this manner (i.e. remove functions that just have inherited in them and change your base class functions from abstract to concrete) | 2010/09/27 | [
"https://Stackoverflow.com/questions/3805516",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1765/"
] | It depends on the problem as always. I use interfaces to define the user interface for the set of classes. At least when I know I will have more than one implementation of the underlying actual class. For instance You can have something like this:
```
IAllInterfaced = interface(IInterface)
procedure ImplementMeEverywhere_1(const Params: TParams);
procedure ImplementMeEverywhere_2(const Params: TParams);
procedure ImplementMeEverywhere_3(const Params: TParams);
end;
TAllInterfaced_ClassA = class(TInterfacedObject, IAllInterfaced)
public
procedure ImplementMeEverywhere_1(const Params: TParams);
procedure ImplementMeEverywhere_2(const Params: TParams);
procedure ImplementMeEverywhere_3(const Params: TParams);
end;
TAllInterfaced_ClassB = class(TInterfacedObject, IAllInterfaced)
public
procedure ImplementMeEverywhere_1(const Params: TParams);
procedure ImplementMeEverywhere_2(const Params: TParams);
procedure ImplementMeEverywhere_3(const Params: TParams);
end;
```
Here you dont have a common ancestor. Each class only implements the interface and has no common underlying structure in a form of a common base class. This is possible if implementations are so different that they do not share anything, but he interface itself. You still need to use the same interface so you are consistent towards the users of the derived classes.
The second option is:
```
IAllAbstract = interface(IInterface)
procedure ImplementMeEverywhere_1(const Params: TParams);
procedure ImplementMeEverywhere_2(const Params: TParams);
procedure ImplementMeEverywhere_3(const Params: TParams);
end;
TAllAbstract_Custom = (TInterfacedObject, IAllAbstract)
private
...
public
procedure ImplementMeEverywhere_1(const Params: TParams); virtual; abstract;
procedure ImplementMeEverywhere_2(const Params: TParams); virtual; abstract;
procedure ImplementMeEverywhere_3(const Params: TParams); virtual; abstract;
end;
TAllAbstract_ClassA = class(TAllAbstract_Custom)
public
procedure ImplementMeEverywhere_1(const Params: TParams); override;
procedure ImplementMeEverywhere_2(const Params: TParams); override;
procedure ImplementMeEverywhere_3(const Params: TParams); override;
end;
TAllAbstract_ClassB = class(TAllAbstract_Custom)
public
procedure ImplementMeEverywhere_1(const Params: TParams); override;
procedure ImplementMeEverywhere_2(const Params: TParams); override;
procedure ImplementMeEverywhere_3(const Params: TParams); override;
end;
```
Here you have a base class for all the classes. In that class you can have common properties or event other classes etc... But all procedures are marked as abstract because they do not perform any common tasks. Abstract ensures the they will be implemented in the derived classes, but you do not need to implement "FieldA" in every class, you only implement it in the "TAllAbstract\_Custom". This ensures that the DRY principle is used.
The last option is:
```
IAllVirtual = interface(IInterface)
procedure ImplementMeEverywhere_1(const Params: TParams);
procedure ImplementMeEverywhere_2(const Params: TParams);
procedure ImplementMeEverywhere_3(const Params: TParams);
end;
TAllVirtual_Custom = (TInterfacedObject, IAllVirtual)
private
...
public
procedure ImplementMeEverywhere_1(const Params: TParams); virtual;
procedure ImplementMeEverywhere_2(const Params: TParams); virtual;
procedure ImplementMeEverywhere_3(const Params: TParams); virtual;
end;
TAllVirtual_ClassA = class(TAllVirtual_Custom)
public
procedure ImplementMeEverywhere_1(const Params: TParams); override;
procedure ImplementMeEverywhere_2(const Params: TParams); override;
procedure ImplementMeEverywhere_3(const Params: TParams); override;
end;
TAllVirtual_ClassB = class(TAllVirtual_Custom)
public
procedure ImplementMeEverywhere_1(const Params: TParams); override;
procedure ImplementMeEverywhere_2(const Params: TParams); override;
procedure ImplementMeEverywhere_3(const Params: TParams); override;
end;
```
Here all derived classes have a common base virtual procedure. This ensures you do not have to implement every single procedure at the level of the derived classes. You can only override some parts of the code or none at all.
Naturally this are all edge cases, there is room in beetwen them. You can have a mix of those concepts.
Just remember:
1. Interfaces are powerfull tool to ensure that you hide implementation from the user and that you have a common usage point (interface). They also force some norms to be used, because interface needs to be implemented in full.
2. Abstract is a good tool so you do not have to use empty stubs for procedures where there is no real need for them. On the other side they force you to implement them in derived classes.
3. Virtual comes in handy when you have common code that must be implemented by every class and that ensures the clean OP and DRY principle. They are also welcome when you have procedures that not every derived class has or needs.
Sorry for a long answer but I could not give an easy explanation here because there is none. It all depends on the problem at hand. It is a balance between how much do the derived classes have in common and how different their implementations are. | Yes, prune your code.
It makes your other code much easier to read (as you already mentioned, it would be easier to see what methods are actually overwritten). As an added benefit it will be easier to change the signature of the method in the parent class: Imagine you decide to pass one more parameter to a virtual method; You make the change to the parent class, then you'll need to repeat that same change for every child class that inherits from the given parent class. At that point you don't want bogus overwritten methods that just call "inherited"! |
1,633,342 | After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide *way* more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correct/standard way to manage WSGI middleware in an application.
I'm not looking for framework suggestions, unless its to provide an example of ways to manage WSGI middleware. Nor am I looking for information on how to get a webserver to talk to python -- that bit I understand.
Rather, I'm looking for advice on how one tells python what components/middleware to put into the stack, and in which order. For instance, if I wanted to use:
`Spawning-->memento-->AuthKit-->(?)-->MyApp`
how would I get those components into the right order, and how would I configure an additional item (say Routes) before `MyApp`?
So; Can you advise on the common/correct/standard way of managing what middleware is included in a WSGI stack for a Python application?
**Edit**
Thanks to Michael Dillon for recommending [A Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html), which helps highlight my problem. The [middleware section](http://pythonpaste.org/do-it-yourself-framework.html#give-me-more-middleware) of that document states that one should wrap middleware A in middleware B, B in C, and so-on:
```
app = ObjectPublisher(Root())
wrapped_app = AuthMiddleware(app)
from paste.evalexception import EvalException
exc_wrapped_app = EvalException(wrapped_app)
```
Which shows how to do it in a very simple way. I understand how this works, however it seems too simple when working with a number of middleware packages.
**Is there a better way to manage how these middleware components are added to the stack? Maybe a common design pattern which reads from a config file?** | 2009/10/27 | [
"https://Stackoverflow.com/questions/1633342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30478/"
] | What middleware do you think you need? You may very well not need to include any WSGI ‘middleware’-like components at all. You can perfectly well put together a loose ‘pseudo-framework’ of standalone libraries without needing to ‘wrap’ the application in middleware at all.
(Personally I use a separate form-reading library, data access layer and template engine, none of which know about each other or need to start fiddling with the WSGI `environ`.) | If you liked the Do-It-Yourself-Framework tutorial mentioned before, but you want to manage these things in a config file, [Paste Deploy](http://pythonpaste.org/deploy/) would be the obvious answer. (It is mentioned in the tutorial, but only very briefly in the very last paragraph).
This is what the Pylons framework uses, by the way (and Turbogears 2, which is built upon Pylons, also). |
1,633,342 | After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide *way* more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correct/standard way to manage WSGI middleware in an application.
I'm not looking for framework suggestions, unless its to provide an example of ways to manage WSGI middleware. Nor am I looking for information on how to get a webserver to talk to python -- that bit I understand.
Rather, I'm looking for advice on how one tells python what components/middleware to put into the stack, and in which order. For instance, if I wanted to use:
`Spawning-->memento-->AuthKit-->(?)-->MyApp`
how would I get those components into the right order, and how would I configure an additional item (say Routes) before `MyApp`?
So; Can you advise on the common/correct/standard way of managing what middleware is included in a WSGI stack for a Python application?
**Edit**
Thanks to Michael Dillon for recommending [A Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html), which helps highlight my problem. The [middleware section](http://pythonpaste.org/do-it-yourself-framework.html#give-me-more-middleware) of that document states that one should wrap middleware A in middleware B, B in C, and so-on:
```
app = ObjectPublisher(Root())
wrapped_app = AuthMiddleware(app)
from paste.evalexception import EvalException
exc_wrapped_app = EvalException(wrapped_app)
```
Which shows how to do it in a very simple way. I understand how this works, however it seems too simple when working with a number of middleware packages.
**Is there a better way to manage how these middleware components are added to the stack? Maybe a common design pattern which reads from a config file?** | 2009/10/27 | [
"https://Stackoverflow.com/questions/1633342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30478/"
] | I'd have to say that Apache/mod\_wsgi is probably the most "manageable" of the setups I've used.
nginx/fcgi is the fastest, but its a bit of a headache. | "it seems too simple when working with a number of middleware packages."
How big a number?
You won't be working with hundreds or thousands.
It will be (a) a small number (under a dozen) and (b) the "right" order isn't magical.
Each piece of middleware will have a very, very specific job and very specific requirements for what must come before it.
It's much less confusing than you're assuming. |
1,633,342 | After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide *way* more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correct/standard way to manage WSGI middleware in an application.
I'm not looking for framework suggestions, unless its to provide an example of ways to manage WSGI middleware. Nor am I looking for information on how to get a webserver to talk to python -- that bit I understand.
Rather, I'm looking for advice on how one tells python what components/middleware to put into the stack, and in which order. For instance, if I wanted to use:
`Spawning-->memento-->AuthKit-->(?)-->MyApp`
how would I get those components into the right order, and how would I configure an additional item (say Routes) before `MyApp`?
So; Can you advise on the common/correct/standard way of managing what middleware is included in a WSGI stack for a Python application?
**Edit**
Thanks to Michael Dillon for recommending [A Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html), which helps highlight my problem. The [middleware section](http://pythonpaste.org/do-it-yourself-framework.html#give-me-more-middleware) of that document states that one should wrap middleware A in middleware B, B in C, and so-on:
```
app = ObjectPublisher(Root())
wrapped_app = AuthMiddleware(app)
from paste.evalexception import EvalException
exc_wrapped_app = EvalException(wrapped_app)
```
Which shows how to do it in a very simple way. I understand how this works, however it seems too simple when working with a number of middleware packages.
**Is there a better way to manage how these middleware components are added to the stack? Maybe a common design pattern which reads from a config file?** | 2009/10/27 | [
"https://Stackoverflow.com/questions/1633342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30478/"
] | That is what a framework does. Some frameworks like Django are fairly rigid and others like Pylons make it easier to mix and match.
Since you will likely be using some of the WSGI components from the Paste project sooner or later, you might as well read this article from the Paste folks about a [Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html). I'm not suggesting that you should go and build your own framework, but that the article gives a good explanation of how the WSGI stack works and how things go together. | What middleware do you think you need? You may very well not need to include any WSGI ‘middleware’-like components at all. You can perfectly well put together a loose ‘pseudo-framework’ of standalone libraries without needing to ‘wrap’ the application in middleware at all.
(Personally I use a separate form-reading library, data access layer and template engine, none of which know about each other or need to start fiddling with the WSGI `environ`.) |
1,633,342 | After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide *way* more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correct/standard way to manage WSGI middleware in an application.
I'm not looking for framework suggestions, unless its to provide an example of ways to manage WSGI middleware. Nor am I looking for information on how to get a webserver to talk to python -- that bit I understand.
Rather, I'm looking for advice on how one tells python what components/middleware to put into the stack, and in which order. For instance, if I wanted to use:
`Spawning-->memento-->AuthKit-->(?)-->MyApp`
how would I get those components into the right order, and how would I configure an additional item (say Routes) before `MyApp`?
So; Can you advise on the common/correct/standard way of managing what middleware is included in a WSGI stack for a Python application?
**Edit**
Thanks to Michael Dillon for recommending [A Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html), which helps highlight my problem. The [middleware section](http://pythonpaste.org/do-it-yourself-framework.html#give-me-more-middleware) of that document states that one should wrap middleware A in middleware B, B in C, and so-on:
```
app = ObjectPublisher(Root())
wrapped_app = AuthMiddleware(app)
from paste.evalexception import EvalException
exc_wrapped_app = EvalException(wrapped_app)
```
Which shows how to do it in a very simple way. I understand how this works, however it seems too simple when working with a number of middleware packages.
**Is there a better way to manage how these middleware components are added to the stack? Maybe a common design pattern which reads from a config file?** | 2009/10/27 | [
"https://Stackoverflow.com/questions/1633342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30478/"
] | That is what a framework does. Some frameworks like Django are fairly rigid and others like Pylons make it easier to mix and match.
Since you will likely be using some of the WSGI components from the Paste project sooner or later, you might as well read this article from the Paste folks about a [Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html). I'm not suggesting that you should go and build your own framework, but that the article gives a good explanation of how the WSGI stack works and how things go together. | "it seems too simple when working with a number of middleware packages."
How big a number?
You won't be working with hundreds or thousands.
It will be (a) a small number (under a dozen) and (b) the "right" order isn't magical.
Each piece of middleware will have a very, very specific job and very specific requirements for what must come before it.
It's much less confusing than you're assuming. |
1,633,342 | After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide *way* more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correct/standard way to manage WSGI middleware in an application.
I'm not looking for framework suggestions, unless its to provide an example of ways to manage WSGI middleware. Nor am I looking for information on how to get a webserver to talk to python -- that bit I understand.
Rather, I'm looking for advice on how one tells python what components/middleware to put into the stack, and in which order. For instance, if I wanted to use:
`Spawning-->memento-->AuthKit-->(?)-->MyApp`
how would I get those components into the right order, and how would I configure an additional item (say Routes) before `MyApp`?
So; Can you advise on the common/correct/standard way of managing what middleware is included in a WSGI stack for a Python application?
**Edit**
Thanks to Michael Dillon for recommending [A Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html), which helps highlight my problem. The [middleware section](http://pythonpaste.org/do-it-yourself-framework.html#give-me-more-middleware) of that document states that one should wrap middleware A in middleware B, B in C, and so-on:
```
app = ObjectPublisher(Root())
wrapped_app = AuthMiddleware(app)
from paste.evalexception import EvalException
exc_wrapped_app = EvalException(wrapped_app)
```
Which shows how to do it in a very simple way. I understand how this works, however it seems too simple when working with a number of middleware packages.
**Is there a better way to manage how these middleware components are added to the stack? Maybe a common design pattern which reads from a config file?** | 2009/10/27 | [
"https://Stackoverflow.com/questions/1633342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30478/"
] | That is what a framework does. Some frameworks like Django are fairly rigid and others like Pylons make it easier to mix and match.
Since you will likely be using some of the WSGI components from the Paste project sooner or later, you might as well read this article from the Paste folks about a [Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html). I'm not suggesting that you should go and build your own framework, but that the article gives a good explanation of how the WSGI stack works and how things go together. | My advice is to read the [PEP](http://www.python.org/dev/peps/pep-0333/) on WSGI, specifically the part on [middleware](http://www.python.org/dev/peps/pep-0333/#middleware-components-that-play-both-sides). If you have a question about anything with the words "standard" and "WSGI" in it, the answer is either there, or you're asking the wrong question. |
1,633,342 | After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide *way* more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correct/standard way to manage WSGI middleware in an application.
I'm not looking for framework suggestions, unless its to provide an example of ways to manage WSGI middleware. Nor am I looking for information on how to get a webserver to talk to python -- that bit I understand.
Rather, I'm looking for advice on how one tells python what components/middleware to put into the stack, and in which order. For instance, if I wanted to use:
`Spawning-->memento-->AuthKit-->(?)-->MyApp`
how would I get those components into the right order, and how would I configure an additional item (say Routes) before `MyApp`?
So; Can you advise on the common/correct/standard way of managing what middleware is included in a WSGI stack for a Python application?
**Edit**
Thanks to Michael Dillon for recommending [A Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html), which helps highlight my problem. The [middleware section](http://pythonpaste.org/do-it-yourself-framework.html#give-me-more-middleware) of that document states that one should wrap middleware A in middleware B, B in C, and so-on:
```
app = ObjectPublisher(Root())
wrapped_app = AuthMiddleware(app)
from paste.evalexception import EvalException
exc_wrapped_app = EvalException(wrapped_app)
```
Which shows how to do it in a very simple way. I understand how this works, however it seems too simple when working with a number of middleware packages.
**Is there a better way to manage how these middleware components are added to the stack? Maybe a common design pattern which reads from a config file?** | 2009/10/27 | [
"https://Stackoverflow.com/questions/1633342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30478/"
] | I'd have to say that Apache/mod\_wsgi is probably the most "manageable" of the setups I've used.
nginx/fcgi is the fastest, but its a bit of a headache. | If you liked the Do-It-Yourself-Framework tutorial mentioned before, but you want to manage these things in a config file, [Paste Deploy](http://pythonpaste.org/deploy/) would be the obvious answer. (It is mentioned in the tutorial, but only very briefly in the very last paragraph).
This is what the Pylons framework uses, by the way (and Turbogears 2, which is built upon Pylons, also). |
1,633,342 | After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide *way* more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correct/standard way to manage WSGI middleware in an application.
I'm not looking for framework suggestions, unless its to provide an example of ways to manage WSGI middleware. Nor am I looking for information on how to get a webserver to talk to python -- that bit I understand.
Rather, I'm looking for advice on how one tells python what components/middleware to put into the stack, and in which order. For instance, if I wanted to use:
`Spawning-->memento-->AuthKit-->(?)-->MyApp`
how would I get those components into the right order, and how would I configure an additional item (say Routes) before `MyApp`?
So; Can you advise on the common/correct/standard way of managing what middleware is included in a WSGI stack for a Python application?
**Edit**
Thanks to Michael Dillon for recommending [A Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html), which helps highlight my problem. The [middleware section](http://pythonpaste.org/do-it-yourself-framework.html#give-me-more-middleware) of that document states that one should wrap middleware A in middleware B, B in C, and so-on:
```
app = ObjectPublisher(Root())
wrapped_app = AuthMiddleware(app)
from paste.evalexception import EvalException
exc_wrapped_app = EvalException(wrapped_app)
```
Which shows how to do it in a very simple way. I understand how this works, however it seems too simple when working with a number of middleware packages.
**Is there a better way to manage how these middleware components are added to the stack? Maybe a common design pattern which reads from a config file?** | 2009/10/27 | [
"https://Stackoverflow.com/questions/1633342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30478/"
] | That is what a framework does. Some frameworks like Django are fairly rigid and others like Pylons make it easier to mix and match.
Since you will likely be using some of the WSGI components from the Paste project sooner or later, you might as well read this article from the Paste folks about a [Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html). I'm not suggesting that you should go and build your own framework, but that the article gives a good explanation of how the WSGI stack works and how things go together. | If you liked the Do-It-Yourself-Framework tutorial mentioned before, but you want to manage these things in a config file, [Paste Deploy](http://pythonpaste.org/deploy/) would be the obvious answer. (It is mentioned in the tutorial, but only very briefly in the very last paragraph).
This is what the Pylons framework uses, by the way (and Turbogears 2, which is built upon Pylons, also). |
1,633,342 | After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide *way* more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correct/standard way to manage WSGI middleware in an application.
I'm not looking for framework suggestions, unless its to provide an example of ways to manage WSGI middleware. Nor am I looking for information on how to get a webserver to talk to python -- that bit I understand.
Rather, I'm looking for advice on how one tells python what components/middleware to put into the stack, and in which order. For instance, if I wanted to use:
`Spawning-->memento-->AuthKit-->(?)-->MyApp`
how would I get those components into the right order, and how would I configure an additional item (say Routes) before `MyApp`?
So; Can you advise on the common/correct/standard way of managing what middleware is included in a WSGI stack for a Python application?
**Edit**
Thanks to Michael Dillon for recommending [A Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html), which helps highlight my problem. The [middleware section](http://pythonpaste.org/do-it-yourself-framework.html#give-me-more-middleware) of that document states that one should wrap middleware A in middleware B, B in C, and so-on:
```
app = ObjectPublisher(Root())
wrapped_app = AuthMiddleware(app)
from paste.evalexception import EvalException
exc_wrapped_app = EvalException(wrapped_app)
```
Which shows how to do it in a very simple way. I understand how this works, however it seems too simple when working with a number of middleware packages.
**Is there a better way to manage how these middleware components are added to the stack? Maybe a common design pattern which reads from a config file?** | 2009/10/27 | [
"https://Stackoverflow.com/questions/1633342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30478/"
] | That is what a framework does. Some frameworks like Django are fairly rigid and others like Pylons make it easier to mix and match.
Since you will likely be using some of the WSGI components from the Paste project sooner or later, you might as well read this article from the Paste folks about a [Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html). I'm not suggesting that you should go and build your own framework, but that the article gives a good explanation of how the WSGI stack works and how things go together. | I'd have to say that Apache/mod\_wsgi is probably the most "manageable" of the setups I've used.
nginx/fcgi is the fastest, but its a bit of a headache. |
1,633,342 | After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide *way* more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correct/standard way to manage WSGI middleware in an application.
I'm not looking for framework suggestions, unless its to provide an example of ways to manage WSGI middleware. Nor am I looking for information on how to get a webserver to talk to python -- that bit I understand.
Rather, I'm looking for advice on how one tells python what components/middleware to put into the stack, and in which order. For instance, if I wanted to use:
`Spawning-->memento-->AuthKit-->(?)-->MyApp`
how would I get those components into the right order, and how would I configure an additional item (say Routes) before `MyApp`?
So; Can you advise on the common/correct/standard way of managing what middleware is included in a WSGI stack for a Python application?
**Edit**
Thanks to Michael Dillon for recommending [A Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html), which helps highlight my problem. The [middleware section](http://pythonpaste.org/do-it-yourself-framework.html#give-me-more-middleware) of that document states that one should wrap middleware A in middleware B, B in C, and so-on:
```
app = ObjectPublisher(Root())
wrapped_app = AuthMiddleware(app)
from paste.evalexception import EvalException
exc_wrapped_app = EvalException(wrapped_app)
```
Which shows how to do it in a very simple way. I understand how this works, however it seems too simple when working with a number of middleware packages.
**Is there a better way to manage how these middleware components are added to the stack? Maybe a common design pattern which reads from a config file?** | 2009/10/27 | [
"https://Stackoverflow.com/questions/1633342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30478/"
] | I'd have to say that Apache/mod\_wsgi is probably the most "manageable" of the setups I've used.
nginx/fcgi is the fastest, but its a bit of a headache. | My advice is to read the [PEP](http://www.python.org/dev/peps/pep-0333/) on WSGI, specifically the part on [middleware](http://www.python.org/dev/peps/pep-0333/#middleware-components-that-play-both-sides). If you have a question about anything with the words "standard" and "WSGI" in it, the answer is either there, or you're asking the wrong question. |
1,633,342 | After looking through the many useful and shiny Python frameworks, I find none of them get close to what I need or provide *way* more than my needs. I'm looking to put something together myself; could define it as a framework, but not full-stack. However, I can't find online what the Python community sees as the correct/standard way to manage WSGI middleware in an application.
I'm not looking for framework suggestions, unless its to provide an example of ways to manage WSGI middleware. Nor am I looking for information on how to get a webserver to talk to python -- that bit I understand.
Rather, I'm looking for advice on how one tells python what components/middleware to put into the stack, and in which order. For instance, if I wanted to use:
`Spawning-->memento-->AuthKit-->(?)-->MyApp`
how would I get those components into the right order, and how would I configure an additional item (say Routes) before `MyApp`?
So; Can you advise on the common/correct/standard way of managing what middleware is included in a WSGI stack for a Python application?
**Edit**
Thanks to Michael Dillon for recommending [A Do-It-Yourself Framework](http://pythonpaste.org/do-it-yourself-framework.html), which helps highlight my problem. The [middleware section](http://pythonpaste.org/do-it-yourself-framework.html#give-me-more-middleware) of that document states that one should wrap middleware A in middleware B, B in C, and so-on:
```
app = ObjectPublisher(Root())
wrapped_app = AuthMiddleware(app)
from paste.evalexception import EvalException
exc_wrapped_app = EvalException(wrapped_app)
```
Which shows how to do it in a very simple way. I understand how this works, however it seems too simple when working with a number of middleware packages.
**Is there a better way to manage how these middleware components are added to the stack? Maybe a common design pattern which reads from a config file?** | 2009/10/27 | [
"https://Stackoverflow.com/questions/1633342",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30478/"
] | What middleware do you think you need? You may very well not need to include any WSGI ‘middleware’-like components at all. You can perfectly well put together a loose ‘pseudo-framework’ of standalone libraries without needing to ‘wrap’ the application in middleware at all.
(Personally I use a separate form-reading library, data access layer and template engine, none of which know about each other or need to start fiddling with the WSGI `environ`.) | "it seems too simple when working with a number of middleware packages."
How big a number?
You won't be working with hundreds or thousands.
It will be (a) a small number (under a dozen) and (b) the "right" order isn't magical.
Each piece of middleware will have a very, very specific job and very specific requirements for what must come before it.
It's much less confusing than you're assuming. |
2,682,940 | Particle, initially at rest travels in a straight line and its acceleration satisfies $$a=0.1(t-5)^2 $$for $0\leq t\leq5$
Find its average speed. during the first$5$ seconds.
I don't expect answers as this clearly is a homework, just a hint what formulas to use to find the answer. Initially I thought that it is $$\frac{\text{final velocity-initial velocity}}{2}$$
but my answer and books answer is different. | 2018/03/08 | [
"https://math.stackexchange.com/questions/2682940",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/182383/"
] | **HINT**
We need to consider an integral average for the speed $|v(t)|$ with $a(t)=\frac{dv(t)}{dt}$ for $t\in[0,5]$, that is
$$\frac{\int\_0^5 |v(t)| dt}{5}$$ | Your formula is only valid if the acceleration is constant, which it is not in your case. Hint:
The average value of a function on $[a,b]$ is
\begin{align}
\frac{1}{b-a}\int\_a^b f(x)\,dx
\end{align} |
2,682,940 | Particle, initially at rest travels in a straight line and its acceleration satisfies $$a=0.1(t-5)^2 $$for $0\leq t\leq5$
Find its average speed. during the first$5$ seconds.
I don't expect answers as this clearly is a homework, just a hint what formulas to use to find the answer. Initially I thought that it is $$\frac{\text{final velocity-initial velocity}}{2}$$
but my answer and books answer is different. | 2018/03/08 | [
"https://math.stackexchange.com/questions/2682940",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/182383/"
] | **HINT**
We need to consider an integral average for the speed $|v(t)|$ with $a(t)=\frac{dv(t)}{dt}$ for $t\in[0,5]$, that is
$$\frac{\int\_0^5 |v(t)| dt}{5}$$ | Velocity is different from speed. For average speed, you'll need to use the equation of $\frac{d}{\Delta t}$. Where d is the sum of all the absolute displacements (also the total distance travelled). So, the hint here is likely you'll need to consider cases since positive and negative displacement shouldn't cancel out each other as they both contribute to the distance. |
2,682,940 | Particle, initially at rest travels in a straight line and its acceleration satisfies $$a=0.1(t-5)^2 $$for $0\leq t\leq5$
Find its average speed. during the first$5$ seconds.
I don't expect answers as this clearly is a homework, just a hint what formulas to use to find the answer. Initially I thought that it is $$\frac{\text{final velocity-initial velocity}}{2}$$
but my answer and books answer is different. | 2018/03/08 | [
"https://math.stackexchange.com/questions/2682940",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/182383/"
] | **HINT**
We need to consider an integral average for the speed $|v(t)|$ with $a(t)=\frac{dv(t)}{dt}$ for $t\in[0,5]$, that is
$$\frac{\int\_0^5 |v(t)| dt}{5}$$ | The average speed is the total distance travelled divided by the time.
Integrating once we get an expression for the velocity, namely $$v=\frac{0.1}{3}\left[(t-5)^3+125\right]$$
Integrating again gives displacement, or in this case, distance travelled, since the motion is not reversed in the first $5$ seconds:
$$s=\frac{0.1}{3}\left[\frac 14(t-5)^4+125t\right]\_0^5$$
Evaluating this and dividing by $5$ gives the answer $3.125$ |
2,682,940 | Particle, initially at rest travels in a straight line and its acceleration satisfies $$a=0.1(t-5)^2 $$for $0\leq t\leq5$
Find its average speed. during the first$5$ seconds.
I don't expect answers as this clearly is a homework, just a hint what formulas to use to find the answer. Initially I thought that it is $$\frac{\text{final velocity-initial velocity}}{2}$$
but my answer and books answer is different. | 2018/03/08 | [
"https://math.stackexchange.com/questions/2682940",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/182383/"
] | Your formula is only valid if the acceleration is constant, which it is not in your case. Hint:
The average value of a function on $[a,b]$ is
\begin{align}
\frac{1}{b-a}\int\_a^b f(x)\,dx
\end{align} | Velocity is different from speed. For average speed, you'll need to use the equation of $\frac{d}{\Delta t}$. Where d is the sum of all the absolute displacements (also the total distance travelled). So, the hint here is likely you'll need to consider cases since positive and negative displacement shouldn't cancel out each other as they both contribute to the distance. |
2,682,940 | Particle, initially at rest travels in a straight line and its acceleration satisfies $$a=0.1(t-5)^2 $$for $0\leq t\leq5$
Find its average speed. during the first$5$ seconds.
I don't expect answers as this clearly is a homework, just a hint what formulas to use to find the answer. Initially I thought that it is $$\frac{\text{final velocity-initial velocity}}{2}$$
but my answer and books answer is different. | 2018/03/08 | [
"https://math.stackexchange.com/questions/2682940",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/182383/"
] | Your formula is only valid if the acceleration is constant, which it is not in your case. Hint:
The average value of a function on $[a,b]$ is
\begin{align}
\frac{1}{b-a}\int\_a^b f(x)\,dx
\end{align} | The average speed is the total distance travelled divided by the time.
Integrating once we get an expression for the velocity, namely $$v=\frac{0.1}{3}\left[(t-5)^3+125\right]$$
Integrating again gives displacement, or in this case, distance travelled, since the motion is not reversed in the first $5$ seconds:
$$s=\frac{0.1}{3}\left[\frac 14(t-5)^4+125t\right]\_0^5$$
Evaluating this and dividing by $5$ gives the answer $3.125$ |
2,682,940 | Particle, initially at rest travels in a straight line and its acceleration satisfies $$a=0.1(t-5)^2 $$for $0\leq t\leq5$
Find its average speed. during the first$5$ seconds.
I don't expect answers as this clearly is a homework, just a hint what formulas to use to find the answer. Initially I thought that it is $$\frac{\text{final velocity-initial velocity}}{2}$$
but my answer and books answer is different. | 2018/03/08 | [
"https://math.stackexchange.com/questions/2682940",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/182383/"
] | The average speed is the total distance travelled divided by the time.
Integrating once we get an expression for the velocity, namely $$v=\frac{0.1}{3}\left[(t-5)^3+125\right]$$
Integrating again gives displacement, or in this case, distance travelled, since the motion is not reversed in the first $5$ seconds:
$$s=\frac{0.1}{3}\left[\frac 14(t-5)^4+125t\right]\_0^5$$
Evaluating this and dividing by $5$ gives the answer $3.125$ | Velocity is different from speed. For average speed, you'll need to use the equation of $\frac{d}{\Delta t}$. Where d is the sum of all the absolute displacements (also the total distance travelled). So, the hint here is likely you'll need to consider cases since positive and negative displacement shouldn't cancel out each other as they both contribute to the distance. |
12,015,674 | I'm trying to use the facebook api to get the app user's profile pic and then save it on the server. I'm getting the image just fine, but creating a new image file and saving it in the correct folder seems to be a problem. I tried using the fopen and file\_put\_contents functions, but apparently they require that a file be created before hand. How can I save the fb user's image on the server? My code is as follows.
```
$facebook = new Facebook(array(
'appId' => '12345',
'secret' => '12345',
'cookie' => true
));
$access_token = $facebook->getAccessToken();
if($access_token != "")
{
$user = $facebook->getUser();
if($user != 0)
{
$user_profile = $facebook->api('/me');
$fb_id = $user_profile['id'];
$fb_first_name = $user_profile['first_name'];
$fb_last_name = $user_profile['last_name'];
$fb_email = $user_profile['email'];
$img = file_get_contents('https://graph.facebook.com/'.$fb_id.'/picture?type=large');
$file = '/img/profile_pics/large/';
rename($img, "".$file."".$img."");
}
```
Any suggestions?
Thanks,
Lance | 2012/08/18 | [
"https://Stackoverflow.com/questions/12015674",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/506825/"
] | Using `$img = file_get_contents(...)` img will contain the source of the image just save that to a file, `rename()` wont work.
Just do:
```
error_reporting(E_ALL);//For debugging, in case something else
$img_data = file_get_contents('https://graph.facebook.com/'.$fb_id.'/picture?type=large');
$save_path = '/img/profile_pics/large/';
if(!file_exists($save_path)){
die('Folder path does not exist');
}else{
file_put_contents($save_path.$fb_id.'.jpg',$img_data);
}
``` | First of all, make sure the directory where you're trying to create the images is writable, otherwise give it the proper chmod.
Like Lawrence said, the $img variable in your code doesn't actually contain the filename, but the image itself. For you to save it in a file, you would have to pass it to file\_put\_contents as a second argument, and the filename as the first :
```
file_put_contents('image.ext', $img);
```
Or in this case :
```
file_put_contents($file.'/image.ext', $img);
```
To save it in the same directory as the PHP script, you can use the `__DIR__` constant to get the absolute path :
```
file_put_contents(__DIR__.'/image.ext', $img);
``` |
20,424,796 | Let me give you an overview of my project first. I have a pdf which I need to convert into images(One image for one page) using `PDFBox` API and write all those images onto a new pdf using `PDFBox` API itself. Basically, converting a pdf into a pdf, which we refer to as PDF Transcoding.
For certain pdfs, which contain JBIG2 images, PDFbox implementation of `convertToImage()` method is failing silently without any exceptions or errors and finally, producing a PDF, but this time, just with blank content(white). The message I am getting on the console is:
```
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.filter.JBIG2Filter decode
SEVERE: Can't find an ImageIO plugin to decode the JBIG2 encoded datastream.
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap getRGBImage
SEVERE: Something went wrong ... the pixelmap doesn't contain any data.
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.util.operator.pagedrawer.Invoke process
WARNING: getRGBImage returned NULL
```
I need to know how to resolve this issue? We have something like:
```
import org.apache.pdfbox.filter.JBIG2Filter;
```
which I don't know how to implement.
I am searching on that, but to no avail. Could anyone please suggest? | 2013/12/06 | [
"https://Stackoverflow.com/questions/20424796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2781882/"
] | Take a look at this ticket in PDFBox <https://issues.apache.org/jira/browse/PDFBOX-1067> . I think the answer to your question is:
1. to make sure that you have JAI and the JAI-ImageIO plugins installed for your version of Java: decent installation instructions are available here: <http://docs.geoserver.org/latest/en/user/production/java.html>
2. to use the JBIG2-imageio plugin, (newer versions are licensed under the Apache2 license) <https://github.com/levigo/jbig2-imageio/> | I had the exact same problem.
I downloaded the jar from
[jbig2-imageio](https://github.com/levigo/jbig2-imageio/)
and I just included it in my project's application libraries, and it worked right out of the box. As adam said, it uses GPL3. |
20,424,796 | Let me give you an overview of my project first. I have a pdf which I need to convert into images(One image for one page) using `PDFBox` API and write all those images onto a new pdf using `PDFBox` API itself. Basically, converting a pdf into a pdf, which we refer to as PDF Transcoding.
For certain pdfs, which contain JBIG2 images, PDFbox implementation of `convertToImage()` method is failing silently without any exceptions or errors and finally, producing a PDF, but this time, just with blank content(white). The message I am getting on the console is:
```
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.filter.JBIG2Filter decode
SEVERE: Can't find an ImageIO plugin to decode the JBIG2 encoded datastream.
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap getRGBImage
SEVERE: Something went wrong ... the pixelmap doesn't contain any data.
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.util.operator.pagedrawer.Invoke process
WARNING: getRGBImage returned NULL
```
I need to know how to resolve this issue? We have something like:
```
import org.apache.pdfbox.filter.JBIG2Filter;
```
which I don't know how to implement.
I am searching on that, but to no avail. Could anyone please suggest? | 2013/12/06 | [
"https://Stackoverflow.com/questions/20424796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2781882/"
] | Take a look at this ticket in PDFBox <https://issues.apache.org/jira/browse/PDFBOX-1067> . I think the answer to your question is:
1. to make sure that you have JAI and the JAI-ImageIO plugins installed for your version of Java: decent installation instructions are available here: <http://docs.geoserver.org/latest/en/user/production/java.html>
2. to use the JBIG2-imageio plugin, (newer versions are licensed under the Apache2 license) <https://github.com/levigo/jbig2-imageio/> | Installing the JAI seems not needed.
I only needed to download the levigo-jbig2-imageio-1.6.5.jar, place it in the folder of my dependency-jars and in eclipse add it to the java build path libraries.
<https://github.com/levigo/jbig2-imageio/> |
20,424,796 | Let me give you an overview of my project first. I have a pdf which I need to convert into images(One image for one page) using `PDFBox` API and write all those images onto a new pdf using `PDFBox` API itself. Basically, converting a pdf into a pdf, which we refer to as PDF Transcoding.
For certain pdfs, which contain JBIG2 images, PDFbox implementation of `convertToImage()` method is failing silently without any exceptions or errors and finally, producing a PDF, but this time, just with blank content(white). The message I am getting on the console is:
```
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.filter.JBIG2Filter decode
SEVERE: Can't find an ImageIO plugin to decode the JBIG2 encoded datastream.
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap getRGBImage
SEVERE: Something went wrong ... the pixelmap doesn't contain any data.
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.util.operator.pagedrawer.Invoke process
WARNING: getRGBImage returned NULL
```
I need to know how to resolve this issue? We have something like:
```
import org.apache.pdfbox.filter.JBIG2Filter;
```
which I don't know how to implement.
I am searching on that, but to no avail. Could anyone please suggest? | 2013/12/06 | [
"https://Stackoverflow.com/questions/20424796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2781882/"
] | Take a look at this ticket in PDFBox <https://issues.apache.org/jira/browse/PDFBOX-1067> . I think the answer to your question is:
1. to make sure that you have JAI and the JAI-ImageIO plugins installed for your version of Java: decent installation instructions are available here: <http://docs.geoserver.org/latest/en/user/production/java.html>
2. to use the JBIG2-imageio plugin, (newer versions are licensed under the Apache2 license) <https://github.com/levigo/jbig2-imageio/> | ```
import java.awt.image.BufferedImage
import org.apache.pdfbox.cos.COSName
import org.apache.pdfbox.pdmodel.PDDocument
import org.apache.pdfbox.pdmodel.PDPage
import org.apache.pdfbox.pdmodel.PDPageTree
import org.apache.pdfbox.pdmodel.PDResources
import org.apache.pdfbox.pdmodel.graphics.PDXObject
import org.apache.pdfbox.rendering.ImageType
import org.apache.pdfbox.rendering.PDFRenderer
import org.apache.pdfbox.tools.imageio.ImageIOUtil
import javax.imageio.ImageIO
import javax.imageio.spi.IIORegistry
import javax.imageio.spi.ImageReaderSpi
import javax.swing.*
import javax.swing.filechooser.FileNameExtensionFilter
public class savePDFAsImage{
String path = "c:/pdfImage/"
//allow pdf file selection for extracting
public static File selectPDF() {
File file = null
JFileChooser chooser = new JFileChooser()
FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF", "pdf")
chooser.setFileFilter(filter)
chooser.setMultiSelectionEnabled(false)
int returnVal = chooser.showOpenDialog(null)
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile()
println "Please wait..."
}
return file
}
public static void main(String[] args) {
try {
// help to view list of plugin registered. check by adding JBig2 plugin and JAI plugin
ImageIO.scanForPlugins()
IIORegistry reg = IIORegistry.getDefaultInstance()
Iterator spIt = reg.getServiceProviders(ImageReaderSpi.class, false)
spIt.each(){
println it.getProperties()
}
testPDFBoxSaveAsImage()
testPDFBoxExtractImagesX()
} catch (Exception e) {
e.printStackTrace()
}
}
public static void testPDFBoxExtractImagesX() throws Exception {
PDDocument document = PDDocument.load(selectPDF())
PDPageTree list = document.getPages()
for (PDPage page : list) {
PDResources pdResources = page.getResources()
for (COSName c : pdResources.getXObjectNames()) {
PDXObject o = pdResources.getXObject(c)
if (o instanceof org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject) {
File file = new File( + System.nanoTime() + ".png")
ImageIO.write(((org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject) o).getImage(), "png", file)
}
}
}
document.close()
println "Extraction complete"
}
public static void testPDFBoxSaveAsImage() throws Exception {
PDDocument document = PDDocument.load(selectPDF().getBytes())
PDFRenderer pdfRenderer = new PDFRenderer(document)
for (int page = 0; page < document.getNumberOfPages(); ++page) {
BufferedImage bim = pdfRenderer.renderImageWithDPI(page,300, ImageType.BINARY)
// suffix in filename will be used as the file format
OutputStream fileOutputStream = new FileOutputStream(+ System.nanoTime() + ".png")
boolean b = ImageIOUtil.writeImage(bim, "png",fileOutputStream,300)
}
document.close()
println "Extraction complete"
}
}
``` |
20,424,796 | Let me give you an overview of my project first. I have a pdf which I need to convert into images(One image for one page) using `PDFBox` API and write all those images onto a new pdf using `PDFBox` API itself. Basically, converting a pdf into a pdf, which we refer to as PDF Transcoding.
For certain pdfs, which contain JBIG2 images, PDFbox implementation of `convertToImage()` method is failing silently without any exceptions or errors and finally, producing a PDF, but this time, just with blank content(white). The message I am getting on the console is:
```
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.filter.JBIG2Filter decode
SEVERE: Can't find an ImageIO plugin to decode the JBIG2 encoded datastream.
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap getRGBImage
SEVERE: Something went wrong ... the pixelmap doesn't contain any data.
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.util.operator.pagedrawer.Invoke process
WARNING: getRGBImage returned NULL
```
I need to know how to resolve this issue? We have something like:
```
import org.apache.pdfbox.filter.JBIG2Filter;
```
which I don't know how to implement.
I am searching on that, but to no avail. Could anyone please suggest? | 2013/12/06 | [
"https://Stackoverflow.com/questions/20424796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2781882/"
] | Take a look at this ticket in PDFBox <https://issues.apache.org/jira/browse/PDFBOX-1067> . I think the answer to your question is:
1. to make sure that you have JAI and the JAI-ImageIO plugins installed for your version of Java: decent installation instructions are available here: <http://docs.geoserver.org/latest/en/user/production/java.html>
2. to use the JBIG2-imageio plugin, (newer versions are licensed under the Apache2 license) <https://github.com/levigo/jbig2-imageio/> | I had the same problem and I fixed it by adding this dependency in my pom.xml :
```
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>jbig2-imageio</artifactId>
<version>3.0.2</version>
</dependency>
```
Good luck. |
20,424,796 | Let me give you an overview of my project first. I have a pdf which I need to convert into images(One image for one page) using `PDFBox` API and write all those images onto a new pdf using `PDFBox` API itself. Basically, converting a pdf into a pdf, which we refer to as PDF Transcoding.
For certain pdfs, which contain JBIG2 images, PDFbox implementation of `convertToImage()` method is failing silently without any exceptions or errors and finally, producing a PDF, but this time, just with blank content(white). The message I am getting on the console is:
```
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.filter.JBIG2Filter decode
SEVERE: Can't find an ImageIO plugin to decode the JBIG2 encoded datastream.
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap getRGBImage
SEVERE: Something went wrong ... the pixelmap doesn't contain any data.
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.util.operator.pagedrawer.Invoke process
WARNING: getRGBImage returned NULL
```
I need to know how to resolve this issue? We have something like:
```
import org.apache.pdfbox.filter.JBIG2Filter;
```
which I don't know how to implement.
I am searching on that, but to no avail. Could anyone please suggest? | 2013/12/06 | [
"https://Stackoverflow.com/questions/20424796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2781882/"
] | I had the exact same problem.
I downloaded the jar from
[jbig2-imageio](https://github.com/levigo/jbig2-imageio/)
and I just included it in my project's application libraries, and it worked right out of the box. As adam said, it uses GPL3. | Installing the JAI seems not needed.
I only needed to download the levigo-jbig2-imageio-1.6.5.jar, place it in the folder of my dependency-jars and in eclipse add it to the java build path libraries.
<https://github.com/levigo/jbig2-imageio/> |
20,424,796 | Let me give you an overview of my project first. I have a pdf which I need to convert into images(One image for one page) using `PDFBox` API and write all those images onto a new pdf using `PDFBox` API itself. Basically, converting a pdf into a pdf, which we refer to as PDF Transcoding.
For certain pdfs, which contain JBIG2 images, PDFbox implementation of `convertToImage()` method is failing silently without any exceptions or errors and finally, producing a PDF, but this time, just with blank content(white). The message I am getting on the console is:
```
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.filter.JBIG2Filter decode
SEVERE: Can't find an ImageIO plugin to decode the JBIG2 encoded datastream.
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap getRGBImage
SEVERE: Something went wrong ... the pixelmap doesn't contain any data.
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.util.operator.pagedrawer.Invoke process
WARNING: getRGBImage returned NULL
```
I need to know how to resolve this issue? We have something like:
```
import org.apache.pdfbox.filter.JBIG2Filter;
```
which I don't know how to implement.
I am searching on that, but to no avail. Could anyone please suggest? | 2013/12/06 | [
"https://Stackoverflow.com/questions/20424796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2781882/"
] | I had the exact same problem.
I downloaded the jar from
[jbig2-imageio](https://github.com/levigo/jbig2-imageio/)
and I just included it in my project's application libraries, and it worked right out of the box. As adam said, it uses GPL3. | ```
import java.awt.image.BufferedImage
import org.apache.pdfbox.cos.COSName
import org.apache.pdfbox.pdmodel.PDDocument
import org.apache.pdfbox.pdmodel.PDPage
import org.apache.pdfbox.pdmodel.PDPageTree
import org.apache.pdfbox.pdmodel.PDResources
import org.apache.pdfbox.pdmodel.graphics.PDXObject
import org.apache.pdfbox.rendering.ImageType
import org.apache.pdfbox.rendering.PDFRenderer
import org.apache.pdfbox.tools.imageio.ImageIOUtil
import javax.imageio.ImageIO
import javax.imageio.spi.IIORegistry
import javax.imageio.spi.ImageReaderSpi
import javax.swing.*
import javax.swing.filechooser.FileNameExtensionFilter
public class savePDFAsImage{
String path = "c:/pdfImage/"
//allow pdf file selection for extracting
public static File selectPDF() {
File file = null
JFileChooser chooser = new JFileChooser()
FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF", "pdf")
chooser.setFileFilter(filter)
chooser.setMultiSelectionEnabled(false)
int returnVal = chooser.showOpenDialog(null)
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile()
println "Please wait..."
}
return file
}
public static void main(String[] args) {
try {
// help to view list of plugin registered. check by adding JBig2 plugin and JAI plugin
ImageIO.scanForPlugins()
IIORegistry reg = IIORegistry.getDefaultInstance()
Iterator spIt = reg.getServiceProviders(ImageReaderSpi.class, false)
spIt.each(){
println it.getProperties()
}
testPDFBoxSaveAsImage()
testPDFBoxExtractImagesX()
} catch (Exception e) {
e.printStackTrace()
}
}
public static void testPDFBoxExtractImagesX() throws Exception {
PDDocument document = PDDocument.load(selectPDF())
PDPageTree list = document.getPages()
for (PDPage page : list) {
PDResources pdResources = page.getResources()
for (COSName c : pdResources.getXObjectNames()) {
PDXObject o = pdResources.getXObject(c)
if (o instanceof org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject) {
File file = new File( + System.nanoTime() + ".png")
ImageIO.write(((org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject) o).getImage(), "png", file)
}
}
}
document.close()
println "Extraction complete"
}
public static void testPDFBoxSaveAsImage() throws Exception {
PDDocument document = PDDocument.load(selectPDF().getBytes())
PDFRenderer pdfRenderer = new PDFRenderer(document)
for (int page = 0; page < document.getNumberOfPages(); ++page) {
BufferedImage bim = pdfRenderer.renderImageWithDPI(page,300, ImageType.BINARY)
// suffix in filename will be used as the file format
OutputStream fileOutputStream = new FileOutputStream(+ System.nanoTime() + ".png")
boolean b = ImageIOUtil.writeImage(bim, "png",fileOutputStream,300)
}
document.close()
println "Extraction complete"
}
}
``` |
20,424,796 | Let me give you an overview of my project first. I have a pdf which I need to convert into images(One image for one page) using `PDFBox` API and write all those images onto a new pdf using `PDFBox` API itself. Basically, converting a pdf into a pdf, which we refer to as PDF Transcoding.
For certain pdfs, which contain JBIG2 images, PDFbox implementation of `convertToImage()` method is failing silently without any exceptions or errors and finally, producing a PDF, but this time, just with blank content(white). The message I am getting on the console is:
```
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.filter.JBIG2Filter decode
SEVERE: Can't find an ImageIO plugin to decode the JBIG2 encoded datastream.
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap getRGBImage
SEVERE: Something went wrong ... the pixelmap doesn't contain any data.
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.util.operator.pagedrawer.Invoke process
WARNING: getRGBImage returned NULL
```
I need to know how to resolve this issue? We have something like:
```
import org.apache.pdfbox.filter.JBIG2Filter;
```
which I don't know how to implement.
I am searching on that, but to no avail. Could anyone please suggest? | 2013/12/06 | [
"https://Stackoverflow.com/questions/20424796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2781882/"
] | I had the same problem and I fixed it by adding this dependency in my pom.xml :
```
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>jbig2-imageio</artifactId>
<version>3.0.2</version>
</dependency>
```
Good luck. | I had the exact same problem.
I downloaded the jar from
[jbig2-imageio](https://github.com/levigo/jbig2-imageio/)
and I just included it in my project's application libraries, and it worked right out of the box. As adam said, it uses GPL3. |
20,424,796 | Let me give you an overview of my project first. I have a pdf which I need to convert into images(One image for one page) using `PDFBox` API and write all those images onto a new pdf using `PDFBox` API itself. Basically, converting a pdf into a pdf, which we refer to as PDF Transcoding.
For certain pdfs, which contain JBIG2 images, PDFbox implementation of `convertToImage()` method is failing silently without any exceptions or errors and finally, producing a PDF, but this time, just with blank content(white). The message I am getting on the console is:
```
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.filter.JBIG2Filter decode
SEVERE: Can't find an ImageIO plugin to decode the JBIG2 encoded datastream.
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap getRGBImage
SEVERE: Something went wrong ... the pixelmap doesn't contain any data.
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.util.operator.pagedrawer.Invoke process
WARNING: getRGBImage returned NULL
```
I need to know how to resolve this issue? We have something like:
```
import org.apache.pdfbox.filter.JBIG2Filter;
```
which I don't know how to implement.
I am searching on that, but to no avail. Could anyone please suggest? | 2013/12/06 | [
"https://Stackoverflow.com/questions/20424796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2781882/"
] | I had the same problem and I fixed it by adding this dependency in my pom.xml :
```
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>jbig2-imageio</artifactId>
<version>3.0.2</version>
</dependency>
```
Good luck. | Installing the JAI seems not needed.
I only needed to download the levigo-jbig2-imageio-1.6.5.jar, place it in the folder of my dependency-jars and in eclipse add it to the java build path libraries.
<https://github.com/levigo/jbig2-imageio/> |
20,424,796 | Let me give you an overview of my project first. I have a pdf which I need to convert into images(One image for one page) using `PDFBox` API and write all those images onto a new pdf using `PDFBox` API itself. Basically, converting a pdf into a pdf, which we refer to as PDF Transcoding.
For certain pdfs, which contain JBIG2 images, PDFbox implementation of `convertToImage()` method is failing silently without any exceptions or errors and finally, producing a PDF, but this time, just with blank content(white). The message I am getting on the console is:
```
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.filter.JBIG2Filter decode
SEVERE: Can't find an ImageIO plugin to decode the JBIG2 encoded datastream.
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.pdmodel.graphics.xobject.PDPixelMap getRGBImage
SEVERE: Something went wrong ... the pixelmap doesn't contain any data.
Dec 06, 2013 5:15:42 PM org.apache.pdfbox.util.operator.pagedrawer.Invoke process
WARNING: getRGBImage returned NULL
```
I need to know how to resolve this issue? We have something like:
```
import org.apache.pdfbox.filter.JBIG2Filter;
```
which I don't know how to implement.
I am searching on that, but to no avail. Could anyone please suggest? | 2013/12/06 | [
"https://Stackoverflow.com/questions/20424796",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2781882/"
] | I had the same problem and I fixed it by adding this dependency in my pom.xml :
```
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>jbig2-imageio</artifactId>
<version>3.0.2</version>
</dependency>
```
Good luck. | ```
import java.awt.image.BufferedImage
import org.apache.pdfbox.cos.COSName
import org.apache.pdfbox.pdmodel.PDDocument
import org.apache.pdfbox.pdmodel.PDPage
import org.apache.pdfbox.pdmodel.PDPageTree
import org.apache.pdfbox.pdmodel.PDResources
import org.apache.pdfbox.pdmodel.graphics.PDXObject
import org.apache.pdfbox.rendering.ImageType
import org.apache.pdfbox.rendering.PDFRenderer
import org.apache.pdfbox.tools.imageio.ImageIOUtil
import javax.imageio.ImageIO
import javax.imageio.spi.IIORegistry
import javax.imageio.spi.ImageReaderSpi
import javax.swing.*
import javax.swing.filechooser.FileNameExtensionFilter
public class savePDFAsImage{
String path = "c:/pdfImage/"
//allow pdf file selection for extracting
public static File selectPDF() {
File file = null
JFileChooser chooser = new JFileChooser()
FileNameExtensionFilter filter = new FileNameExtensionFilter("PDF", "pdf")
chooser.setFileFilter(filter)
chooser.setMultiSelectionEnabled(false)
int returnVal = chooser.showOpenDialog(null)
if (returnVal == JFileChooser.APPROVE_OPTION) {
file = chooser.getSelectedFile()
println "Please wait..."
}
return file
}
public static void main(String[] args) {
try {
// help to view list of plugin registered. check by adding JBig2 plugin and JAI plugin
ImageIO.scanForPlugins()
IIORegistry reg = IIORegistry.getDefaultInstance()
Iterator spIt = reg.getServiceProviders(ImageReaderSpi.class, false)
spIt.each(){
println it.getProperties()
}
testPDFBoxSaveAsImage()
testPDFBoxExtractImagesX()
} catch (Exception e) {
e.printStackTrace()
}
}
public static void testPDFBoxExtractImagesX() throws Exception {
PDDocument document = PDDocument.load(selectPDF())
PDPageTree list = document.getPages()
for (PDPage page : list) {
PDResources pdResources = page.getResources()
for (COSName c : pdResources.getXObjectNames()) {
PDXObject o = pdResources.getXObject(c)
if (o instanceof org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject) {
File file = new File( + System.nanoTime() + ".png")
ImageIO.write(((org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject) o).getImage(), "png", file)
}
}
}
document.close()
println "Extraction complete"
}
public static void testPDFBoxSaveAsImage() throws Exception {
PDDocument document = PDDocument.load(selectPDF().getBytes())
PDFRenderer pdfRenderer = new PDFRenderer(document)
for (int page = 0; page < document.getNumberOfPages(); ++page) {
BufferedImage bim = pdfRenderer.renderImageWithDPI(page,300, ImageType.BINARY)
// suffix in filename will be used as the file format
OutputStream fileOutputStream = new FileOutputStream(+ System.nanoTime() + ".png")
boolean b = ImageIOUtil.writeImage(bim, "png",fileOutputStream,300)
}
document.close()
println "Extraction complete"
}
}
``` |
863,107 | I have two files data.7z.001 and data.7z.002.
l tried to extract them using :
```
7z e asdf data.7z.001
```
l got this error
```
7-Zip [64] 9.20 Copyright (c) 1999-2010 Igor Pavlov 2010-11-18
p7zip Version 9.20 (locale=en_US.UTF-8,Utf16=on,HugeFiles=on,4 CPUs)
Error:
there is no such archive
```
and
```
7z x /home/Desktop/data.7z.001 -tufd.split -o/home/Desktop/
```
error :
```
Error:
Unsupported archive type
```
and
```
7z x /home/Desktop/data.7z.001 -tiso.split -o/home/Desktop/
```
error :
```
Error:
Unsupported archive type
``` | 2016/12/21 | [
"https://askubuntu.com/questions/863107",
"https://askubuntu.com",
"https://askubuntu.com/users/633425/"
] | ```
7z x data.7z.001
```
7z like that will find the others automatically (002 003 and so on) | I continued getting an "Unknown format" error until doing the following:
```
7z e file.7z.001 -tsplit
``` |
69,741 | Mayamalavagowla is the first raga taught to students who learn South Indian Carnatic Music. But I wonder what is the western scale used to represent this Raga ? Why did Carnatic Music system selects this Raga for starting lessons? Is there any advantages or disadvantage with this Raga ? | 2018/04/08 | [
"https://music.stackexchange.com/questions/69741",
"https://music.stackexchange.com",
"https://music.stackexchange.com/users/49365/"
] | I will answer the question in the title, Stinkfoot is right, for other questions (why is this the most common beginning raga taught), it is better to ask them separately.
The name we give to the western scale that uses the same notes as the Raga Mayamalavagowla is the double harmonic scale.
In C, it looks like this:
[](https://i.stack.imgur.com/7CrWt.png)
Obviously, a raga is about more than just the notes, so the details of *Mayamalavagowla* (the order, the importance of the notes, and microtonal inflections) isn't covered by the *Double Harmonic Scale* which is a term which simply describes the 7 notes that makes the scale (and nothing more). I'm not an expert in this, but I know enough to know that a "raga" includes more information that just the scale itself.
*Something to note about this scale is, like the major scale, it is "symmetric". The intervals from the fifth to the tonic are a repeat of the intervals from the tonic to the fourth. So C Db E F and G Ab B C are the same pattern repeated.*
The most well known melody in the west which uses this scale is probably miserlou, a Greek/Turkish folk melody made famous by dick dale's surf rock version and then by the movie pulp fiction, which used it prominently.
In western music the Double Harmonic scale is not a traditional scale, and when it's used, it's often used to give a "middle eastern feel" to music (in film scores for example, music may use this scale to evoke Arabia). That's probably because this scale is very common in middle eastern music (maqam music), where it is known as maqam *hijaz kar*, (although even more common is the slightly different *maqam hijaz* which has a flattened 7th.)
[](https://i.stack.imgur.com/vprBV.png)
This scale is known as the "Phrygian Dominant Scale" and is very common in both Arabic/Turkish/Persian music (where it is known as *maqam hijaz*) and Jewish Klezmer music (in Jewish music I'm not sure what it's called, but it's everywhere). Greek folk music uses it a lot too. Again, it is not a traditional "western" scale. | Raga is not equivalent to scale. Scale never explains the acceptable phrases, ascending and descending patterns. |
345,737 | An issue I've seen frequently brought up in the context of Neural Networks in general, and Deep Neural Networks in particular, is that they're "data hungry" - that is they don't perform well unless we have a large data set with which to train the network.
My understanding is that this is due to the fact that NNets, especially Deep NNets, have a large number of degrees of freedom. So as a model, a NNet has a very large number of parameters, and if the number of parameters of the model is large relative to the number of training data points, there is an increased tendency to over fit.
But why isn't this issue solved by regularization? As far as I know NNets can use L1 and L2 regularization and also have their own regularization methods like dropout which can reduce the number of parameters in the network.
Can we choose our regularizations methods such that they enforce parsimony and limit the size of the network?
---
To clarify my thinking: Say we are using a large Deep NNet to try to model our data, but the data set is small and could actually be modeled by a linear model. Then why don't the network weights converge in such a way that one neuron simulates the linear regression and all the others converge to zeros? Why doesn't regularization help with this? | 2018/05/11 | [
"https://stats.stackexchange.com/questions/345737",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/89649/"
] | I would say that at a high level, the inductive bias of DNNs (deep neural networks) is powerful but slightly too loose or not opinionated enough. By that I mean that DNNs capture a lot of surface statistics about what is going on, but fail to get to the deeper causal/compositional high level structure. (You could view convolutions as a poor's man inductive bias specification).
In addition, it is believed in the machine learning community that the best way to generalize (making good inferences/predictions with little data) is to find the shortest program that gave rise to the data. But program induction/synthesis is hard and we have no good way of doing it efficiently. So instead we rely on a close approximation which is circuit search, and we know how do that with backpropagation. [Here](https://www.youtube.com/watch?v=9EN_HoEk3KY&t=1m11s), Ilya Sutskever gives an overview of that idea.
---
To illustrate the difference in generalization power of models represented as actual programs vs deep learning models, I'll show the one in this paper: [Simulation as an engine of physical scene understanding](https://pdfs.semanticscholar.org/26f7/d738df74539b8de1e158e1844e5c5cece47f.pdf).
[](https://i.stack.imgur.com/e2cXb.png)
>
> (A) The IPE [intuitive physics engine] model takes inputs (e.g., perception, language, memory, imagery, etc.) that instantiate a distribution over scenes (1), then simulates the effects of physics on the distribution (2), and then aggregates the results for output to other sensorimotor and cognitive faculties (3)
>
>
>
[](https://i.stack.imgur.com/0ExAH.png)
>
> (B) Exp. 1 (Will it fall?) tower stimuli. The tower with the red border is actually delicately balanced, and the other two are the same height, but the blue-bordered one is judged much less likely to fall by the model and people.
>
>
> (C) Probabilistic IPE model (x axis) vs. human judgment averages (y axis) in Exp. 1. See Fig. S3 for correlations for other values of σ and ϕ. Each point represents one tower (with SEM), and the three colored circles correspond to the three towers in B.
>
>
> (D) Ground truth (nonprobabilistic) vs. human judgments (Exp. 1). Because it does not represent uncertainty, it cannot capture people’s judgments for a number of our stimuli, such as the red-bordered tower in B. (Note that these cases may be rare in natural scenes, where configurations tend to be more clearly stable or unstable and the IPE would be expected to correlate better with ground truth than it does on our stimuli.)
>
>
>
My point here is that the fit in C is really good, because the model captures the right biases about how humans make physical judgments. This is in big part because it models actual physics (remember that it **is** a actual physics engine) and can deal with uncertainty.
Now the obvious question is: can you do that with deep learning? This is what Lerer et al did in this work: [Learning Physical Intuition of Block Towers by Example](https://arxiv.org/abs/1603.01312)
Their model:
[](https://i.stack.imgur.com/0fr1v.png)
Their model is actually pretty good on the task at hand (predicting the number of falling blocks, and even their falling direction)
[](https://i.stack.imgur.com/coz1f.png)
But it suffers two major drawbacks:
* It needs a huge amount of data to train properly
* In generalizes only in shallow ways: you can transfer to more realistic looking images, add or remove 1 or 2 blocks. But anything beyond that, and the performance goes down catastrophically: add 3 or 4 blocks, change the prediction task...
There was a comparison study done by Tenenbaum's lab about these two approaches: [A Comparative Evaluation of Approximate Probabilistic Simulation and Deep Neural Networks as Accounts of Human Physical Scene Understanding](https://jiajunwu.com/papers/blocks_cogsci.pdf).
Quoting the discussion section:
>
> The performance of CNNs decreases as there are fewer training data.
> Although AlexNet (not pretrained) performs better with 200,000
> training images, it also suffers more from the lack of data, while
> pretrained AlexNet is able to learn better from a small amount of
> training images. For our task, both models require around 1,000 images
> for their performance to be comparable to the IPE model and humans.
>
>
>
>
> CNNs also have limited generalization ability across even small scene
> variations, such as changing the number of blocks. In contrast, IPE
> models naturally generalize and capture the ways that human judgment
> accuracy decreases with the number of blocks in a stack.
>
>
>
>
> Taken together, these results point to something fundamental about
> human cognition that neural networks (or at least CNNs) are not
> currently capturing: the existence of a mental model of the world’s
> causal processes. Causal mental models can be simulated to predict
> what will happen in qualitatively novel situations, and they do not
> require vast and diverse training data to generalize broadly, but they
> are inherently subject to certain kinds of errors (e.g., propagation
> of uncertainty due to state and dynamics noise) just in virtue of
> operating by simulation.
>
>
>
Back to the point I want to make: while neural networks are powerful models, they seem to lack the ability to represent causal, compositional and complex structure. And they make up for that by requiring lots of training data.
And back to your question: I would venture that the broad inductive bias and the fact that neural networks do not model causality/compositionality is why they need so much training data. Regularization is not a great fix because of the way they generalize. A better fix would be to change their bias, as is currently being tried by Hinton with [capsules](https://arxiv.org/abs/1710.09829) for modelling whole/part geometry, or [interaction networks](https://arxiv.org/abs/1612.00222) for modelling relations. | Regularization is a method for including prior information into a model. This will seem straightforward from the Bayesian perspective but is easy to see outside from the perspective as well. For example, the $L\_2$ penalty + standarization of covariates in Ridge Regression is essentially using the prior information that we don't believe that estimation should be entirely dominated by a small number of predictors. Similarly, the $L\_1$ penalty can be seen as "betting on sparseness of the solution" (side note: this *doesn't* make sense from the traditional Bayesian perspective but that's another story...).
A key point here is that regularization isn't always helpful. Rather, regularizing *toward what should probably be true* is very helpful, but regularizing in the wrong direction is clearly bad.
Now, when it comes to deep neural nets, the interpretability of this models makes regularization a little more difficult. For example, if we're trying to identify cats, in advance we know that "pointy ears" is an important feature. If we were using some like logistic regression with an $L\_2$ penalty and we had an indicator variable "pointy ears" in our dataset, we could just reduce the penalty on the pointy ears variable (or better yet, penalize *towards* a positive value rather than 0) and then our model would need less data for accurate predictions.
But now suppose our data is images of cats fed into a deep neural networks. If "pointy ears" is, in fact, very helpful for identifying cats, maybe we would like to reduce the penalty to give this more predictive power. But we have no idea *where* in the network this will be represented! We can still introduce penalties so that some small part of the system doesn't dominate the whole network, but outside of that, it's hard to introduce regularization in a meaningful way.
In summary, it's extremely difficult to incorporate prior information into a system we don't understand. |
345,737 | An issue I've seen frequently brought up in the context of Neural Networks in general, and Deep Neural Networks in particular, is that they're "data hungry" - that is they don't perform well unless we have a large data set with which to train the network.
My understanding is that this is due to the fact that NNets, especially Deep NNets, have a large number of degrees of freedom. So as a model, a NNet has a very large number of parameters, and if the number of parameters of the model is large relative to the number of training data points, there is an increased tendency to over fit.
But why isn't this issue solved by regularization? As far as I know NNets can use L1 and L2 regularization and also have their own regularization methods like dropout which can reduce the number of parameters in the network.
Can we choose our regularizations methods such that they enforce parsimony and limit the size of the network?
---
To clarify my thinking: Say we are using a large Deep NNet to try to model our data, but the data set is small and could actually be modeled by a linear model. Then why don't the network weights converge in such a way that one neuron simulates the linear regression and all the others converge to zeros? Why doesn't regularization help with this? | 2018/05/11 | [
"https://stats.stackexchange.com/questions/345737",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/89649/"
] | The simple way to explain it is that regularization helps to not fit to the noise, it doesn't do much in terms of determining the shape of the signal. If you think of deep learning as a giant glorious function approximator, then you realize that it needs a lot of data to define the shape of the complex signal.
If there was no noise then increasing complexity of NN would produce a better approximation. There would not be any penalty to the size of the NN, bigger would have been better in every case. Consider a Taylor approximation, more terms is always better for non-polynomial function (ignoring numerical precision issues).
This breaks down in presence of a noise, because you start fitting to the noise. So, here comes regularization to help: it *may* reduce fitting to the noise, thus allowing us to build **bigger** NN to fit nonlinear problems.
The following discussion is not essential to my answer, but I added in part to answer some comments and motivate the main body of the answer above. Basically, the rest of my answer is like french fires that come with a burger meal, you can skip it.
(Ir)relevant Case: Polynomial regression
========================================
Let's look at a toy example of a polynomial regression. It is also a pretty good approximator for many functions. We'll look at the $\sin(x)$ function in $x\in(-3,3)$ region. As you can see from its Taylor series below, 7th order expansion is already a pretty good fit, so we can expect that a polynomial of 7+ order should be a very good fit too:
[](https://i.stack.imgur.com/snfCp.png)
Next, we're going to fit polynomials with progressively higher order to a small very noisy data set with 7 observations:
[](https://i.stack.imgur.com/aL9XS.png)
We can observe what we've been told about polynomials by many people in-the-know: they're unstable, and start to oscillate wildly with increase in the order of polynomials.
However, the problem is not the polynomials themselves. The problem is the noise. When we fit polynomials to noisy data, part of the fit is to the noise, not to the signal. Here's the same exact polynomials fit to the same data set but with noise completely removed. The fits are great!
Notice a visually perfect fit for order 6. This shouldn't be surprising since 7 observations is all we need to uniquely identify order 6 polynomial, and we saw from Taylor approximation plot above that order 6 is already a very good approximation to $\sin(x)$ in our data range.
[](https://i.stack.imgur.com/tYCfk.png)
Also notice that higher order polynomials do not fit as well as order 6, because there is not enough observations to define them. So, let's look at what happens with 100 observations. On a chart below you see how a larger data set allowed us to fit higher order polynomials, thus accomplishing a better fit!
[](https://i.stack.imgur.com/zS65r.png)
Great, but the problem is that we usually deal with noisy data. Look at what happens if you fit the same to 100 observations of very noisy data, see the chart below. We're back to square one: higher order polynomials produce horrible oscillating fits. So, increasing data set didn't help that much in increasing the complexity of the model to better explain the data. This is, again, because complex model is fitting better not only to the shape of the signal, but to the shape of the noise too.
[](https://i.stack.imgur.com/3AZoj.png)
Finally, let's try some lame regularization on this problem. The chart below shows regularization (with different penalties) applied to order 9 polynomial regression. Compare this to order (power) 9 polynomial fit above: at an appropriate level of regularization it is possible to fit higher order polynomials to noisy data.
[](https://i.stack.imgur.com/WHvJI.png)
Just in case it wasn't clear: I'm not suggesting to use polynomial regression this way. Polynomials are good for local fits, so a piece-wise polynomial can be a good choice. To fit the entire domain with them is often a bad idea, because they are sensitive to noise, indeed, as it should be evident from plots above. Whether the noise is numerical or from some other source is not that important in this context. the noise is noise, and polynomials will react to it passionately. | >
> To clarify my thinking: Say we are using a large Deep NNet to try to model our data, but the data set is small and could actually be modeled by a linear model. Then why don't the network weights converge in such a way that one neuron simulates the linear regression and all the others converge to zeros? Why doesn't regularization help with this?
>
>
>
Neural nets can be trained like this. If proper L1 regularization used then much of the weights can be zeroed and this will make neural nets behave like concatenation of 1 or so linear regression neurons and many other zero nerons. So yes - L1/L2 regularizations or like that can be used to restrict the size or representational power of the neural network.
Actually the size of the model itself is a kind of regularization - if you make model large, it means that you injects a prior knowledge about the problem, that is, the problems is highly complex so it requires model that have high representational power. If you make model small, then it means you injects knowledge that the problem is simple so model don't need much capacity.
And this means L2 regularization will not make networks "sparse" as you described, because L2 regularization injects prior knowledge that contribution of each neuron (weight) should be small but non-zero. So network would use each of the neurons rather than use only small set of neurons. |
345,737 | An issue I've seen frequently brought up in the context of Neural Networks in general, and Deep Neural Networks in particular, is that they're "data hungry" - that is they don't perform well unless we have a large data set with which to train the network.
My understanding is that this is due to the fact that NNets, especially Deep NNets, have a large number of degrees of freedom. So as a model, a NNet has a very large number of parameters, and if the number of parameters of the model is large relative to the number of training data points, there is an increased tendency to over fit.
But why isn't this issue solved by regularization? As far as I know NNets can use L1 and L2 regularization and also have their own regularization methods like dropout which can reduce the number of parameters in the network.
Can we choose our regularizations methods such that they enforce parsimony and limit the size of the network?
---
To clarify my thinking: Say we are using a large Deep NNet to try to model our data, but the data set is small and could actually be modeled by a linear model. Then why don't the network weights converge in such a way that one neuron simulates the linear regression and all the others converge to zeros? Why doesn't regularization help with this? | 2018/05/11 | [
"https://stats.stackexchange.com/questions/345737",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/89649/"
] | At this point in time, its not well-understood when and why certain regularization methods succeed and fail. In fact, its not understood at all why deep learning works in the first place.
Considering the fact that a sufficiently deep neural net can memorize most well-behaved training data perfectly, there are considerably more wrong solutions than there are right for any particular deep net. Regularization, broadly speaking, is an attempt to limit the expressivity of models for these "wrong" solutions - where "wrong" is defined by heuristics we think are important for a particular **domain**. But often it is difficult to define the heuristic such that you don't lose the "right" expressivity with it. A great example of this is L2 penalties.
Very few methods that would be considered a form of regularization are generally applicable to all application areas of ML. Vision, NLP, and structured prediction problems all have their own cookbook of regularization techniques that have been demonstrated to be effective experimentally for those particular domains. But even within those domains, these techniques are only effective under certain circumstances. For example, batch normalization on deep residual networks appears to make dropout redundant, despite the fact that both have been shown to independently improve generalization.
On a separate note, I think the term regularization is so broad that it makes it difficult to understand anything about it. Considering the fact that convolutions restrict the parameter space exponentially with respect to pixels, you could consider the convolutional neural network a form of regularization on the vanilla neural net. | I would say that at a high level, the inductive bias of DNNs (deep neural networks) is powerful but slightly too loose or not opinionated enough. By that I mean that DNNs capture a lot of surface statistics about what is going on, but fail to get to the deeper causal/compositional high level structure. (You could view convolutions as a poor's man inductive bias specification).
In addition, it is believed in the machine learning community that the best way to generalize (making good inferences/predictions with little data) is to find the shortest program that gave rise to the data. But program induction/synthesis is hard and we have no good way of doing it efficiently. So instead we rely on a close approximation which is circuit search, and we know how do that with backpropagation. [Here](https://www.youtube.com/watch?v=9EN_HoEk3KY&t=1m11s), Ilya Sutskever gives an overview of that idea.
---
To illustrate the difference in generalization power of models represented as actual programs vs deep learning models, I'll show the one in this paper: [Simulation as an engine of physical scene understanding](https://pdfs.semanticscholar.org/26f7/d738df74539b8de1e158e1844e5c5cece47f.pdf).
[](https://i.stack.imgur.com/e2cXb.png)
>
> (A) The IPE [intuitive physics engine] model takes inputs (e.g., perception, language, memory, imagery, etc.) that instantiate a distribution over scenes (1), then simulates the effects of physics on the distribution (2), and then aggregates the results for output to other sensorimotor and cognitive faculties (3)
>
>
>
[](https://i.stack.imgur.com/0ExAH.png)
>
> (B) Exp. 1 (Will it fall?) tower stimuli. The tower with the red border is actually delicately balanced, and the other two are the same height, but the blue-bordered one is judged much less likely to fall by the model and people.
>
>
> (C) Probabilistic IPE model (x axis) vs. human judgment averages (y axis) in Exp. 1. See Fig. S3 for correlations for other values of σ and ϕ. Each point represents one tower (with SEM), and the three colored circles correspond to the three towers in B.
>
>
> (D) Ground truth (nonprobabilistic) vs. human judgments (Exp. 1). Because it does not represent uncertainty, it cannot capture people’s judgments for a number of our stimuli, such as the red-bordered tower in B. (Note that these cases may be rare in natural scenes, where configurations tend to be more clearly stable or unstable and the IPE would be expected to correlate better with ground truth than it does on our stimuli.)
>
>
>
My point here is that the fit in C is really good, because the model captures the right biases about how humans make physical judgments. This is in big part because it models actual physics (remember that it **is** a actual physics engine) and can deal with uncertainty.
Now the obvious question is: can you do that with deep learning? This is what Lerer et al did in this work: [Learning Physical Intuition of Block Towers by Example](https://arxiv.org/abs/1603.01312)
Their model:
[](https://i.stack.imgur.com/0fr1v.png)
Their model is actually pretty good on the task at hand (predicting the number of falling blocks, and even their falling direction)
[](https://i.stack.imgur.com/coz1f.png)
But it suffers two major drawbacks:
* It needs a huge amount of data to train properly
* In generalizes only in shallow ways: you can transfer to more realistic looking images, add or remove 1 or 2 blocks. But anything beyond that, and the performance goes down catastrophically: add 3 or 4 blocks, change the prediction task...
There was a comparison study done by Tenenbaum's lab about these two approaches: [A Comparative Evaluation of Approximate Probabilistic Simulation and Deep Neural Networks as Accounts of Human Physical Scene Understanding](https://jiajunwu.com/papers/blocks_cogsci.pdf).
Quoting the discussion section:
>
> The performance of CNNs decreases as there are fewer training data.
> Although AlexNet (not pretrained) performs better with 200,000
> training images, it also suffers more from the lack of data, while
> pretrained AlexNet is able to learn better from a small amount of
> training images. For our task, both models require around 1,000 images
> for their performance to be comparable to the IPE model and humans.
>
>
>
>
> CNNs also have limited generalization ability across even small scene
> variations, such as changing the number of blocks. In contrast, IPE
> models naturally generalize and capture the ways that human judgment
> accuracy decreases with the number of blocks in a stack.
>
>
>
>
> Taken together, these results point to something fundamental about
> human cognition that neural networks (or at least CNNs) are not
> currently capturing: the existence of a mental model of the world’s
> causal processes. Causal mental models can be simulated to predict
> what will happen in qualitatively novel situations, and they do not
> require vast and diverse training data to generalize broadly, but they
> are inherently subject to certain kinds of errors (e.g., propagation
> of uncertainty due to state and dynamics noise) just in virtue of
> operating by simulation.
>
>
>
Back to the point I want to make: while neural networks are powerful models, they seem to lack the ability to represent causal, compositional and complex structure. And they make up for that by requiring lots of training data.
And back to your question: I would venture that the broad inductive bias and the fact that neural networks do not model causality/compositionality is why they need so much training data. Regularization is not a great fix because of the way they generalize. A better fix would be to change their bias, as is currently being tried by Hinton with [capsules](https://arxiv.org/abs/1710.09829) for modelling whole/part geometry, or [interaction networks](https://arxiv.org/abs/1612.00222) for modelling relations. |
345,737 | An issue I've seen frequently brought up in the context of Neural Networks in general, and Deep Neural Networks in particular, is that they're "data hungry" - that is they don't perform well unless we have a large data set with which to train the network.
My understanding is that this is due to the fact that NNets, especially Deep NNets, have a large number of degrees of freedom. So as a model, a NNet has a very large number of parameters, and if the number of parameters of the model is large relative to the number of training data points, there is an increased tendency to over fit.
But why isn't this issue solved by regularization? As far as I know NNets can use L1 and L2 regularization and also have their own regularization methods like dropout which can reduce the number of parameters in the network.
Can we choose our regularizations methods such that they enforce parsimony and limit the size of the network?
---
To clarify my thinking: Say we are using a large Deep NNet to try to model our data, but the data set is small and could actually be modeled by a linear model. Then why don't the network weights converge in such a way that one neuron simulates the linear regression and all the others converge to zeros? Why doesn't regularization help with this? | 2018/05/11 | [
"https://stats.stackexchange.com/questions/345737",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/89649/"
] | One class of theorems that show why this problem is fundamental are the [No Free Lunch Theorems](https://en.wikipedia.org/wiki/No_free_lunch_theorem). For every problem with limited samples where a certain regularization helps, there is another problem where that same regularization will make things worse. As Austin points out, we generally find that L1/L2 regularization are helpful for many real-world problems, but this is only an observation and, because of the NFL theorems, there can be no general guarantees. | Regularization is a method for including prior information into a model. This will seem straightforward from the Bayesian perspective but is easy to see outside from the perspective as well. For example, the $L\_2$ penalty + standarization of covariates in Ridge Regression is essentially using the prior information that we don't believe that estimation should be entirely dominated by a small number of predictors. Similarly, the $L\_1$ penalty can be seen as "betting on sparseness of the solution" (side note: this *doesn't* make sense from the traditional Bayesian perspective but that's another story...).
A key point here is that regularization isn't always helpful. Rather, regularizing *toward what should probably be true* is very helpful, but regularizing in the wrong direction is clearly bad.
Now, when it comes to deep neural nets, the interpretability of this models makes regularization a little more difficult. For example, if we're trying to identify cats, in advance we know that "pointy ears" is an important feature. If we were using some like logistic regression with an $L\_2$ penalty and we had an indicator variable "pointy ears" in our dataset, we could just reduce the penalty on the pointy ears variable (or better yet, penalize *towards* a positive value rather than 0) and then our model would need less data for accurate predictions.
But now suppose our data is images of cats fed into a deep neural networks. If "pointy ears" is, in fact, very helpful for identifying cats, maybe we would like to reduce the penalty to give this more predictive power. But we have no idea *where* in the network this will be represented! We can still introduce penalties so that some small part of the system doesn't dominate the whole network, but outside of that, it's hard to introduce regularization in a meaningful way.
In summary, it's extremely difficult to incorporate prior information into a system we don't understand. |
345,737 | An issue I've seen frequently brought up in the context of Neural Networks in general, and Deep Neural Networks in particular, is that they're "data hungry" - that is they don't perform well unless we have a large data set with which to train the network.
My understanding is that this is due to the fact that NNets, especially Deep NNets, have a large number of degrees of freedom. So as a model, a NNet has a very large number of parameters, and if the number of parameters of the model is large relative to the number of training data points, there is an increased tendency to over fit.
But why isn't this issue solved by regularization? As far as I know NNets can use L1 and L2 regularization and also have their own regularization methods like dropout which can reduce the number of parameters in the network.
Can we choose our regularizations methods such that they enforce parsimony and limit the size of the network?
---
To clarify my thinking: Say we are using a large Deep NNet to try to model our data, but the data set is small and could actually be modeled by a linear model. Then why don't the network weights converge in such a way that one neuron simulates the linear regression and all the others converge to zeros? Why doesn't regularization help with this? | 2018/05/11 | [
"https://stats.stackexchange.com/questions/345737",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/89649/"
] | At this point in time, its not well-understood when and why certain regularization methods succeed and fail. In fact, its not understood at all why deep learning works in the first place.
Considering the fact that a sufficiently deep neural net can memorize most well-behaved training data perfectly, there are considerably more wrong solutions than there are right for any particular deep net. Regularization, broadly speaking, is an attempt to limit the expressivity of models for these "wrong" solutions - where "wrong" is defined by heuristics we think are important for a particular **domain**. But often it is difficult to define the heuristic such that you don't lose the "right" expressivity with it. A great example of this is L2 penalties.
Very few methods that would be considered a form of regularization are generally applicable to all application areas of ML. Vision, NLP, and structured prediction problems all have their own cookbook of regularization techniques that have been demonstrated to be effective experimentally for those particular domains. But even within those domains, these techniques are only effective under certain circumstances. For example, batch normalization on deep residual networks appears to make dropout redundant, despite the fact that both have been shown to independently improve generalization.
On a separate note, I think the term regularization is so broad that it makes it difficult to understand anything about it. Considering the fact that convolutions restrict the parameter space exponentially with respect to pixels, you could consider the convolutional neural network a form of regularization on the vanilla neural net. | Regularization is a method for including prior information into a model. This will seem straightforward from the Bayesian perspective but is easy to see outside from the perspective as well. For example, the $L\_2$ penalty + standarization of covariates in Ridge Regression is essentially using the prior information that we don't believe that estimation should be entirely dominated by a small number of predictors. Similarly, the $L\_1$ penalty can be seen as "betting on sparseness of the solution" (side note: this *doesn't* make sense from the traditional Bayesian perspective but that's another story...).
A key point here is that regularization isn't always helpful. Rather, regularizing *toward what should probably be true* is very helpful, but regularizing in the wrong direction is clearly bad.
Now, when it comes to deep neural nets, the interpretability of this models makes regularization a little more difficult. For example, if we're trying to identify cats, in advance we know that "pointy ears" is an important feature. If we were using some like logistic regression with an $L\_2$ penalty and we had an indicator variable "pointy ears" in our dataset, we could just reduce the penalty on the pointy ears variable (or better yet, penalize *towards* a positive value rather than 0) and then our model would need less data for accurate predictions.
But now suppose our data is images of cats fed into a deep neural networks. If "pointy ears" is, in fact, very helpful for identifying cats, maybe we would like to reduce the penalty to give this more predictive power. But we have no idea *where* in the network this will be represented! We can still introduce penalties so that some small part of the system doesn't dominate the whole network, but outside of that, it's hard to introduce regularization in a meaningful way.
In summary, it's extremely difficult to incorporate prior information into a system we don't understand. |
345,737 | An issue I've seen frequently brought up in the context of Neural Networks in general, and Deep Neural Networks in particular, is that they're "data hungry" - that is they don't perform well unless we have a large data set with which to train the network.
My understanding is that this is due to the fact that NNets, especially Deep NNets, have a large number of degrees of freedom. So as a model, a NNet has a very large number of parameters, and if the number of parameters of the model is large relative to the number of training data points, there is an increased tendency to over fit.
But why isn't this issue solved by regularization? As far as I know NNets can use L1 and L2 regularization and also have their own regularization methods like dropout which can reduce the number of parameters in the network.
Can we choose our regularizations methods such that they enforce parsimony and limit the size of the network?
---
To clarify my thinking: Say we are using a large Deep NNet to try to model our data, but the data set is small and could actually be modeled by a linear model. Then why don't the network weights converge in such a way that one neuron simulates the linear regression and all the others converge to zeros? Why doesn't regularization help with this? | 2018/05/11 | [
"https://stats.stackexchange.com/questions/345737",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/89649/"
] | The simple way to explain it is that regularization helps to not fit to the noise, it doesn't do much in terms of determining the shape of the signal. If you think of deep learning as a giant glorious function approximator, then you realize that it needs a lot of data to define the shape of the complex signal.
If there was no noise then increasing complexity of NN would produce a better approximation. There would not be any penalty to the size of the NN, bigger would have been better in every case. Consider a Taylor approximation, more terms is always better for non-polynomial function (ignoring numerical precision issues).
This breaks down in presence of a noise, because you start fitting to the noise. So, here comes regularization to help: it *may* reduce fitting to the noise, thus allowing us to build **bigger** NN to fit nonlinear problems.
The following discussion is not essential to my answer, but I added in part to answer some comments and motivate the main body of the answer above. Basically, the rest of my answer is like french fires that come with a burger meal, you can skip it.
(Ir)relevant Case: Polynomial regression
========================================
Let's look at a toy example of a polynomial regression. It is also a pretty good approximator for many functions. We'll look at the $\sin(x)$ function in $x\in(-3,3)$ region. As you can see from its Taylor series below, 7th order expansion is already a pretty good fit, so we can expect that a polynomial of 7+ order should be a very good fit too:
[](https://i.stack.imgur.com/snfCp.png)
Next, we're going to fit polynomials with progressively higher order to a small very noisy data set with 7 observations:
[](https://i.stack.imgur.com/aL9XS.png)
We can observe what we've been told about polynomials by many people in-the-know: they're unstable, and start to oscillate wildly with increase in the order of polynomials.
However, the problem is not the polynomials themselves. The problem is the noise. When we fit polynomials to noisy data, part of the fit is to the noise, not to the signal. Here's the same exact polynomials fit to the same data set but with noise completely removed. The fits are great!
Notice a visually perfect fit for order 6. This shouldn't be surprising since 7 observations is all we need to uniquely identify order 6 polynomial, and we saw from Taylor approximation plot above that order 6 is already a very good approximation to $\sin(x)$ in our data range.
[](https://i.stack.imgur.com/tYCfk.png)
Also notice that higher order polynomials do not fit as well as order 6, because there is not enough observations to define them. So, let's look at what happens with 100 observations. On a chart below you see how a larger data set allowed us to fit higher order polynomials, thus accomplishing a better fit!
[](https://i.stack.imgur.com/zS65r.png)
Great, but the problem is that we usually deal with noisy data. Look at what happens if you fit the same to 100 observations of very noisy data, see the chart below. We're back to square one: higher order polynomials produce horrible oscillating fits. So, increasing data set didn't help that much in increasing the complexity of the model to better explain the data. This is, again, because complex model is fitting better not only to the shape of the signal, but to the shape of the noise too.
[](https://i.stack.imgur.com/3AZoj.png)
Finally, let's try some lame regularization on this problem. The chart below shows regularization (with different penalties) applied to order 9 polynomial regression. Compare this to order (power) 9 polynomial fit above: at an appropriate level of regularization it is possible to fit higher order polynomials to noisy data.
[](https://i.stack.imgur.com/WHvJI.png)
Just in case it wasn't clear: I'm not suggesting to use polynomial regression this way. Polynomials are good for local fits, so a piece-wise polynomial can be a good choice. To fit the entire domain with them is often a bad idea, because they are sensitive to noise, indeed, as it should be evident from plots above. Whether the noise is numerical or from some other source is not that important in this context. the noise is noise, and polynomials will react to it passionately. | At this point in time, its not well-understood when and why certain regularization methods succeed and fail. In fact, its not understood at all why deep learning works in the first place.
Considering the fact that a sufficiently deep neural net can memorize most well-behaved training data perfectly, there are considerably more wrong solutions than there are right for any particular deep net. Regularization, broadly speaking, is an attempt to limit the expressivity of models for these "wrong" solutions - where "wrong" is defined by heuristics we think are important for a particular **domain**. But often it is difficult to define the heuristic such that you don't lose the "right" expressivity with it. A great example of this is L2 penalties.
Very few methods that would be considered a form of regularization are generally applicable to all application areas of ML. Vision, NLP, and structured prediction problems all have their own cookbook of regularization techniques that have been demonstrated to be effective experimentally for those particular domains. But even within those domains, these techniques are only effective under certain circumstances. For example, batch normalization on deep residual networks appears to make dropout redundant, despite the fact that both have been shown to independently improve generalization.
On a separate note, I think the term regularization is so broad that it makes it difficult to understand anything about it. Considering the fact that convolutions restrict the parameter space exponentially with respect to pixels, you could consider the convolutional neural network a form of regularization on the vanilla neural net. |
345,737 | An issue I've seen frequently brought up in the context of Neural Networks in general, and Deep Neural Networks in particular, is that they're "data hungry" - that is they don't perform well unless we have a large data set with which to train the network.
My understanding is that this is due to the fact that NNets, especially Deep NNets, have a large number of degrees of freedom. So as a model, a NNet has a very large number of parameters, and if the number of parameters of the model is large relative to the number of training data points, there is an increased tendency to over fit.
But why isn't this issue solved by regularization? As far as I know NNets can use L1 and L2 regularization and also have their own regularization methods like dropout which can reduce the number of parameters in the network.
Can we choose our regularizations methods such that they enforce parsimony and limit the size of the network?
---
To clarify my thinking: Say we are using a large Deep NNet to try to model our data, but the data set is small and could actually be modeled by a linear model. Then why don't the network weights converge in such a way that one neuron simulates the linear regression and all the others converge to zeros? Why doesn't regularization help with this? | 2018/05/11 | [
"https://stats.stackexchange.com/questions/345737",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/89649/"
] | The simple way to explain it is that regularization helps to not fit to the noise, it doesn't do much in terms of determining the shape of the signal. If you think of deep learning as a giant glorious function approximator, then you realize that it needs a lot of data to define the shape of the complex signal.
If there was no noise then increasing complexity of NN would produce a better approximation. There would not be any penalty to the size of the NN, bigger would have been better in every case. Consider a Taylor approximation, more terms is always better for non-polynomial function (ignoring numerical precision issues).
This breaks down in presence of a noise, because you start fitting to the noise. So, here comes regularization to help: it *may* reduce fitting to the noise, thus allowing us to build **bigger** NN to fit nonlinear problems.
The following discussion is not essential to my answer, but I added in part to answer some comments and motivate the main body of the answer above. Basically, the rest of my answer is like french fires that come with a burger meal, you can skip it.
(Ir)relevant Case: Polynomial regression
========================================
Let's look at a toy example of a polynomial regression. It is also a pretty good approximator for many functions. We'll look at the $\sin(x)$ function in $x\in(-3,3)$ region. As you can see from its Taylor series below, 7th order expansion is already a pretty good fit, so we can expect that a polynomial of 7+ order should be a very good fit too:
[](https://i.stack.imgur.com/snfCp.png)
Next, we're going to fit polynomials with progressively higher order to a small very noisy data set with 7 observations:
[](https://i.stack.imgur.com/aL9XS.png)
We can observe what we've been told about polynomials by many people in-the-know: they're unstable, and start to oscillate wildly with increase in the order of polynomials.
However, the problem is not the polynomials themselves. The problem is the noise. When we fit polynomials to noisy data, part of the fit is to the noise, not to the signal. Here's the same exact polynomials fit to the same data set but with noise completely removed. The fits are great!
Notice a visually perfect fit for order 6. This shouldn't be surprising since 7 observations is all we need to uniquely identify order 6 polynomial, and we saw from Taylor approximation plot above that order 6 is already a very good approximation to $\sin(x)$ in our data range.
[](https://i.stack.imgur.com/tYCfk.png)
Also notice that higher order polynomials do not fit as well as order 6, because there is not enough observations to define them. So, let's look at what happens with 100 observations. On a chart below you see how a larger data set allowed us to fit higher order polynomials, thus accomplishing a better fit!
[](https://i.stack.imgur.com/zS65r.png)
Great, but the problem is that we usually deal with noisy data. Look at what happens if you fit the same to 100 observations of very noisy data, see the chart below. We're back to square one: higher order polynomials produce horrible oscillating fits. So, increasing data set didn't help that much in increasing the complexity of the model to better explain the data. This is, again, because complex model is fitting better not only to the shape of the signal, but to the shape of the noise too.
[](https://i.stack.imgur.com/3AZoj.png)
Finally, let's try some lame regularization on this problem. The chart below shows regularization (with different penalties) applied to order 9 polynomial regression. Compare this to order (power) 9 polynomial fit above: at an appropriate level of regularization it is possible to fit higher order polynomials to noisy data.
[](https://i.stack.imgur.com/WHvJI.png)
Just in case it wasn't clear: I'm not suggesting to use polynomial regression this way. Polynomials are good for local fits, so a piece-wise polynomial can be a good choice. To fit the entire domain with them is often a bad idea, because they are sensitive to noise, indeed, as it should be evident from plots above. Whether the noise is numerical or from some other source is not that important in this context. the noise is noise, and polynomials will react to it passionately. | One class of theorems that show why this problem is fundamental are the [No Free Lunch Theorems](https://en.wikipedia.org/wiki/No_free_lunch_theorem). For every problem with limited samples where a certain regularization helps, there is another problem where that same regularization will make things worse. As Austin points out, we generally find that L1/L2 regularization are helpful for many real-world problems, but this is only an observation and, because of the NFL theorems, there can be no general guarantees. |
345,737 | An issue I've seen frequently brought up in the context of Neural Networks in general, and Deep Neural Networks in particular, is that they're "data hungry" - that is they don't perform well unless we have a large data set with which to train the network.
My understanding is that this is due to the fact that NNets, especially Deep NNets, have a large number of degrees of freedom. So as a model, a NNet has a very large number of parameters, and if the number of parameters of the model is large relative to the number of training data points, there is an increased tendency to over fit.
But why isn't this issue solved by regularization? As far as I know NNets can use L1 and L2 regularization and also have their own regularization methods like dropout which can reduce the number of parameters in the network.
Can we choose our regularizations methods such that they enforce parsimony and limit the size of the network?
---
To clarify my thinking: Say we are using a large Deep NNet to try to model our data, but the data set is small and could actually be modeled by a linear model. Then why don't the network weights converge in such a way that one neuron simulates the linear regression and all the others converge to zeros? Why doesn't regularization help with this? | 2018/05/11 | [
"https://stats.stackexchange.com/questions/345737",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/89649/"
] | >
> To clarify my thinking: Say we are using a large Deep NNet to try to model our data, but the data set is small and could actually be modeled by a linear model. Then why don't the network weights converge in such a way that one neuron simulates the linear regression and all the others converge to zeros? Why doesn't regularization help with this?
>
>
>
Neural nets can be trained like this. If proper L1 regularization used then much of the weights can be zeroed and this will make neural nets behave like concatenation of 1 or so linear regression neurons and many other zero nerons. So yes - L1/L2 regularizations or like that can be used to restrict the size or representational power of the neural network.
Actually the size of the model itself is a kind of regularization - if you make model large, it means that you injects a prior knowledge about the problem, that is, the problems is highly complex so it requires model that have high representational power. If you make model small, then it means you injects knowledge that the problem is simple so model don't need much capacity.
And this means L2 regularization will not make networks "sparse" as you described, because L2 regularization injects prior knowledge that contribution of each neuron (weight) should be small but non-zero. So network would use each of the neurons rather than use only small set of neurons. | Regularization is a method for including prior information into a model. This will seem straightforward from the Bayesian perspective but is easy to see outside from the perspective as well. For example, the $L\_2$ penalty + standarization of covariates in Ridge Regression is essentially using the prior information that we don't believe that estimation should be entirely dominated by a small number of predictors. Similarly, the $L\_1$ penalty can be seen as "betting on sparseness of the solution" (side note: this *doesn't* make sense from the traditional Bayesian perspective but that's another story...).
A key point here is that regularization isn't always helpful. Rather, regularizing *toward what should probably be true* is very helpful, but regularizing in the wrong direction is clearly bad.
Now, when it comes to deep neural nets, the interpretability of this models makes regularization a little more difficult. For example, if we're trying to identify cats, in advance we know that "pointy ears" is an important feature. If we were using some like logistic regression with an $L\_2$ penalty and we had an indicator variable "pointy ears" in our dataset, we could just reduce the penalty on the pointy ears variable (or better yet, penalize *towards* a positive value rather than 0) and then our model would need less data for accurate predictions.
But now suppose our data is images of cats fed into a deep neural networks. If "pointy ears" is, in fact, very helpful for identifying cats, maybe we would like to reduce the penalty to give this more predictive power. But we have no idea *where* in the network this will be represented! We can still introduce penalties so that some small part of the system doesn't dominate the whole network, but outside of that, it's hard to introduce regularization in a meaningful way.
In summary, it's extremely difficult to incorporate prior information into a system we don't understand. |
345,737 | An issue I've seen frequently brought up in the context of Neural Networks in general, and Deep Neural Networks in particular, is that they're "data hungry" - that is they don't perform well unless we have a large data set with which to train the network.
My understanding is that this is due to the fact that NNets, especially Deep NNets, have a large number of degrees of freedom. So as a model, a NNet has a very large number of parameters, and if the number of parameters of the model is large relative to the number of training data points, there is an increased tendency to over fit.
But why isn't this issue solved by regularization? As far as I know NNets can use L1 and L2 regularization and also have their own regularization methods like dropout which can reduce the number of parameters in the network.
Can we choose our regularizations methods such that they enforce parsimony and limit the size of the network?
---
To clarify my thinking: Say we are using a large Deep NNet to try to model our data, but the data set is small and could actually be modeled by a linear model. Then why don't the network weights converge in such a way that one neuron simulates the linear regression and all the others converge to zeros? Why doesn't regularization help with this? | 2018/05/11 | [
"https://stats.stackexchange.com/questions/345737",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/89649/"
] | At this point in time, its not well-understood when and why certain regularization methods succeed and fail. In fact, its not understood at all why deep learning works in the first place.
Considering the fact that a sufficiently deep neural net can memorize most well-behaved training data perfectly, there are considerably more wrong solutions than there are right for any particular deep net. Regularization, broadly speaking, is an attempt to limit the expressivity of models for these "wrong" solutions - where "wrong" is defined by heuristics we think are important for a particular **domain**. But often it is difficult to define the heuristic such that you don't lose the "right" expressivity with it. A great example of this is L2 penalties.
Very few methods that would be considered a form of regularization are generally applicable to all application areas of ML. Vision, NLP, and structured prediction problems all have their own cookbook of regularization techniques that have been demonstrated to be effective experimentally for those particular domains. But even within those domains, these techniques are only effective under certain circumstances. For example, batch normalization on deep residual networks appears to make dropout redundant, despite the fact that both have been shown to independently improve generalization.
On a separate note, I think the term regularization is so broad that it makes it difficult to understand anything about it. Considering the fact that convolutions restrict the parameter space exponentially with respect to pixels, you could consider the convolutional neural network a form of regularization on the vanilla neural net. | One class of theorems that show why this problem is fundamental are the [No Free Lunch Theorems](https://en.wikipedia.org/wiki/No_free_lunch_theorem). For every problem with limited samples where a certain regularization helps, there is another problem where that same regularization will make things worse. As Austin points out, we generally find that L1/L2 regularization are helpful for many real-world problems, but this is only an observation and, because of the NFL theorems, there can be no general guarantees. |
345,737 | An issue I've seen frequently brought up in the context of Neural Networks in general, and Deep Neural Networks in particular, is that they're "data hungry" - that is they don't perform well unless we have a large data set with which to train the network.
My understanding is that this is due to the fact that NNets, especially Deep NNets, have a large number of degrees of freedom. So as a model, a NNet has a very large number of parameters, and if the number of parameters of the model is large relative to the number of training data points, there is an increased tendency to over fit.
But why isn't this issue solved by regularization? As far as I know NNets can use L1 and L2 regularization and also have their own regularization methods like dropout which can reduce the number of parameters in the network.
Can we choose our regularizations methods such that they enforce parsimony and limit the size of the network?
---
To clarify my thinking: Say we are using a large Deep NNet to try to model our data, but the data set is small and could actually be modeled by a linear model. Then why don't the network weights converge in such a way that one neuron simulates the linear regression and all the others converge to zeros? Why doesn't regularization help with this? | 2018/05/11 | [
"https://stats.stackexchange.com/questions/345737",
"https://stats.stackexchange.com",
"https://stats.stackexchange.com/users/89649/"
] | At this point in time, its not well-understood when and why certain regularization methods succeed and fail. In fact, its not understood at all why deep learning works in the first place.
Considering the fact that a sufficiently deep neural net can memorize most well-behaved training data perfectly, there are considerably more wrong solutions than there are right for any particular deep net. Regularization, broadly speaking, is an attempt to limit the expressivity of models for these "wrong" solutions - where "wrong" is defined by heuristics we think are important for a particular **domain**. But often it is difficult to define the heuristic such that you don't lose the "right" expressivity with it. A great example of this is L2 penalties.
Very few methods that would be considered a form of regularization are generally applicable to all application areas of ML. Vision, NLP, and structured prediction problems all have their own cookbook of regularization techniques that have been demonstrated to be effective experimentally for those particular domains. But even within those domains, these techniques are only effective under certain circumstances. For example, batch normalization on deep residual networks appears to make dropout redundant, despite the fact that both have been shown to independently improve generalization.
On a separate note, I think the term regularization is so broad that it makes it difficult to understand anything about it. Considering the fact that convolutions restrict the parameter space exponentially with respect to pixels, you could consider the convolutional neural network a form of regularization on the vanilla neural net. | >
> To clarify my thinking: Say we are using a large Deep NNet to try to model our data, but the data set is small and could actually be modeled by a linear model. Then why don't the network weights converge in such a way that one neuron simulates the linear regression and all the others converge to zeros? Why doesn't regularization help with this?
>
>
>
Neural nets can be trained like this. If proper L1 regularization used then much of the weights can be zeroed and this will make neural nets behave like concatenation of 1 or so linear regression neurons and many other zero nerons. So yes - L1/L2 regularizations or like that can be used to restrict the size or representational power of the neural network.
Actually the size of the model itself is a kind of regularization - if you make model large, it means that you injects a prior knowledge about the problem, that is, the problems is highly complex so it requires model that have high representational power. If you make model small, then it means you injects knowledge that the problem is simple so model don't need much capacity.
And this means L2 regularization will not make networks "sparse" as you described, because L2 regularization injects prior knowledge that contribution of each neuron (weight) should be small but non-zero. So network would use each of the neurons rather than use only small set of neurons. |
26,414,312 | I have some ideas to solve this situation, but still wanted to ask someone with more experience.
I've created an Android App that makes requests to some URL. In this URL I would also like to have the landing page of my app. Howevere, I don't want people to enter to my folders where I process the requests (I have there some interface to test my app). When I protect this folder with a password via cPanel, the users are not avaible to connect with my php files and download the data. What is the best way to handle this? Should I have two URL (one for the landing page - one for the backend)? Should I not create any link to my backend files and not allow Google to crawl them? Should I add a password to this folder and insert the Username and Password in my client?
Thanks! | 2014/10/16 | [
"https://Stackoverflow.com/questions/26414312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3404681/"
] | either add .htaccess file [here is apache link how to configure it](https://httpd.apache.org/docs/2.2/howto/htaccess.html) or add empty index.html or index.php files in each folder. | If you add an .htaccess file with:
```
deny from all
```
It will give a 403 error to any visitors and therefore not display the folders!
(See this page: [.htaccess to restrict access to folder](https://stackoverflow.com/questions/4610524/htaccess-to-restrict-access-to-folder)) |
4,385 | Hi am working on salesforce touch. I am trying to Install the Mobile SDK for Android but while doing it in the
step 3. their is 'Open a command prompt in the directory where you installed the cloned repository, and run the install script from the command line: ./install.sh'
while doing this process i am getting error "There was an error getting the status of the git repository:"Make sure the 'git' executable is on your PATH variable"
can anybody help me to solve this issue. | 2012/11/14 | [
"https://salesforce.stackexchange.com/questions/4385",
"https://salesforce.stackexchange.com",
"https://salesforce.stackexchange.com/users/417/"
] | I know it's been awhile since you posted the question, but I ran into the exact problem you encountered today: I'm trying to install the Salesforce Mobile SDK kit for Android on Windows 7. The guide
([http://wiki.developerforce.com/page/Developing\_Hybrid\_Apps\_with\_the\_Salesforce\_Mobile\_SDK])[1](http://wiki.developerforce.com/page/Developing_Hybrid_Apps_with_the_Salesforce_Mobile_SDK)
says to:
>
> Clone the SalesforceMobileSDK-Android project from GitHub:
>
>
>
> ```
> git clone https://github.com/forcedotcom/SalesforceMobileSDK-Android.git
>
> ```
>
>
And you have to do this in `Powershell` (**not** `cmd`).
Then it says:
>
> Windows
> ------- Run the install script from the *Windows command line*:
>
>
>
> ```
> cd SalesforceMobileSDK-Android
> cscript install.vbs
>
> ```
>
>
So I go to `cmd`, fumble around for a bit finding my `GitHub\SalesforceMobileSDK-Android` directory. When I try to `cscript install.vbs`, it says:
>
> There was an error getting the status of the git repository: '' Make sure the
> 'git' executable is on your PATH variable.
>
>
>
So I go to change my `PATH` variable, but I can't find anything like `*--something--*\Git\bin` to point to. Then I realized, it's trying to use the `git` executable.
**The solution is** to do everything in `Powershell`. That is, in `Powershell`:
Go to your directory and
```
cscript install.vbs
```
and volia! | The question is long long time ago..But I'm posting this answer since I have faced the same issue and was able to resolve the issue.
After installing **GIT**, simply set the *PATH\** in your environment variables. This [link](http://blog.countableset.ch/2012/06/07/adding-git-to-windows-7-path/) will help you. Open new Command prompt and retry. |
7,519,901 | Can someone tell me how to remove the decimal points from the Axis labels? Instead of 10.0 I'd like to have only 10 showing. | 2011/09/22 | [
"https://Stackoverflow.com/questions/7519901",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/335427/"
] | ```
CPTXYAxis *x = axisSet.xAxis;
NSNumberFormatter *Xformatter = [[NSNumberFormatter alloc] init];
[Xformatter setGeneratesDecimalNumbers:NO];
[Xformatter setNumberStyle:NSNumberFormatterDecimalStyle];
x.labelFormatter = Xformatter;
[Xformatter release];
```
This will take care of the decimals on the x axis as well as add commas with NSNumberFormatterDecimalStyle. You will need to do the same for the y axis.
There are a ton of things you can do with NSNumberFormatter, including converting numbers into dollars using:
```
[Xformatter setNumberStyle:NSNumberFormatterCurrencyStyle];
//this will add a decimal point again if you put this in the code above
```
Play around with the Esc key to see all formatting available for setNumberStyle or other methods. | Set the `labelFormatter` property on the axis to a new formatter. This is a standard NSNumberFormatter object. See [Apple's class documentation](http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Classes/NSNumberFormatter_Class/Reference/Reference.html) for details on the options available. |
34,759,999 | I have a windows application developed in c#, starts automatically everyday when machine starts. By using this windows c# application we are launching an html application to show all the details which reads from this c# application. And this windows application before launches html, reads updated data from server if any available.
My issue is when machine starts application also starts and unable to connect to server and goes idle and launches html application and the html application will not be able to communicate and get any data from the windows application.
But when manually again stop and start the windows application it start connect to server and launch html with proper data.
In registry settings we have give winlogon as c:\myapplication.exe.
Is there any way to make my c# application should wait until the machine starts completely and load all network connections in the machine and later the application starts.
Any suggestions.
Regards
Sangeetha | 2016/01/13 | [
"https://Stackoverflow.com/questions/34759999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2081969/"
] | I'd say your selector is wrong, you use the element tag `<chart></chart>`, but in the directive declaration you use `[chart]`, which selects an attribute. This will leave you with 2 possible options:
**Option 1**
```
@Directive({
selector: 'chart', //remove the straight brackets to select a tag
...
})
```
**Option 2**
```
<div chart>...</div> <!-- now you can use the attribute selector -->
``` | Two things I did. (problem not solved yet.)
1. This was the final code that I used in template.html
`<div id="chartdiv" chart2 style="width:100%; height:600px;"></div>`
2. The selector stayed the same.
`selector: '[chart2]'`
3. I also ran `npm start` to compile the TypeScript. Which I think might have helped.
Hopefully this will help someone. |
34,759,999 | I have a windows application developed in c#, starts automatically everyday when machine starts. By using this windows c# application we are launching an html application to show all the details which reads from this c# application. And this windows application before launches html, reads updated data from server if any available.
My issue is when machine starts application also starts and unable to connect to server and goes idle and launches html application and the html application will not be able to communicate and get any data from the windows application.
But when manually again stop and start the windows application it start connect to server and launch html with proper data.
In registry settings we have give winlogon as c:\myapplication.exe.
Is there any way to make my c# application should wait until the machine starts completely and load all network connections in the machine and later the application starts.
Any suggestions.
Regards
Sangeetha | 2016/01/13 | [
"https://Stackoverflow.com/questions/34759999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2081969/"
] | Thanks to the help of customer support at AmCharts.
A working plunker can be found [here](http://plnkr.co/edit/YwAy0dOpnS2yPSd6HWth?p=preview).
The key issue was this line of code: Instead of doing this:
```
AmCharts.ready(function () {
createStockChart();
});
```
Instead do this:
```
if (AmCharts.isReady) {
createStockChart();
} else {
AmCharts.ready(function () {
createStockChart();
});
}
```
UPDATE:
Here is the extended answer using Angular Service to get the data for the chart. [Angular2 HTTP Providers, get a string from JSON for Amcharts](https://stackoverflow.com/questions/35658236/angular2-http-providers-get-a-string-from-json-for-amcharts) | I'd say your selector is wrong, you use the element tag `<chart></chart>`, but in the directive declaration you use `[chart]`, which selects an attribute. This will leave you with 2 possible options:
**Option 1**
```
@Directive({
selector: 'chart', //remove the straight brackets to select a tag
...
})
```
**Option 2**
```
<div chart>...</div> <!-- now you can use the attribute selector -->
``` |
34,759,999 | I have a windows application developed in c#, starts automatically everyday when machine starts. By using this windows c# application we are launching an html application to show all the details which reads from this c# application. And this windows application before launches html, reads updated data from server if any available.
My issue is when machine starts application also starts and unable to connect to server and goes idle and launches html application and the html application will not be able to communicate and get any data from the windows application.
But when manually again stop and start the windows application it start connect to server and launch html with proper data.
In registry settings we have give winlogon as c:\myapplication.exe.
Is there any way to make my c# application should wait until the machine starts completely and load all network connections in the machine and later the application starts.
Any suggestions.
Regards
Sangeetha | 2016/01/13 | [
"https://Stackoverflow.com/questions/34759999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2081969/"
] | **1. Installation**
```
npm install amcharts/amcharts3-angular2 --save
```
**2. In your HTML file, load the amCharts library using tags:**
```
<script src="https://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="https://www.amcharts.com/lib/3/serial.js"></script>
<script src="https://www.amcharts.com/lib/3/themes/light.js"></script>
```
**3. In your app module, import the AmChartsModule module and add it to the imports:**
```
import { AmChartsModule } from "amcharts3-angular2";
@NgModule({
imports: [
AmChartsModule
]
})
export class AppModule {}
```
**4. Inject the AmChartsService into your app component, create a element with an id, then use the makeChart method to create the chart:**
```
import { AmChartsService } from "amcharts3-angular2";
@Component({
template: `<div id="chartdiv" [style.width.%]="100" [style.height.px]="500"></div>`
})
export class AppComponent {
private chart: any;
constructor(private AmCharts: AmChartsService) {}
ngOnInit() {
this.chart = this.AmCharts.makeChart("chartdiv", {
"type": "serial",
"theme": "light",
"dataProvider": []
...
});
}
ngOnDestroy() {
this.AmCharts.destroyChart(this.chart);
}
}
```
The first argument to makeChart must be the same as the 's id. The id can be whatever you want, but if you display multiple charts each chart must have a different id
When you are finished with the chart, you must call the destroyChart method. It's good to put this inside the ngOnDestroy method.
**5. If you want to change the chart after the chart has been created, you must make the changes using the updateChart method:**
```
// This must be called when making any changes to the chart
this.AmCharts.updateChart(this.chart, () => {
// Change whatever properties you want, add event listeners, etc.
this.chart.dataProvider = [];
this.chart.addListener("init", () => {
// Do stuff after the chart is initialized
});
});
```
*Sample Project:*
<https://github.com/amcharts/amcharts3-angular2> | I'd say your selector is wrong, you use the element tag `<chart></chart>`, but in the directive declaration you use `[chart]`, which selects an attribute. This will leave you with 2 possible options:
**Option 1**
```
@Directive({
selector: 'chart', //remove the straight brackets to select a tag
...
})
```
**Option 2**
```
<div chart>...</div> <!-- now you can use the attribute selector -->
``` |
34,759,999 | I have a windows application developed in c#, starts automatically everyday when machine starts. By using this windows c# application we are launching an html application to show all the details which reads from this c# application. And this windows application before launches html, reads updated data from server if any available.
My issue is when machine starts application also starts and unable to connect to server and goes idle and launches html application and the html application will not be able to communicate and get any data from the windows application.
But when manually again stop and start the windows application it start connect to server and launch html with proper data.
In registry settings we have give winlogon as c:\myapplication.exe.
Is there any way to make my c# application should wait until the machine starts completely and load all network connections in the machine and later the application starts.
Any suggestions.
Regards
Sangeetha | 2016/01/13 | [
"https://Stackoverflow.com/questions/34759999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2081969/"
] | Thanks to the help of customer support at AmCharts.
A working plunker can be found [here](http://plnkr.co/edit/YwAy0dOpnS2yPSd6HWth?p=preview).
The key issue was this line of code: Instead of doing this:
```
AmCharts.ready(function () {
createStockChart();
});
```
Instead do this:
```
if (AmCharts.isReady) {
createStockChart();
} else {
AmCharts.ready(function () {
createStockChart();
});
}
```
UPDATE:
Here is the extended answer using Angular Service to get the data for the chart. [Angular2 HTTP Providers, get a string from JSON for Amcharts](https://stackoverflow.com/questions/35658236/angular2-http-providers-get-a-string-from-json-for-amcharts) | Two things I did. (problem not solved yet.)
1. This was the final code that I used in template.html
`<div id="chartdiv" chart2 style="width:100%; height:600px;"></div>`
2. The selector stayed the same.
`selector: '[chart2]'`
3. I also ran `npm start` to compile the TypeScript. Which I think might have helped.
Hopefully this will help someone. |
34,759,999 | I have a windows application developed in c#, starts automatically everyday when machine starts. By using this windows c# application we are launching an html application to show all the details which reads from this c# application. And this windows application before launches html, reads updated data from server if any available.
My issue is when machine starts application also starts and unable to connect to server and goes idle and launches html application and the html application will not be able to communicate and get any data from the windows application.
But when manually again stop and start the windows application it start connect to server and launch html with proper data.
In registry settings we have give winlogon as c:\myapplication.exe.
Is there any way to make my c# application should wait until the machine starts completely and load all network connections in the machine and later the application starts.
Any suggestions.
Regards
Sangeetha | 2016/01/13 | [
"https://Stackoverflow.com/questions/34759999",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2081969/"
] | **1. Installation**
```
npm install amcharts/amcharts3-angular2 --save
```
**2. In your HTML file, load the amCharts library using tags:**
```
<script src="https://www.amcharts.com/lib/3/amcharts.js"></script>
<script src="https://www.amcharts.com/lib/3/serial.js"></script>
<script src="https://www.amcharts.com/lib/3/themes/light.js"></script>
```
**3. In your app module, import the AmChartsModule module and add it to the imports:**
```
import { AmChartsModule } from "amcharts3-angular2";
@NgModule({
imports: [
AmChartsModule
]
})
export class AppModule {}
```
**4. Inject the AmChartsService into your app component, create a element with an id, then use the makeChart method to create the chart:**
```
import { AmChartsService } from "amcharts3-angular2";
@Component({
template: `<div id="chartdiv" [style.width.%]="100" [style.height.px]="500"></div>`
})
export class AppComponent {
private chart: any;
constructor(private AmCharts: AmChartsService) {}
ngOnInit() {
this.chart = this.AmCharts.makeChart("chartdiv", {
"type": "serial",
"theme": "light",
"dataProvider": []
...
});
}
ngOnDestroy() {
this.AmCharts.destroyChart(this.chart);
}
}
```
The first argument to makeChart must be the same as the 's id. The id can be whatever you want, but if you display multiple charts each chart must have a different id
When you are finished with the chart, you must call the destroyChart method. It's good to put this inside the ngOnDestroy method.
**5. If you want to change the chart after the chart has been created, you must make the changes using the updateChart method:**
```
// This must be called when making any changes to the chart
this.AmCharts.updateChart(this.chart, () => {
// Change whatever properties you want, add event listeners, etc.
this.chart.dataProvider = [];
this.chart.addListener("init", () => {
// Do stuff after the chart is initialized
});
});
```
*Sample Project:*
<https://github.com/amcharts/amcharts3-angular2> | Two things I did. (problem not solved yet.)
1. This was the final code that I used in template.html
`<div id="chartdiv" chart2 style="width:100%; height:600px;"></div>`
2. The selector stayed the same.
`selector: '[chart2]'`
3. I also ran `npm start` to compile the TypeScript. Which I think might have helped.
Hopefully this will help someone. |
762,280 | *Let $D$ be an open set in the complex plane and $f(z)$ be a non-constant holomorphic function on D.
Then $|f(z)|$ has no local maximum on D.*
I can follow the proof fine - usually if I don't understand a theorem intuitively beforehand, the proof will offer the insight necessary. Here, however, I can't see the reason for the Maximum Principle to hold - or perhaps I was just too shallow in my grasp of the proof.
Does anybody have any shillings of wisdom that they would be willing to offer?
Cheers. | 2014/04/20 | [
"https://math.stackexchange.com/questions/762280",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/71562/"
] | Think about what the mean value property of analytic functions says: $f(z\_0) = \dfrac{1}{2\pi} \int\_0^{2\pi} f(z\_0 + re^{i\theta}) d\theta$, where $f$ is analytic in the disk $B\_r(z\_0)$. This says that $f$ is equal to the average of the boundary points. How can $|f(z\_0)|$ be larger than every single point of which it is the average? Thinking discretely, if $a= \dfrac{a\_1 + \cdots + a\_n}{n}$, can $a$ be larger than every point in this sum? No, this is not possible. | holomorphic means, among other things, that the map is open. This is immediate when $f'(z\_0) \neq 0,$ the Inverse Function Theorem says that an open neighborhood of $f(z\_0)$ is covered surjectively. Even when $f'(z\_0) = 0,$ the surjective part still holds, it is just that the map is locally $k$ to one, where $k$ is the first derivative such that $f^{(k)} (z\_0) \neq 0.$ So, there it acts the way $z^3$ acts around the origin, for example.
Anyway, your $D$ is open; assume that the modulus takes its maximum at some point $z\_0 \in D.$ Well then $f$ maps a neighborhood of $z\_0$ onto a neighborhood of $f(z\_0),$ including points with larger modulus than $f(z\_0)$ |
762,280 | *Let $D$ be an open set in the complex plane and $f(z)$ be a non-constant holomorphic function on D.
Then $|f(z)|$ has no local maximum on D.*
I can follow the proof fine - usually if I don't understand a theorem intuitively beforehand, the proof will offer the insight necessary. Here, however, I can't see the reason for the Maximum Principle to hold - or perhaps I was just too shallow in my grasp of the proof.
Does anybody have any shillings of wisdom that they would be willing to offer?
Cheers. | 2014/04/20 | [
"https://math.stackexchange.com/questions/762280",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/71562/"
] | Think about what the mean value property of analytic functions says: $f(z\_0) = \dfrac{1}{2\pi} \int\_0^{2\pi} f(z\_0 + re^{i\theta}) d\theta$, where $f$ is analytic in the disk $B\_r(z\_0)$. This says that $f$ is equal to the average of the boundary points. How can $|f(z\_0)|$ be larger than every single point of which it is the average? Thinking discretely, if $a= \dfrac{a\_1 + \cdots + a\_n}{n}$, can $a$ be larger than every point in this sum? No, this is not possible. | There's another question that's been marked as a duplicate of this one. The other question asks specifically what the difference is between $\Bbb R$ and $\Bbb C$ here - it seems possibly worthwhile to transplant the answer I gave to the other questions:
In either case $$f(z+h)=f(z)+hf'(z)+\dots,$$where the dots indicate higher order terms that are smaller than the last term if $h$ is small. Now if $f'(z)\ne0$ this shows that $|f|$ cannot have a maximum at $z$, because we can choose $h$ to point in the right direction so $|f(z)+hf'(z)|>|f(z)|$.
But what if $f'(z)=0$? Then $$f(z+h)=f(z)+\frac12h^2f''(z)+\dots.$$In the real case $h^2\ge0$, so if $f''(z)$ has the opposite sign to $f(z)$ then adding the $h^2f''(z)$ makes $|f|$ smaller. But in the complex case $h^2$ can point in any direction; so if we choose the direction for $h^2f''(z)$ to be the same as the direction of $f(z)$ then adding the $h^2f''(z)$ again makes $|f|$ larger.
Hmm, slightly more formally: If $f'(z)\ne0$ then $z$ cannot be a maximum for $|f|$, for very much the same reason in the real and complex case. Suppose that $f'(z)=0$, $f''(z)\ne0$. Now in the real case, if $f(z)>0$ and $f''(z)<0$ then $$|f(z)+\frac12 h^2f''(z)|
=|f(z)|-\frac12h^2|f''(z)|<|f(z)|$$ for all small $h\ne0$, regardless of whether $h$ is positive or negative, the only two directions available. But that can't happen in the complex case: If $f''(z)\ne0$ then there exists $\alpha$ so that if $h=re^{i\alpha}$ then $$|f(z)+\frac12h^2f''(z)|=|f(z)|+r^2|f''(z)|>|f(z)|$$ for all small $r>0$. |
762,280 | *Let $D$ be an open set in the complex plane and $f(z)$ be a non-constant holomorphic function on D.
Then $|f(z)|$ has no local maximum on D.*
I can follow the proof fine - usually if I don't understand a theorem intuitively beforehand, the proof will offer the insight necessary. Here, however, I can't see the reason for the Maximum Principle to hold - or perhaps I was just too shallow in my grasp of the proof.
Does anybody have any shillings of wisdom that they would be willing to offer?
Cheers. | 2014/04/20 | [
"https://math.stackexchange.com/questions/762280",
"https://math.stackexchange.com",
"https://math.stackexchange.com/users/71562/"
] | holomorphic means, among other things, that the map is open. This is immediate when $f'(z\_0) \neq 0,$ the Inverse Function Theorem says that an open neighborhood of $f(z\_0)$ is covered surjectively. Even when $f'(z\_0) = 0,$ the surjective part still holds, it is just that the map is locally $k$ to one, where $k$ is the first derivative such that $f^{(k)} (z\_0) \neq 0.$ So, there it acts the way $z^3$ acts around the origin, for example.
Anyway, your $D$ is open; assume that the modulus takes its maximum at some point $z\_0 \in D.$ Well then $f$ maps a neighborhood of $z\_0$ onto a neighborhood of $f(z\_0),$ including points with larger modulus than $f(z\_0)$ | There's another question that's been marked as a duplicate of this one. The other question asks specifically what the difference is between $\Bbb R$ and $\Bbb C$ here - it seems possibly worthwhile to transplant the answer I gave to the other questions:
In either case $$f(z+h)=f(z)+hf'(z)+\dots,$$where the dots indicate higher order terms that are smaller than the last term if $h$ is small. Now if $f'(z)\ne0$ this shows that $|f|$ cannot have a maximum at $z$, because we can choose $h$ to point in the right direction so $|f(z)+hf'(z)|>|f(z)|$.
But what if $f'(z)=0$? Then $$f(z+h)=f(z)+\frac12h^2f''(z)+\dots.$$In the real case $h^2\ge0$, so if $f''(z)$ has the opposite sign to $f(z)$ then adding the $h^2f''(z)$ makes $|f|$ smaller. But in the complex case $h^2$ can point in any direction; so if we choose the direction for $h^2f''(z)$ to be the same as the direction of $f(z)$ then adding the $h^2f''(z)$ again makes $|f|$ larger.
Hmm, slightly more formally: If $f'(z)\ne0$ then $z$ cannot be a maximum for $|f|$, for very much the same reason in the real and complex case. Suppose that $f'(z)=0$, $f''(z)\ne0$. Now in the real case, if $f(z)>0$ and $f''(z)<0$ then $$|f(z)+\frac12 h^2f''(z)|
=|f(z)|-\frac12h^2|f''(z)|<|f(z)|$$ for all small $h\ne0$, regardless of whether $h$ is positive or negative, the only two directions available. But that can't happen in the complex case: If $f''(z)\ne0$ then there exists $\alpha$ so that if $h=re^{i\alpha}$ then $$|f(z)+\frac12h^2f''(z)|=|f(z)|+r^2|f''(z)|>|f(z)|$$ for all small $r>0$. |
19,943,615 | My friend recently allowed me to use his web hosting for a site I have, and he went and got all the ftp and database setup and I can do the ftp for it, but, when I try to go into the database using something like heidisql or mysql toolkit it gives me an error:
Host'XX-XXX-XXX-XXXX.dhcp.unas.al.charter.com' is not allowed to connect to this mysql server. I called charter and they said they couldn't do anything on their end so I am assuming it may be a setting in his cpanel on his server to allow remote access to it?
Or if I'm completely off, how would this work?
EDIT: I would like to know how to get it to work by going to a cmd line and running a local mysql.exe and then connecting -u user -p -h xxx.xxx.x.xx | 2013/11/13 | [
"https://Stackoverflow.com/questions/19943615",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2701687/"
] | No, Charter wouldn't be able to do anything about it, because that's an error coming [directly from the MySQL server](http://dev.mysql.com/doc/refman/5.6/en/error-messages-server.html#error_er_host_not_privileged), because your IP address is not among the hosts configured for access.
```
Error: 1130 SQLSTATE: HY000 (ER_HOST_NOT_PRIVILEGED)
Message: Host '%s' is not allowed to connect to this MySQL server
```
The correct solution involves understanding that the [MySQL Access Privilege System](http://dev.mysql.com/doc/refman/5.6/en/account-names.html) treats username + host IP address or name where the connection is originating as an "account" -- not username by itself.
```
'foo'@'localhost' # username foo connecting from the server machine
'foo'@'192.168.1.1' # username foo from IP address 192.168.1.1
'foo'@'192.168.1.%' # username foo from IP address 192.168.1.*
'foo'@'192.168.%' # username foo from IP address 192.168.*.*
'foo'@'%' # username foo from any IP address
```
In MySQL's privilege system, these are 5 different "users," potentially with 5 different passwords. If no users are allowed to connect from your IP address or any wildcard address that matches yours, this would be the message you'd get. This is explained further, [here](http://dev.mysql.com/doc/refman/5.6/en/connection-access.html) and [here](http://dev.mysql.com/doc/refman/5.6/en/access-denied.html).
There is nothing you can do with the `mysql` command line client to override the server's configuration, though you could use an SSH tunnel so that the server would think you are connecting from `localhost` or another trusted host, as was suggested in a comment.
The fix it is for your friend to grant privileges to you at your address [with a `GRANT` statement](http://dev.mysql.com/doc/refman/5.6/en/grant.html). cPanel might provide an interface to do this -- I have no idea, since I work directly with MySQL -- but if it does, that would be cPanel essentially writing the same `GRANT` statement and sending it to the MySQL server to be executed. | Error 1130 is a networking error. The server cannot resolve the hostname of the client. Or the host is not allowed to connect to the MySQL server.
There are basically 2 categories of possible reasons:
* The simple one:
In MySQL a user a user is specified using BOTH the user name and the host from where the user may connect. If no user has been created where the host-part (using wildcards or not) mathces the host of the client trying to connect MySQL will return this error.
* The tricky ones:
1)
Your hosts file is damaged or invalid. Various vira and spyware attack and alter the host file in various ways. For instance if the hosts file does not contain the line
127.0.0.1 localhost
'localhost' cant' be resolved as pointing to ip 127.0.0.1. On some larger corporate network it is widely used to "roll out" host files to all clients with symbolic names (like 'mysqlserver', 'mailserver' etc.) for important machines on the network and the corresponding ip's. Check with your admin that you got the right file!
2)
If you use the Windows network name as hostname, it may be a network configuration problem. Try using the ip instead.
This link can be helpful:
<http://faq.webyog.com/content/23/36/en/i-get-error-1130-host-is-not-allowed-to-connect-or-access-denied-or-could-not-connect-.html> |
25,663,633 | I've two site, when I used the google map.
The code is the same, and I use the same apy key, generater in
<https://console.developers.google.com/project/579752013451/apiui/credential?authuser=0>
In the box referers I've specified both domains using the same method (*.domain.it/*), one for line.
In frist site the map run, in the second, the map say "Google ha disabilitato l'utilizzo della API di Google Maps per questa applicazione. La chiave fornita non è una Chiave API Google valida o non è autorizzata per l'API Javascript v3 di Google Maps su questo sito. Se sei il proprietario di questa applicazione, puoi trovare ulteriori informazioni su come ottenere una chiave valida qui: <https://developers.google.com/maps/documentation/javascript/tutorial#api_key>"
I tried to swap the order of the two domains, but the result is same.
What did I do wrong? | 2014/09/04 | [
"https://Stackoverflow.com/questions/25663633",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4007587/"
] | By moving the declaration of the variable outside the try/catch you would make it exist both inside the scope (context) of the try and the catch.
However I'm not sure what you are trying to accomplish as the only way you will in this case come into the catch is if you fail to try to open the file, and in that case you cannot write to it in the catch
```
StreamWriter file1 = null; // declare outside try/catch
try
{
file1 = new StreamWriter(newPath);
}
catch (IOException)
{
if(file1 != null){
file1.Write(textBox1.Text);
file1.Close();
}
throw;
}
```
Moving the variable so that it is declared before the try catch does not however make it global, it simply makes it so it exists through the entire scope of the remaining code in that method you are in.
If you want to create a global variable inside a class you would do something like this
```
public class MyClass{
public string _ClassGlobalVariable;
public void MethodToWorkIn(){
// this method knows about _ClassGlobalVariable and can work with it
_ClassGlobalVariable = "a string";
}
}
``` | In C# things are declared within a scope and only available within that scope
You declare your variable File1 within the try scope, while it's initialisation is well placed (it could throw an exception), what you want is to declare it beforehand so that in the outer scope (in which both the try and catch are) so that it is available to both.
```
StreamWriter File1 = null;
try
{
// Try to create the StreamWriter
File1 = new StreamWriter(newPath);
}
catch (IOException)
{
/* Catch System.IO.IOException was unhandled
Message=The process cannot access the file 'C:\Users\Dilan V 8
*/ Desktop\TextFile1.txt' because it is being used by another process.
File1.Write(textBox1.Text);
File1.Close();
throw;
}
```
However this still is a wrong approach as the only thing you do within your try is to instantiate a new StreamWriter. If you end up in the catch, it means this failed, if it failed you shouldn't touch the object anymore as it wasn't properly constructed (you don't write to it nor close it, you cannot write to it at all, it didn't work).
Basically what you're doing in your code is saying "try to start up the car engine, if it failed, start hitting the Accelerator anyway". |
50,334,961 | I want my ‘p’ to be align to center, and the “#fname label” to get 1/3 of the space and the “#fname input” 2/3
and the next row #mail the same.
Right now everything is scrambled and in the same row,
My [codepen](https://codepen.io/nadav-himmelfarb/pen/BxVYzv) and my code:
```css
body,
html {
height: 100%;
margin: 0;
}
/* styles to make borders not take on extra space */
* {
-moz-box-sizing: border-box;
-webkit-box-sizing: border-box;
box-sizing: border-box;
}
html {
overflow-y: scroll;
/* fix for the scrollbar push issue */
width: 100%;
height: 100%;
}
body {
width: 100%;
height: 100%;
}
/* Browser style reset so they all play nice */
html,
body,
div,
span,
object,
iframe,
h1,
h2,
h3,
h4,
h5,
h6,
p,
blockquote,
pre,
abbr,
address,
cite,
code,
del,
dfn,
em,
img,
ins,
kbd,
q,
samp,
small,
strong,
sub,
sup,
var,
b,
i,
dl,
dt,
dd,
ol,
ul,
li,
fieldset,
form,
label,
legend,
table,
caption,
tbody,
tfoot,
thead,
tr,
th,
td,
time,
mark,
audio,
video {
font-size: 100%;
margin: 0;
padding: 0;
outline: 0 none;
vertical-align: baseline;
}
/* Now we Starting to code */
body {
background-color: #F7FBCC;
}
#title {
text-align: center;
font-size: 40pt;
color: #1A1A1A;
font-family: 'Chivo', sans-serif;
margin-top: 40px;
margin-bottom: 40px;
}
.container {
background-color: #fff;
display: flex;
flex-flow: row wrap;
flex border-radius: 8px;
box-shadow: 0px 2px 8px rgba(29, 31, 32, 0.2);
}
#description {
color: #1a1a1a;
flex: 1;
justify-content: center;
padding-top: 16px;
margin-bottom: 40px;
}
#fname {
display: flex;
flex-flow: row wrap;
margin-top: 40px;
margin-left: 40px;
}
#fname label {
flex: 1;
}
#fname input {
flex: 2;
}
#mail {
display: flex;
flex-flow: row wrap;
margin-top: 40px;
margin-left: 40px;
}
#mail label {
flex: 1;
}
#email input {
flex: 2;
}
```
```html
<head>
<link href="https://fonts.googleapis.com/css?family=Chivo|Roboto" rel="stylesheet">
<meta charset="UTF-8">
</head>
<header>
<div id="title">
<h1> Music - Survey Form </h1>
</div>
</header>
<body>
<form>
<div class="container">
<div id="description">
<p> Let us know what kind of music you like</p>
</div>
<div id="fname">
<label for="name"> Full Name: </label>
<input type="text" id="name" placeholder="What's your name" required>
</div>
<div id="mail">
<label for="email"> Email address: </label>
<input type="text" id="email" placeholder="What's your email" required>
</div>
-->
</div>
<!-- Closing div-container -->
</div>
</body>
```
p.s
If you could tell me if there are lines that I can get rid of, please tell me
Thank you all from advanced :) | 2018/05/14 | [
"https://Stackoverflow.com/questions/50334961",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9769143/"
] | Some of the other dependencies are using a different version of the lib jsr311-api. In my case it was the eureka client. I just added an exclude with this dependency in the pom and it worked
```
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
<exclusions>
<exclusion>
<groupId>javax.ws.rs</groupId>
<artifactId>jsr311-api</artifactId>
</exclusion>
</exclusions>
</dependency>
``` | Please make sure **UriBuilder** class exist on your project. And make sure only one **UriBuilder** class (version) exist in your project. (It can be multiple on your project with different versions.) Different versions can be overlapped.
1. keycloak-admin-client version should same with your keycloak server version.
2. add additional dependency to pom (**versions must be added**, for keycloak 3.0.0.Final => resteasy dependecies 3.5.0.Final works for me. Dependencies must be complied.)
```
<dependency>
<groupId>org.keycloak</groupId>
<artifactId>keycloak-admin-client</artifactId>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-client</artifactId>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-jackson2-provider</artifactId>
</dependency>
<dependency>
<groupId>org.jboss.resteasy</groupId>
<artifactId>resteasy-multipart-provider</artifactId>
</dependency>
```
Note: This is my suggestion, if you are develop multi-layer app. You can divide your project to layers. You can divide your spring boot starter app and keycloak access layer. And use this new project as dependecy.
edit,
see [Failed adding user by keycloak-admin-client to Keycloak due to "unknown resource"](https://stackoverflow.com/questions/38320163/failed-adding-user-by-keycloak-admin-client-to-keycloak-due-to-unknown-resource)
i hope these can helps. |
370,391 | Bestiary is per world:
>
> Bestiary progress is tied to a world, not a character ([source](https://terraria.gamepedia.com/Bestiary)).
>
>
>
And I was thinking about [crimson](https://terraria.gamepedia.com/The_Crimson) and [corruption](https://terraria.gamepedia.com/The_Corruption) creatures, where I can create new world, get missing in my world blocks and just bring them into mine. It should work in theory (confirm?).
But what about other cases? Killing Skeletron before Dungeon Defender? What else?
Is it **always possible**? Or should I be careful with something? | 2020/05/24 | [
"https://gaming.stackexchange.com/questions/370391",
"https://gaming.stackexchange.com",
"https://gaming.stackexchange.com/users/-1/"
] | You can always complete the Bestiary, but you will also need enemies from the other type of evil. This includes the evil-specific bosses, the Eater of Worlds and the Brain of Cthulhu.
You can accomplish this by taking some Ebonstone or Crimstone from a different world, or by purchasing the appropriate seeds from the Dryad. Once in hardmode, the Dryad will sell seeds for the evil that is not native to your world if she's in a graveyard biome, created by placing six or more tombstones close to each other.
Some NPCs and enemies require the ingame Halloween or Christmas events in order to spawn, which are normally only available in accordance to your system's clock. It is possible, however, to trigger a single ingame day of Halloween or Christmas by defeating the Pumpkin Moon or the Frost Moon respectively.
The entries for the only two missable enemies, the Dungeon Guardian and the Tortured Soul, can be obtained by talking to the Clothier and Tax Collector NPCs respectively. Every other enemy that was missable prior to 1.4 (due to being exclusive to worlds pre-hardmode) can now be found in hard mode as well. | It depends on the world. If your world is an old world prior to 1.3, and underground desert biome is not generated, and therefore you are not able to find those creatures. You are unable to create artificial Underground desert biome, but again, you can use TEdit to modify your world and add that biome to finish up the bestiary. |
15,140,388 | Question narrowed to the following:
I have two arrays: `user_in_need` and `active_users`. `user_in_need` is a subset of `active_users`.
```
Array ( [1] [2] [3] [4] [5] [6] [7] [8] [9] ) // active_users
Array ( [3] [7] [9] ) // user_in_need
```
I need to randomly assign to each `user_in_need` a partner from the `active_users` array. The one caveat, I cannot have a user be assigned himself as partner.
This is as far as I've been able to get [doesn't work]:
```
$partners = array();
foreach ($user_in_need as $value) {
$key = array_search($value, $active_users);
unset($active_users[$key]);
shuffle($active_users);
$newpartner = end($active_users);
$partners[$value] = $newpartner;
$user = $value;
$query = "UPDATE users SET target=:partner WHERE uid=:uid";
$query_params = array(':partner' => $newpartner, ':uid' => $user );
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
``` | 2013/02/28 | [
"https://Stackoverflow.com/questions/15140388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/378052/"
] | `async: false` *blocks* the browser. It completely **locks up everything**, including repaints to the DOM.
I strongly **strongly** recommend you don't use `async: false`. It is extremely bad.
You might be able to use `setTimeout` in-between the calls, but they don't guarantee the browser will trigger a repaint.
If you set `async: true` you will not have this problem, but you will likely have to change your code to properly deal with asynchronous behaviour.
---
[async false is so bad jQuery decided to remove it from the API.](https://stackoverflow.com/questions/11448011/jquery-ajax-async-deprecated-what-now) | assuming you know how many calls you make (or can include that as a parameter to the return result) you can simply fire the calls asynchronously, and make them elements in an array on your success callback. When the array gets to the expected size, just render them in sequence. |
15,140,388 | Question narrowed to the following:
I have two arrays: `user_in_need` and `active_users`. `user_in_need` is a subset of `active_users`.
```
Array ( [1] [2] [3] [4] [5] [6] [7] [8] [9] ) // active_users
Array ( [3] [7] [9] ) // user_in_need
```
I need to randomly assign to each `user_in_need` a partner from the `active_users` array. The one caveat, I cannot have a user be assigned himself as partner.
This is as far as I've been able to get [doesn't work]:
```
$partners = array();
foreach ($user_in_need as $value) {
$key = array_search($value, $active_users);
unset($active_users[$key]);
shuffle($active_users);
$newpartner = end($active_users);
$partners[$value] = $newpartner;
$user = $value;
$query = "UPDATE users SET target=:partner WHERE uid=:uid";
$query_params = array(':partner' => $newpartner, ':uid' => $user );
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
``` | 2013/02/28 | [
"https://Stackoverflow.com/questions/15140388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/378052/"
] | Do not use `async: false`.
The code below will run all ajax requests as fast as possible, then append the content to #results in the correct order. DO NOT include `async: false` if you are using the code below.
```
var defArr = [];
for(var i = 0; i < splitnames.length; i++) {
defArr.push( $.ajax({...}) );
}
$.when.apply($,defArr).done(function(){
var $results = $("#results");
$results.empty();
for (var i = 0; i < arguments.length; i++) {
$results.append(arguments[i][0]);
}
});
``` | assuming you know how many calls you make (or can include that as a parameter to the return result) you can simply fire the calls asynchronously, and make them elements in an array on your success callback. When the array gets to the expected size, just render them in sequence. |
15,140,388 | Question narrowed to the following:
I have two arrays: `user_in_need` and `active_users`. `user_in_need` is a subset of `active_users`.
```
Array ( [1] [2] [3] [4] [5] [6] [7] [8] [9] ) // active_users
Array ( [3] [7] [9] ) // user_in_need
```
I need to randomly assign to each `user_in_need` a partner from the `active_users` array. The one caveat, I cannot have a user be assigned himself as partner.
This is as far as I've been able to get [doesn't work]:
```
$partners = array();
foreach ($user_in_need as $value) {
$key = array_search($value, $active_users);
unset($active_users[$key]);
shuffle($active_users);
$newpartner = end($active_users);
$partners[$value] = $newpartner;
$user = $value;
$query = "UPDATE users SET target=:partner WHERE uid=:uid";
$query_params = array(':partner' => $newpartner, ':uid' => $user );
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
``` | 2013/02/28 | [
"https://Stackoverflow.com/questions/15140388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/378052/"
] | `async: false` *blocks* the browser. It completely **locks up everything**, including repaints to the DOM.
I strongly **strongly** recommend you don't use `async: false`. It is extremely bad.
You might be able to use `setTimeout` in-between the calls, but they don't guarantee the browser will trigger a repaint.
If you set `async: true` you will not have this problem, but you will likely have to change your code to properly deal with asynchronous behaviour.
---
[async false is so bad jQuery decided to remove it from the API.](https://stackoverflow.com/questions/11448011/jquery-ajax-async-deprecated-what-now) | For one, you seem to have an extra curly brace there.
But more to the issue at hand, if you just want to monitor the progress would it work for you to use [`setTimeout`](https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout)?
-- update --
I think I get what you're trying to do. And if I'm not mistaken, you could refactor a little, and then use a closure and an object with the names as the keys. Something like this:
```
function getNames()
{
var names = $('#thenames').val();
var splitnames = names.split(',');
var myData = {};
for(var i = 0; i < splitnames.length; i++)
{
(function(name)
{ return function(){
$.ajax({
type: 'GET',
url: '/acert/secure/people/namesservice/getnamesajax.jsp',
data: { usernames: name},
success: function(data) { myData[name] = data; updateNames(); }
});
})( splitnames[i] )
}
}
```
What this basically does is that it sets up a bunch of ajax calls right away, that weird bit in the middle with the (function(){})() makes sure you don't end up fetching the last value that `name` gets set to when the loop finishes. Everything gets saved to `myData`, I figured once everyone is loaded you could check to see if all the names you have in `splitnames` are in `myData` with the `updateNames` function. Something like
```
var count = 0;
for ( var i = 0; i < splitnames.length; i++ )
{
count += myData[splitnames[i]] != null ? 1 : 0;
}
if (count == splitnames.length)
{
// write the names to the screen
}
```
Does that make sense?
But, to be honest, the best approach would probably be to change the getnamesajax.jsp so that it accepts all the names, and then gives you back the info you need in the order you need. If that was an option, that would be best since you would only need to make one ajax call. |
15,140,388 | Question narrowed to the following:
I have two arrays: `user_in_need` and `active_users`. `user_in_need` is a subset of `active_users`.
```
Array ( [1] [2] [3] [4] [5] [6] [7] [8] [9] ) // active_users
Array ( [3] [7] [9] ) // user_in_need
```
I need to randomly assign to each `user_in_need` a partner from the `active_users` array. The one caveat, I cannot have a user be assigned himself as partner.
This is as far as I've been able to get [doesn't work]:
```
$partners = array();
foreach ($user_in_need as $value) {
$key = array_search($value, $active_users);
unset($active_users[$key]);
shuffle($active_users);
$newpartner = end($active_users);
$partners[$value] = $newpartner;
$user = $value;
$query = "UPDATE users SET target=:partner WHERE uid=:uid";
$query_params = array(':partner' => $newpartner, ':uid' => $user );
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
``` | 2013/02/28 | [
"https://Stackoverflow.com/questions/15140388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/378052/"
] | `async: false` *blocks* the browser. It completely **locks up everything**, including repaints to the DOM.
I strongly **strongly** recommend you don't use `async: false`. It is extremely bad.
You might be able to use `setTimeout` in-between the calls, but they don't guarantee the browser will trigger a repaint.
If you set `async: true` you will not have this problem, but you will likely have to change your code to properly deal with asynchronous behaviour.
---
[async false is so bad jQuery decided to remove it from the API.](https://stackoverflow.com/questions/11448011/jquery-ajax-async-deprecated-what-now) | Do not use `async: false`.
The code below will run all ajax requests as fast as possible, then append the content to #results in the correct order. DO NOT include `async: false` if you are using the code below.
```
var defArr = [];
for(var i = 0; i < splitnames.length; i++) {
defArr.push( $.ajax({...}) );
}
$.when.apply($,defArr).done(function(){
var $results = $("#results");
$results.empty();
for (var i = 0; i < arguments.length; i++) {
$results.append(arguments[i][0]);
}
});
``` |
15,140,388 | Question narrowed to the following:
I have two arrays: `user_in_need` and `active_users`. `user_in_need` is a subset of `active_users`.
```
Array ( [1] [2] [3] [4] [5] [6] [7] [8] [9] ) // active_users
Array ( [3] [7] [9] ) // user_in_need
```
I need to randomly assign to each `user_in_need` a partner from the `active_users` array. The one caveat, I cannot have a user be assigned himself as partner.
This is as far as I've been able to get [doesn't work]:
```
$partners = array();
foreach ($user_in_need as $value) {
$key = array_search($value, $active_users);
unset($active_users[$key]);
shuffle($active_users);
$newpartner = end($active_users);
$partners[$value] = $newpartner;
$user = $value;
$query = "UPDATE users SET target=:partner WHERE uid=:uid";
$query_params = array(':partner' => $newpartner, ':uid' => $user );
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
``` | 2013/02/28 | [
"https://Stackoverflow.com/questions/15140388",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/378052/"
] | Do not use `async: false`.
The code below will run all ajax requests as fast as possible, then append the content to #results in the correct order. DO NOT include `async: false` if you are using the code below.
```
var defArr = [];
for(var i = 0; i < splitnames.length; i++) {
defArr.push( $.ajax({...}) );
}
$.when.apply($,defArr).done(function(){
var $results = $("#results");
$results.empty();
for (var i = 0; i < arguments.length; i++) {
$results.append(arguments[i][0]);
}
});
``` | For one, you seem to have an extra curly brace there.
But more to the issue at hand, if you just want to monitor the progress would it work for you to use [`setTimeout`](https://developer.mozilla.org/en-US/docs/DOM/window.setTimeout)?
-- update --
I think I get what you're trying to do. And if I'm not mistaken, you could refactor a little, and then use a closure and an object with the names as the keys. Something like this:
```
function getNames()
{
var names = $('#thenames').val();
var splitnames = names.split(',');
var myData = {};
for(var i = 0; i < splitnames.length; i++)
{
(function(name)
{ return function(){
$.ajax({
type: 'GET',
url: '/acert/secure/people/namesservice/getnamesajax.jsp',
data: { usernames: name},
success: function(data) { myData[name] = data; updateNames(); }
});
})( splitnames[i] )
}
}
```
What this basically does is that it sets up a bunch of ajax calls right away, that weird bit in the middle with the (function(){})() makes sure you don't end up fetching the last value that `name` gets set to when the loop finishes. Everything gets saved to `myData`, I figured once everyone is loaded you could check to see if all the names you have in `splitnames` are in `myData` with the `updateNames` function. Something like
```
var count = 0;
for ( var i = 0; i < splitnames.length; i++ )
{
count += myData[splitnames[i]] != null ? 1 : 0;
}
if (count == splitnames.length)
{
// write the names to the screen
}
```
Does that make sense?
But, to be honest, the best approach would probably be to change the getnamesajax.jsp so that it accepts all the names, and then gives you back the info you need in the order you need. If that was an option, that would be best since you would only need to make one ajax call. |
48,958,818 | Is there any way I could find how much bytes are allocated for `RandomArray` in this code
```
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *RandomArray;
int n;
srand(time(NULL));
RandomArray=malloc(sizeof *RandomArray * (rand()%11));
printf("%d %d",sizeof(RandomArray),sizeof(*RandomArray));
return 0;
}
```
Also I don't know whether above code will ever have any kind of practical usage. But I am looking from programming perspective. | 2018/02/24 | [
"https://Stackoverflow.com/questions/48958818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9399889/"
] | Ah this is experimental code. Interesting things are there.
* You will allocate memory for `N` integers where `N` is between `0` to `10` including `0` and `10`.
* Then you applied `sizeof` to the pointer (`int*`) and what it points to (`int`). It won't matter how much memory you allocate. The output from this line will be same.
* There is no error check here. if it was you couldn't tell whether it is successful entirely surely because `rand()` may give `0` as result. You need to store it somewhere and check whether it is `0` because on that case `malloc` may or may not return `NULL`.
* Printing what `sizeof` returns should be done using `%zu` format specifier. It returns `size_t`.
>
> * To be more clear remember it is a pointer pointing to dynamically allocated memory. `RandomArray` is not an array - it is an pointer pointing to contiguous memory. That doesn't make it array. It is still a pointer. And the `sizeof` trick that you wanted to apply thinking `RandomArray` is an array won't work. In general we keep track of it - using some variable. But here you don't know how much memory you allocated.
>
>
>
* `malloc` may return `NULL` when you pass `0` to it. Handle that case separately. In case you get `sz!=0` and get `NULL` in `RandomArray` throw error.
```
size_t sz = rand()%11;
RandomArray = malloc(sz);
if(!RandomArray && sz){
perror("malloc");
exit(EXIT_FAILURE);
}
```
After all this talk - the short answer is, with this setup *there is no use of the code (code you have written) so far*. You don't know what `rand()` returned on that case inside malloc. | Yes, by saving the size in a variable:
```
int main()
{
int *RandomArray;
int n;
srand(time(NULL));
size_t size = rand() % 11;
if(size == 0)
{
fprintf(stderr, "Size 0, no point in allocating memory\n");
return 1;
}
RandomArray = malloc(size * sizeof *RandomArray)
if(RandomArray == NULL)
{
fprintf(stderr, "no memory left\n");
return 1;
}
printf("%zu %zu\n", sizeof(RandomArray), size);
// don't forget to free the memory
free(RandomArray);
return 0;
}
```
Note that `sizeof(RandomArray)` returns you the size that a pointer to `int`
needs to be stored in memory, and `sizeof(*RandomArray)` returns you the size of
an `int`.
Also don't forget to free the memory. |
48,958,818 | Is there any way I could find how much bytes are allocated for `RandomArray` in this code
```
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *RandomArray;
int n;
srand(time(NULL));
RandomArray=malloc(sizeof *RandomArray * (rand()%11));
printf("%d %d",sizeof(RandomArray),sizeof(*RandomArray));
return 0;
}
```
Also I don't know whether above code will ever have any kind of practical usage. But I am looking from programming perspective. | 2018/02/24 | [
"https://Stackoverflow.com/questions/48958818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9399889/"
] | Yes, by saving the size in a variable:
```
int main()
{
int *RandomArray;
int n;
srand(time(NULL));
size_t size = rand() % 11;
if(size == 0)
{
fprintf(stderr, "Size 0, no point in allocating memory\n");
return 1;
}
RandomArray = malloc(size * sizeof *RandomArray)
if(RandomArray == NULL)
{
fprintf(stderr, "no memory left\n");
return 1;
}
printf("%zu %zu\n", sizeof(RandomArray), size);
// don't forget to free the memory
free(RandomArray);
return 0;
}
```
Note that `sizeof(RandomArray)` returns you the size that a pointer to `int`
needs to be stored in memory, and `sizeof(*RandomArray)` returns you the size of
an `int`.
Also don't forget to free the memory. | `sizeof(RandomArray)` always results in 4 bytes(equal to pointer size), if you want to find how many bytes allocated for `RandomArray`
```
/* Since its implimentation dependent, so I'm not
advising you to access RandomArray[-1], also proper type casting needed */
printf("memory allocated = %d \n",RandomArray[-1]);
```
From
>
> The C programming language by Denis Ritchie & Kernighan
>
>
>
```
typedef long Align; /* for alignment to long boundary */
union header { /* block header */
struct {
union header *ptr; /* next block if on free list */
unsigned size; /* size of this block */
} s;
Align x; /* force alignment of blocks */
};
typedef union header Header;
```
The `Align` field is never used;**it just forces each header to be aligned on a worst-case boundary**.
In `malloc`,the requested size in characters is rounded up to the proper number of *header-sized* units; the block that will be allocated contains
one more unit, for the `header` itself, and this is the value recorded in the
`size` field of the header.
**The pointer returned by malloc points at the free space, not at the header itself**.
```
RandomArray[-1]
-----------------------------------------
| | SIZE | |
-----------------------------------------
RandomArray
-> a block returned by malloc
``` |
48,958,818 | Is there any way I could find how much bytes are allocated for `RandomArray` in this code
```
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *RandomArray;
int n;
srand(time(NULL));
RandomArray=malloc(sizeof *RandomArray * (rand()%11));
printf("%d %d",sizeof(RandomArray),sizeof(*RandomArray));
return 0;
}
```
Also I don't know whether above code will ever have any kind of practical usage. But I am looking from programming perspective. | 2018/02/24 | [
"https://Stackoverflow.com/questions/48958818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9399889/"
] | Yes, by saving the size in a variable:
```
int main()
{
int *RandomArray;
int n;
srand(time(NULL));
size_t size = rand() % 11;
if(size == 0)
{
fprintf(stderr, "Size 0, no point in allocating memory\n");
return 1;
}
RandomArray = malloc(size * sizeof *RandomArray)
if(RandomArray == NULL)
{
fprintf(stderr, "no memory left\n");
return 1;
}
printf("%zu %zu\n", sizeof(RandomArray), size);
// don't forget to free the memory
free(RandomArray);
return 0;
}
```
Note that `sizeof(RandomArray)` returns you the size that a pointer to `int`
needs to be stored in memory, and `sizeof(*RandomArray)` returns you the size of
an `int`.
Also don't forget to free the memory. | The `sizeof` operator works at **compile time**, except for the case when the operand is variable length array, and the dynamic memory allocation is **run time** operation.
In the expression:
```
printf("%d %d",sizeof(RandomArray),sizeof(*RandomArray));
```
the type of `RandomArray` is `int *` and the type of `*RandomArray` is `int`.
Hence, the expression is equivalent to:
```
printf("%d %d",sizeof(int *),sizeof(int));
```
for which the `sizeof` will yield the result as an integer constant and therefore, you will get the same result every time irrespective of the size of memory allocate to `RandomArray`.
>
> `How to find the size of dynamic array`
>
>
>
**Keep the track of the *size*** from the point where you are allocating memory dynamically.
---
Beware, you are multiplying the value returned by `rand()%11` to the `sizeof *RandomArray` while allocating memory and `rand()` may return `0` as well which will lead to `malloc(0)`. Good to know that (from [C Standards#7.22.3](http://port70.net/~nsz/c/c11/n1570.html#7.22.3)):
>
> ....If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.
>
>
> |
48,958,818 | Is there any way I could find how much bytes are allocated for `RandomArray` in this code
```
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *RandomArray;
int n;
srand(time(NULL));
RandomArray=malloc(sizeof *RandomArray * (rand()%11));
printf("%d %d",sizeof(RandomArray),sizeof(*RandomArray));
return 0;
}
```
Also I don't know whether above code will ever have any kind of practical usage. But I am looking from programming perspective. | 2018/02/24 | [
"https://Stackoverflow.com/questions/48958818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9399889/"
] | Ah this is experimental code. Interesting things are there.
* You will allocate memory for `N` integers where `N` is between `0` to `10` including `0` and `10`.
* Then you applied `sizeof` to the pointer (`int*`) and what it points to (`int`). It won't matter how much memory you allocate. The output from this line will be same.
* There is no error check here. if it was you couldn't tell whether it is successful entirely surely because `rand()` may give `0` as result. You need to store it somewhere and check whether it is `0` because on that case `malloc` may or may not return `NULL`.
* Printing what `sizeof` returns should be done using `%zu` format specifier. It returns `size_t`.
>
> * To be more clear remember it is a pointer pointing to dynamically allocated memory. `RandomArray` is not an array - it is an pointer pointing to contiguous memory. That doesn't make it array. It is still a pointer. And the `sizeof` trick that you wanted to apply thinking `RandomArray` is an array won't work. In general we keep track of it - using some variable. But here you don't know how much memory you allocated.
>
>
>
* `malloc` may return `NULL` when you pass `0` to it. Handle that case separately. In case you get `sz!=0` and get `NULL` in `RandomArray` throw error.
```
size_t sz = rand()%11;
RandomArray = malloc(sz);
if(!RandomArray && sz){
perror("malloc");
exit(EXIT_FAILURE);
}
```
After all this talk - the short answer is, with this setup *there is no use of the code (code you have written) so far*. You don't know what `rand()` returned on that case inside malloc. | Since the expression `*RandomArray` is of type `int`, `sizeof(*RandomArray)` evaluates to `sizeof(int)`. It does not tell you how much memory was allocated.
When dynamically allocating memory, you need to keep track of how much was allocated yourself. In the case above, you would need to store the random number someplace so you know what that amount is. |
48,958,818 | Is there any way I could find how much bytes are allocated for `RandomArray` in this code
```
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *RandomArray;
int n;
srand(time(NULL));
RandomArray=malloc(sizeof *RandomArray * (rand()%11));
printf("%d %d",sizeof(RandomArray),sizeof(*RandomArray));
return 0;
}
```
Also I don't know whether above code will ever have any kind of practical usage. But I am looking from programming perspective. | 2018/02/24 | [
"https://Stackoverflow.com/questions/48958818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9399889/"
] | Since the expression `*RandomArray` is of type `int`, `sizeof(*RandomArray)` evaluates to `sizeof(int)`. It does not tell you how much memory was allocated.
When dynamically allocating memory, you need to keep track of how much was allocated yourself. In the case above, you would need to store the random number someplace so you know what that amount is. | `sizeof(RandomArray)` always results in 4 bytes(equal to pointer size), if you want to find how many bytes allocated for `RandomArray`
```
/* Since its implimentation dependent, so I'm not
advising you to access RandomArray[-1], also proper type casting needed */
printf("memory allocated = %d \n",RandomArray[-1]);
```
From
>
> The C programming language by Denis Ritchie & Kernighan
>
>
>
```
typedef long Align; /* for alignment to long boundary */
union header { /* block header */
struct {
union header *ptr; /* next block if on free list */
unsigned size; /* size of this block */
} s;
Align x; /* force alignment of blocks */
};
typedef union header Header;
```
The `Align` field is never used;**it just forces each header to be aligned on a worst-case boundary**.
In `malloc`,the requested size in characters is rounded up to the proper number of *header-sized* units; the block that will be allocated contains
one more unit, for the `header` itself, and this is the value recorded in the
`size` field of the header.
**The pointer returned by malloc points at the free space, not at the header itself**.
```
RandomArray[-1]
-----------------------------------------
| | SIZE | |
-----------------------------------------
RandomArray
-> a block returned by malloc
``` |
48,958,818 | Is there any way I could find how much bytes are allocated for `RandomArray` in this code
```
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *RandomArray;
int n;
srand(time(NULL));
RandomArray=malloc(sizeof *RandomArray * (rand()%11));
printf("%d %d",sizeof(RandomArray),sizeof(*RandomArray));
return 0;
}
```
Also I don't know whether above code will ever have any kind of practical usage. But I am looking from programming perspective. | 2018/02/24 | [
"https://Stackoverflow.com/questions/48958818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9399889/"
] | Since the expression `*RandomArray` is of type `int`, `sizeof(*RandomArray)` evaluates to `sizeof(int)`. It does not tell you how much memory was allocated.
When dynamically allocating memory, you need to keep track of how much was allocated yourself. In the case above, you would need to store the random number someplace so you know what that amount is. | The `sizeof` operator works at **compile time**, except for the case when the operand is variable length array, and the dynamic memory allocation is **run time** operation.
In the expression:
```
printf("%d %d",sizeof(RandomArray),sizeof(*RandomArray));
```
the type of `RandomArray` is `int *` and the type of `*RandomArray` is `int`.
Hence, the expression is equivalent to:
```
printf("%d %d",sizeof(int *),sizeof(int));
```
for which the `sizeof` will yield the result as an integer constant and therefore, you will get the same result every time irrespective of the size of memory allocate to `RandomArray`.
>
> `How to find the size of dynamic array`
>
>
>
**Keep the track of the *size*** from the point where you are allocating memory dynamically.
---
Beware, you are multiplying the value returned by `rand()%11` to the `sizeof *RandomArray` while allocating memory and `rand()` may return `0` as well which will lead to `malloc(0)`. Good to know that (from [C Standards#7.22.3](http://port70.net/~nsz/c/c11/n1570.html#7.22.3)):
>
> ....If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.
>
>
> |
48,958,818 | Is there any way I could find how much bytes are allocated for `RandomArray` in this code
```
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *RandomArray;
int n;
srand(time(NULL));
RandomArray=malloc(sizeof *RandomArray * (rand()%11));
printf("%d %d",sizeof(RandomArray),sizeof(*RandomArray));
return 0;
}
```
Also I don't know whether above code will ever have any kind of practical usage. But I am looking from programming perspective. | 2018/02/24 | [
"https://Stackoverflow.com/questions/48958818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9399889/"
] | Ah this is experimental code. Interesting things are there.
* You will allocate memory for `N` integers where `N` is between `0` to `10` including `0` and `10`.
* Then you applied `sizeof` to the pointer (`int*`) and what it points to (`int`). It won't matter how much memory you allocate. The output from this line will be same.
* There is no error check here. if it was you couldn't tell whether it is successful entirely surely because `rand()` may give `0` as result. You need to store it somewhere and check whether it is `0` because on that case `malloc` may or may not return `NULL`.
* Printing what `sizeof` returns should be done using `%zu` format specifier. It returns `size_t`.
>
> * To be more clear remember it is a pointer pointing to dynamically allocated memory. `RandomArray` is not an array - it is an pointer pointing to contiguous memory. That doesn't make it array. It is still a pointer. And the `sizeof` trick that you wanted to apply thinking `RandomArray` is an array won't work. In general we keep track of it - using some variable. But here you don't know how much memory you allocated.
>
>
>
* `malloc` may return `NULL` when you pass `0` to it. Handle that case separately. In case you get `sz!=0` and get `NULL` in `RandomArray` throw error.
```
size_t sz = rand()%11;
RandomArray = malloc(sz);
if(!RandomArray && sz){
perror("malloc");
exit(EXIT_FAILURE);
}
```
After all this talk - the short answer is, with this setup *there is no use of the code (code you have written) so far*. You don't know what `rand()` returned on that case inside malloc. | `sizeof(RandomArray)` always results in 4 bytes(equal to pointer size), if you want to find how many bytes allocated for `RandomArray`
```
/* Since its implimentation dependent, so I'm not
advising you to access RandomArray[-1], also proper type casting needed */
printf("memory allocated = %d \n",RandomArray[-1]);
```
From
>
> The C programming language by Denis Ritchie & Kernighan
>
>
>
```
typedef long Align; /* for alignment to long boundary */
union header { /* block header */
struct {
union header *ptr; /* next block if on free list */
unsigned size; /* size of this block */
} s;
Align x; /* force alignment of blocks */
};
typedef union header Header;
```
The `Align` field is never used;**it just forces each header to be aligned on a worst-case boundary**.
In `malloc`,the requested size in characters is rounded up to the proper number of *header-sized* units; the block that will be allocated contains
one more unit, for the `header` itself, and this is the value recorded in the
`size` field of the header.
**The pointer returned by malloc points at the free space, not at the header itself**.
```
RandomArray[-1]
-----------------------------------------
| | SIZE | |
-----------------------------------------
RandomArray
-> a block returned by malloc
``` |
48,958,818 | Is there any way I could find how much bytes are allocated for `RandomArray` in this code
```
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *RandomArray;
int n;
srand(time(NULL));
RandomArray=malloc(sizeof *RandomArray * (rand()%11));
printf("%d %d",sizeof(RandomArray),sizeof(*RandomArray));
return 0;
}
```
Also I don't know whether above code will ever have any kind of practical usage. But I am looking from programming perspective. | 2018/02/24 | [
"https://Stackoverflow.com/questions/48958818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9399889/"
] | Ah this is experimental code. Interesting things are there.
* You will allocate memory for `N` integers where `N` is between `0` to `10` including `0` and `10`.
* Then you applied `sizeof` to the pointer (`int*`) and what it points to (`int`). It won't matter how much memory you allocate. The output from this line will be same.
* There is no error check here. if it was you couldn't tell whether it is successful entirely surely because `rand()` may give `0` as result. You need to store it somewhere and check whether it is `0` because on that case `malloc` may or may not return `NULL`.
* Printing what `sizeof` returns should be done using `%zu` format specifier. It returns `size_t`.
>
> * To be more clear remember it is a pointer pointing to dynamically allocated memory. `RandomArray` is not an array - it is an pointer pointing to contiguous memory. That doesn't make it array. It is still a pointer. And the `sizeof` trick that you wanted to apply thinking `RandomArray` is an array won't work. In general we keep track of it - using some variable. But here you don't know how much memory you allocated.
>
>
>
* `malloc` may return `NULL` when you pass `0` to it. Handle that case separately. In case you get `sz!=0` and get `NULL` in `RandomArray` throw error.
```
size_t sz = rand()%11;
RandomArray = malloc(sz);
if(!RandomArray && sz){
perror("malloc");
exit(EXIT_FAILURE);
}
```
After all this talk - the short answer is, with this setup *there is no use of the code (code you have written) so far*. You don't know what `rand()` returned on that case inside malloc. | The `sizeof` operator works at **compile time**, except for the case when the operand is variable length array, and the dynamic memory allocation is **run time** operation.
In the expression:
```
printf("%d %d",sizeof(RandomArray),sizeof(*RandomArray));
```
the type of `RandomArray` is `int *` and the type of `*RandomArray` is `int`.
Hence, the expression is equivalent to:
```
printf("%d %d",sizeof(int *),sizeof(int));
```
for which the `sizeof` will yield the result as an integer constant and therefore, you will get the same result every time irrespective of the size of memory allocate to `RandomArray`.
>
> `How to find the size of dynamic array`
>
>
>
**Keep the track of the *size*** from the point where you are allocating memory dynamically.
---
Beware, you are multiplying the value returned by `rand()%11` to the `sizeof *RandomArray` while allocating memory and `rand()` may return `0` as well which will lead to `malloc(0)`. Good to know that (from [C Standards#7.22.3](http://port70.net/~nsz/c/c11/n1570.html#7.22.3)):
>
> ....If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.
>
>
> |
48,958,818 | Is there any way I could find how much bytes are allocated for `RandomArray` in this code
```
#include<stdio.h>
#include<stdlib.h>
int main()
{
int *RandomArray;
int n;
srand(time(NULL));
RandomArray=malloc(sizeof *RandomArray * (rand()%11));
printf("%d %d",sizeof(RandomArray),sizeof(*RandomArray));
return 0;
}
```
Also I don't know whether above code will ever have any kind of practical usage. But I am looking from programming perspective. | 2018/02/24 | [
"https://Stackoverflow.com/questions/48958818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9399889/"
] | `sizeof(RandomArray)` always results in 4 bytes(equal to pointer size), if you want to find how many bytes allocated for `RandomArray`
```
/* Since its implimentation dependent, so I'm not
advising you to access RandomArray[-1], also proper type casting needed */
printf("memory allocated = %d \n",RandomArray[-1]);
```
From
>
> The C programming language by Denis Ritchie & Kernighan
>
>
>
```
typedef long Align; /* for alignment to long boundary */
union header { /* block header */
struct {
union header *ptr; /* next block if on free list */
unsigned size; /* size of this block */
} s;
Align x; /* force alignment of blocks */
};
typedef union header Header;
```
The `Align` field is never used;**it just forces each header to be aligned on a worst-case boundary**.
In `malloc`,the requested size in characters is rounded up to the proper number of *header-sized* units; the block that will be allocated contains
one more unit, for the `header` itself, and this is the value recorded in the
`size` field of the header.
**The pointer returned by malloc points at the free space, not at the header itself**.
```
RandomArray[-1]
-----------------------------------------
| | SIZE | |
-----------------------------------------
RandomArray
-> a block returned by malloc
``` | The `sizeof` operator works at **compile time**, except for the case when the operand is variable length array, and the dynamic memory allocation is **run time** operation.
In the expression:
```
printf("%d %d",sizeof(RandomArray),sizeof(*RandomArray));
```
the type of `RandomArray` is `int *` and the type of `*RandomArray` is `int`.
Hence, the expression is equivalent to:
```
printf("%d %d",sizeof(int *),sizeof(int));
```
for which the `sizeof` will yield the result as an integer constant and therefore, you will get the same result every time irrespective of the size of memory allocate to `RandomArray`.
>
> `How to find the size of dynamic array`
>
>
>
**Keep the track of the *size*** from the point where you are allocating memory dynamically.
---
Beware, you are multiplying the value returned by `rand()%11` to the `sizeof *RandomArray` while allocating memory and `rand()` may return `0` as well which will lead to `malloc(0)`. Good to know that (from [C Standards#7.22.3](http://port70.net/~nsz/c/c11/n1570.html#7.22.3)):
>
> ....If the size of the space requested is zero, the behavior is implementation-defined: either a null pointer is returned, or the behavior is as if the size were some nonzero value, except that the returned pointer shall not be used to access an object.
>
>
> |
3,770,781 | What is the overhead in the string structure that causes sizeof() to be 32 ? | 2010/09/22 | [
"https://Stackoverflow.com/questions/3770781",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/387527/"
] | `std::string` typically contains a buffer for the "small string optimization" --- if the string is less than the buffer size then no heap allocation is required. | It is library dependent. You shouldn't rely on the size of `std::string` objects because it is likely to change in different environments (obviously between different standard library vendors, but also between different versions of the same library).
Keep in mind that `std::string` implementations are written by people who have optimized for a variety of use cases, typically leading to 2 internal representations, one for short strings (small internal buffer) and one for long strings (heap-allocated external buffer). The overhead is associated to holding both of these inside each `std::string` object. |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.